From b27081aa8ef586c7f10f39ad12bad64b631ebb0e Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Sun, 8 Sep 2024 20:24:49 +0200 Subject: [PATCH 001/133] fix: fix(hosts): Improve hosts parser --- handlers/aliases/ast/parser.go | 1 + handlers/hosts/Hosts.g4 | 52 +- handlers/hosts/analyzer/handler_test.go | 6 +- handlers/hosts/analyzer/resolver_test.go | 2 +- handlers/hosts/ast/listener.go | 22 +- handlers/hosts/ast/parser.go | 1 + handlers/hosts/ast/parser/Hosts.interp | 13 +- handlers/hosts/ast/parser/Hosts.tokens | 4 +- handlers/hosts/ast/parser/HostsLexer.interp | 13 +- handlers/hosts/ast/parser/HostsLexer.tokens | 4 +- .../hosts/ast/parser/hosts_base_listener.go | 30 +- handlers/hosts/ast/parser/hosts_lexer.go | 64 +- handlers/hosts/ast/parser/hosts_listener.go | 30 +- handlers/hosts/ast/parser/hosts_parser.go | 1274 ++++++++--------- handlers/hosts/ast/parser_test.go | 20 + .../hosts/lsp/text-document-did-change.go | 4 +- handlers/hosts/lsp/text-document-did-open.go | 28 +- 17 files changed, 722 insertions(+), 846 deletions(-) create mode 100644 handlers/hosts/ast/parser_test.go diff --git a/handlers/aliases/ast/parser.go b/handlers/aliases/ast/parser.go index 2abe986..e0384c9 100644 --- a/handlers/aliases/ast/parser.go +++ b/handlers/aliases/ast/parser.go @@ -77,6 +77,7 @@ func (p *AliasesParser) parseStatement( errors := lexerErrorListener.Errors errors = append(errors, parserErrorListener.Errors...) + errors = append(errors, listener.Errors...) return errors } diff --git a/handlers/hosts/Hosts.g4 b/handlers/hosts/Hosts.g4 index 7690ee3..236674b 100644 --- a/handlers/hosts/Hosts.g4 +++ b/handlers/hosts/Hosts.g4 @@ -13,7 +13,7 @@ aliases ; alias - : DOMAIN + : domain ; hostname @@ -21,17 +21,26 @@ hostname ; domain - : DOMAIN + : (STRING)+ (DOT STRING*)* ; ipAddress : (ipv4Address | ipv6Address) ; +ipv4Address + : (STRING DOT)+ STRING (ipRange? | ipPort?) + ; + +ipv6Address + : (((STRING COLON)+ STRING) | (STRING? COLON COLON STRING)) (ipRange? | ipPort?) + ; + +/* ipv4Address : singleIPv4Address // Allow optional range to tell user ranges are not allowed - ipRange? + (ipRange? | ipPort?) ; singleIPv4Address @@ -42,7 +51,7 @@ singleIPv4Address ipv6Address : singleIPv6Address // Allow optional range to tell user ranges are not allowed - ipRange? + (ipRange? | ipPort?) ; singleIPv6Address @@ -50,19 +59,24 @@ singleIPv6Address ; ipv4Digit - : DIGITS + : STRING ; ipv6Octet - : OCTETS + : STRING ; +*/ ipRange : SLASH ipRangeBits ; ipRangeBits - : DIGITS + : STRING + ; + +ipPort + : COLON STRING ; comment @@ -101,26 +115,6 @@ NEWLINE : [\r]? [\n] ; -DIGITS - : DIGIT+ - ; - -fragment DIGIT - : [0-9] - ; - -OCTETS - : OCTET+ - ; - -fragment OCTET - : [0-9a-fA-F] - ; - -DOMAIN - : ((STRING)+ (DOT [a-zA-Z]+)*) - ; - -fragment STRING - : ~(' ' | '\t' | '\n' | '\r' | '#' | '.') +STRING + : [a-zA-Z0-9_\-]+ ; diff --git a/handlers/hosts/analyzer/handler_test.go b/handlers/hosts/analyzer/handler_test.go index 38e34c1..ce274c6 100644 --- a/handlers/hosts/analyzer/handler_test.go +++ b/handlers/hosts/analyzer/handler_test.go @@ -18,7 +18,7 @@ func TestValidSimpleExampleWorks( errors := parser.Parse(input) if len(errors) != 0 { - t.Errorf("Expected no errors, but got %v", errors) + t.Fatalf("Expected no errors, but got %v", errors) } if !(len(parser.Tree.Entries) == 1) { @@ -85,7 +85,7 @@ func TestValidComplexExampleWorks( errors := parser.Parse(input) if len(errors) != 0 { - t.Errorf("Expected no errors, but got %v", errors) + t.Fatalf("Expected no errors, but got %v", errors) } if !(len(parser.Tree.Entries) == 3) { @@ -120,7 +120,7 @@ func TestInvalidExampleWorks( errors := parser.Parse(input) if len(errors) == 0 { - t.Errorf("Expected errors, but got none") + t.Fatalf("Expected errors, but got none") } if !(len(parser.Tree.Entries) == 1) { diff --git a/handlers/hosts/analyzer/resolver_test.go b/handlers/hosts/analyzer/resolver_test.go index df720e7..0dd8337 100644 --- a/handlers/hosts/analyzer/resolver_test.go +++ b/handlers/hosts/analyzer/resolver_test.go @@ -96,7 +96,7 @@ func TestResolverEntriesWithComplexOverlapping( resolver, errors := createResolverFromParser(parser) if !(len(errors) == 1) { - t.Errorf("Expected 1 error, but got %v", len(errors)) + t.Fatalf("Expected 1 error, but got %v", len(errors)) } if len(resolver.Entries) != 3 { diff --git a/handlers/hosts/ast/listener.go b/handlers/hosts/ast/listener.go index dd26bb6..11d9083 100644 --- a/handlers/hosts/ast/listener.go +++ b/handlers/hosts/ast/listener.go @@ -4,7 +4,9 @@ import ( "config-lsp/common" docvalues "config-lsp/doc-values" parser2 "config-lsp/handlers/hosts/ast/parser" + "errors" "net" + "regexp" "github.com/antlr4-go/antlr/v4" ) @@ -21,7 +23,7 @@ type hostsParserListener struct { } func (s *hostsParserListener) EnterComment(ctx *parser2.CommentContext) { - line := uint32(s.hostsContext.line) + line := s.hostsContext.line s.Parser.CommentLines[line] = struct{}{} } @@ -34,6 +36,8 @@ func (s *hostsParserListener) EnterEntry(ctx *parser2.EntryContext) { } } +var containsPortPattern = regexp.MustCompile(`:[0-9]+$`) + func (s *hostsParserListener) EnterIpAddress(ctx *parser2.IpAddressContext) { location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext) location.ChangeBothLines(s.hostsContext.line) @@ -41,10 +45,18 @@ func (s *hostsParserListener) EnterIpAddress(ctx *parser2.IpAddressContext) { ip := net.ParseIP(ctx.GetText()) if ip == nil { - s.Errors = append(s.Errors, common.LSPError{ - Range: location, - Err: docvalues.InvalidIPAddress{}, - }) + if containsPortPattern.MatchString(ctx.GetText()) { + s.Errors = append(s.Errors, common.LSPError{ + Range: location, + Err: errors.New("Port numbers are not allowed in IP addresses"), + }) + } else { + s.Errors = append(s.Errors, common.LSPError{ + Range: location, + Err: docvalues.InvalidIPAddress{}, + }) + } + return } diff --git a/handlers/hosts/ast/parser.go b/handlers/hosts/ast/parser.go index bfdcf82..42dd6c6 100644 --- a/handlers/hosts/ast/parser.go +++ b/handlers/hosts/ast/parser.go @@ -45,6 +45,7 @@ func (p *HostsParser) parseStatement( ) errors = append(errors, errorListener.Errors...) + errors = append(errors, listener.Errors...) return errors } diff --git a/handlers/hosts/ast/parser/Hosts.interp b/handlers/hosts/ast/parser/Hosts.interp index 9417135..61da0c5 100644 --- a/handlers/hosts/ast/parser/Hosts.interp +++ b/handlers/hosts/ast/parser/Hosts.interp @@ -8,8 +8,6 @@ null null null null -null -null token symbolic names: null @@ -20,9 +18,7 @@ COLON HASHTAG SEPARATOR NEWLINE -DIGITS -OCTETS -DOMAIN +STRING rule names: lineStatement @@ -33,16 +29,13 @@ hostname domain ipAddress ipv4Address -singleIPv4Address ipv6Address -singleIPv6Address -ipv4Digit -ipv6Octet ipRange ipRangeBits +ipPort comment leadingComment atn: -[4, 1, 10, 110, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 2, 5, 7, 5, 2, 6, 7, 6, 2, 7, 7, 7, 2, 8, 7, 8, 2, 9, 7, 9, 2, 10, 7, 10, 2, 11, 7, 11, 2, 12, 7, 12, 2, 13, 7, 13, 2, 14, 7, 14, 2, 15, 7, 15, 2, 16, 7, 16, 1, 0, 3, 0, 36, 8, 0, 1, 0, 1, 0, 3, 0, 40, 8, 0, 1, 0, 3, 0, 43, 8, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 52, 8, 1, 1, 2, 1, 2, 3, 2, 56, 8, 2, 4, 2, 58, 8, 2, 11, 2, 12, 2, 59, 1, 3, 1, 3, 1, 4, 1, 4, 1, 5, 1, 5, 1, 6, 1, 6, 3, 6, 70, 8, 6, 1, 7, 1, 7, 3, 7, 74, 8, 7, 1, 8, 1, 8, 1, 8, 1, 8, 1, 8, 1, 8, 1, 8, 1, 8, 1, 9, 1, 9, 3, 9, 86, 8, 9, 1, 10, 1, 10, 1, 10, 4, 10, 91, 8, 10, 11, 10, 12, 10, 92, 1, 10, 1, 10, 1, 11, 1, 11, 1, 12, 1, 12, 1, 13, 1, 13, 1, 13, 1, 14, 1, 14, 1, 15, 1, 15, 1, 16, 1, 16, 1, 16, 0, 0, 17, 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 0, 0, 102, 0, 35, 1, 0, 0, 0, 2, 46, 1, 0, 0, 0, 4, 57, 1, 0, 0, 0, 6, 61, 1, 0, 0, 0, 8, 63, 1, 0, 0, 0, 10, 65, 1, 0, 0, 0, 12, 69, 1, 0, 0, 0, 14, 71, 1, 0, 0, 0, 16, 75, 1, 0, 0, 0, 18, 83, 1, 0, 0, 0, 20, 90, 1, 0, 0, 0, 22, 96, 1, 0, 0, 0, 24, 98, 1, 0, 0, 0, 26, 100, 1, 0, 0, 0, 28, 103, 1, 0, 0, 0, 30, 105, 1, 0, 0, 0, 32, 107, 1, 0, 0, 0, 34, 36, 5, 6, 0, 0, 35, 34, 1, 0, 0, 0, 35, 36, 1, 0, 0, 0, 36, 37, 1, 0, 0, 0, 37, 39, 3, 2, 1, 0, 38, 40, 5, 6, 0, 0, 39, 38, 1, 0, 0, 0, 39, 40, 1, 0, 0, 0, 40, 42, 1, 0, 0, 0, 41, 43, 3, 32, 16, 0, 42, 41, 1, 0, 0, 0, 42, 43, 1, 0, 0, 0, 43, 44, 1, 0, 0, 0, 44, 45, 5, 0, 0, 1, 45, 1, 1, 0, 0, 0, 46, 47, 3, 12, 6, 0, 47, 48, 5, 6, 0, 0, 48, 51, 3, 8, 4, 0, 49, 50, 5, 6, 0, 0, 50, 52, 3, 4, 2, 0, 51, 49, 1, 0, 0, 0, 51, 52, 1, 0, 0, 0, 52, 3, 1, 0, 0, 0, 53, 55, 3, 6, 3, 0, 54, 56, 5, 6, 0, 0, 55, 54, 1, 0, 0, 0, 55, 56, 1, 0, 0, 0, 56, 58, 1, 0, 0, 0, 57, 53, 1, 0, 0, 0, 58, 59, 1, 0, 0, 0, 59, 57, 1, 0, 0, 0, 59, 60, 1, 0, 0, 0, 60, 5, 1, 0, 0, 0, 61, 62, 5, 10, 0, 0, 62, 7, 1, 0, 0, 0, 63, 64, 3, 10, 5, 0, 64, 9, 1, 0, 0, 0, 65, 66, 5, 10, 0, 0, 66, 11, 1, 0, 0, 0, 67, 70, 3, 14, 7, 0, 68, 70, 3, 18, 9, 0, 69, 67, 1, 0, 0, 0, 69, 68, 1, 0, 0, 0, 70, 13, 1, 0, 0, 0, 71, 73, 3, 16, 8, 0, 72, 74, 3, 26, 13, 0, 73, 72, 1, 0, 0, 0, 73, 74, 1, 0, 0, 0, 74, 15, 1, 0, 0, 0, 75, 76, 3, 22, 11, 0, 76, 77, 5, 3, 0, 0, 77, 78, 3, 22, 11, 0, 78, 79, 5, 3, 0, 0, 79, 80, 3, 22, 11, 0, 80, 81, 5, 3, 0, 0, 81, 82, 3, 22, 11, 0, 82, 17, 1, 0, 0, 0, 83, 85, 3, 20, 10, 0, 84, 86, 3, 26, 13, 0, 85, 84, 1, 0, 0, 0, 85, 86, 1, 0, 0, 0, 86, 19, 1, 0, 0, 0, 87, 88, 3, 24, 12, 0, 88, 89, 5, 4, 0, 0, 89, 91, 1, 0, 0, 0, 90, 87, 1, 0, 0, 0, 91, 92, 1, 0, 0, 0, 92, 90, 1, 0, 0, 0, 92, 93, 1, 0, 0, 0, 93, 94, 1, 0, 0, 0, 94, 95, 3, 24, 12, 0, 95, 21, 1, 0, 0, 0, 96, 97, 5, 8, 0, 0, 97, 23, 1, 0, 0, 0, 98, 99, 5, 9, 0, 0, 99, 25, 1, 0, 0, 0, 100, 101, 5, 2, 0, 0, 101, 102, 3, 28, 14, 0, 102, 27, 1, 0, 0, 0, 103, 104, 5, 8, 0, 0, 104, 29, 1, 0, 0, 0, 105, 106, 5, 1, 0, 0, 106, 31, 1, 0, 0, 0, 107, 108, 5, 1, 0, 0, 108, 33, 1, 0, 0, 0, 10, 35, 39, 42, 51, 55, 59, 69, 73, 85, 92] \ No newline at end of file +[4, 1, 8, 131, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 2, 5, 7, 5, 2, 6, 7, 6, 2, 7, 7, 7, 2, 8, 7, 8, 2, 9, 7, 9, 2, 10, 7, 10, 2, 11, 7, 11, 2, 12, 7, 12, 2, 13, 7, 13, 1, 0, 3, 0, 30, 8, 0, 1, 0, 1, 0, 3, 0, 34, 8, 0, 1, 0, 3, 0, 37, 8, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 46, 8, 1, 1, 2, 1, 2, 3, 2, 50, 8, 2, 4, 2, 52, 8, 2, 11, 2, 12, 2, 53, 1, 3, 1, 3, 1, 4, 1, 4, 1, 5, 4, 5, 61, 8, 5, 11, 5, 12, 5, 62, 1, 5, 1, 5, 5, 5, 67, 8, 5, 10, 5, 12, 5, 70, 9, 5, 5, 5, 72, 8, 5, 10, 5, 12, 5, 75, 9, 5, 1, 6, 1, 6, 3, 6, 79, 8, 6, 1, 7, 1, 7, 4, 7, 83, 8, 7, 11, 7, 12, 7, 84, 1, 7, 1, 7, 3, 7, 89, 8, 7, 1, 7, 3, 7, 92, 8, 7, 3, 7, 94, 8, 7, 1, 8, 1, 8, 4, 8, 98, 8, 8, 11, 8, 12, 8, 99, 1, 8, 1, 8, 3, 8, 104, 8, 8, 1, 8, 1, 8, 1, 8, 3, 8, 109, 8, 8, 1, 8, 3, 8, 112, 8, 8, 1, 8, 3, 8, 115, 8, 8, 3, 8, 117, 8, 8, 1, 9, 1, 9, 1, 9, 1, 10, 1, 10, 1, 11, 1, 11, 1, 11, 1, 12, 1, 12, 1, 13, 1, 13, 1, 13, 0, 0, 14, 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 0, 0, 136, 0, 29, 1, 0, 0, 0, 2, 40, 1, 0, 0, 0, 4, 51, 1, 0, 0, 0, 6, 55, 1, 0, 0, 0, 8, 57, 1, 0, 0, 0, 10, 60, 1, 0, 0, 0, 12, 78, 1, 0, 0, 0, 14, 82, 1, 0, 0, 0, 16, 108, 1, 0, 0, 0, 18, 118, 1, 0, 0, 0, 20, 121, 1, 0, 0, 0, 22, 123, 1, 0, 0, 0, 24, 126, 1, 0, 0, 0, 26, 128, 1, 0, 0, 0, 28, 30, 5, 6, 0, 0, 29, 28, 1, 0, 0, 0, 29, 30, 1, 0, 0, 0, 30, 31, 1, 0, 0, 0, 31, 33, 3, 2, 1, 0, 32, 34, 5, 6, 0, 0, 33, 32, 1, 0, 0, 0, 33, 34, 1, 0, 0, 0, 34, 36, 1, 0, 0, 0, 35, 37, 3, 26, 13, 0, 36, 35, 1, 0, 0, 0, 36, 37, 1, 0, 0, 0, 37, 38, 1, 0, 0, 0, 38, 39, 5, 0, 0, 1, 39, 1, 1, 0, 0, 0, 40, 41, 3, 12, 6, 0, 41, 42, 5, 6, 0, 0, 42, 45, 3, 8, 4, 0, 43, 44, 5, 6, 0, 0, 44, 46, 3, 4, 2, 0, 45, 43, 1, 0, 0, 0, 45, 46, 1, 0, 0, 0, 46, 3, 1, 0, 0, 0, 47, 49, 3, 6, 3, 0, 48, 50, 5, 6, 0, 0, 49, 48, 1, 0, 0, 0, 49, 50, 1, 0, 0, 0, 50, 52, 1, 0, 0, 0, 51, 47, 1, 0, 0, 0, 52, 53, 1, 0, 0, 0, 53, 51, 1, 0, 0, 0, 53, 54, 1, 0, 0, 0, 54, 5, 1, 0, 0, 0, 55, 56, 3, 10, 5, 0, 56, 7, 1, 0, 0, 0, 57, 58, 3, 10, 5, 0, 58, 9, 1, 0, 0, 0, 59, 61, 5, 8, 0, 0, 60, 59, 1, 0, 0, 0, 61, 62, 1, 0, 0, 0, 62, 60, 1, 0, 0, 0, 62, 63, 1, 0, 0, 0, 63, 73, 1, 0, 0, 0, 64, 68, 5, 3, 0, 0, 65, 67, 5, 8, 0, 0, 66, 65, 1, 0, 0, 0, 67, 70, 1, 0, 0, 0, 68, 66, 1, 0, 0, 0, 68, 69, 1, 0, 0, 0, 69, 72, 1, 0, 0, 0, 70, 68, 1, 0, 0, 0, 71, 64, 1, 0, 0, 0, 72, 75, 1, 0, 0, 0, 73, 71, 1, 0, 0, 0, 73, 74, 1, 0, 0, 0, 74, 11, 1, 0, 0, 0, 75, 73, 1, 0, 0, 0, 76, 79, 3, 14, 7, 0, 77, 79, 3, 16, 8, 0, 78, 76, 1, 0, 0, 0, 78, 77, 1, 0, 0, 0, 79, 13, 1, 0, 0, 0, 80, 81, 5, 8, 0, 0, 81, 83, 5, 3, 0, 0, 82, 80, 1, 0, 0, 0, 83, 84, 1, 0, 0, 0, 84, 82, 1, 0, 0, 0, 84, 85, 1, 0, 0, 0, 85, 86, 1, 0, 0, 0, 86, 93, 5, 8, 0, 0, 87, 89, 3, 18, 9, 0, 88, 87, 1, 0, 0, 0, 88, 89, 1, 0, 0, 0, 89, 94, 1, 0, 0, 0, 90, 92, 3, 22, 11, 0, 91, 90, 1, 0, 0, 0, 91, 92, 1, 0, 0, 0, 92, 94, 1, 0, 0, 0, 93, 88, 1, 0, 0, 0, 93, 91, 1, 0, 0, 0, 94, 15, 1, 0, 0, 0, 95, 96, 5, 8, 0, 0, 96, 98, 5, 4, 0, 0, 97, 95, 1, 0, 0, 0, 98, 99, 1, 0, 0, 0, 99, 97, 1, 0, 0, 0, 99, 100, 1, 0, 0, 0, 100, 101, 1, 0, 0, 0, 101, 109, 5, 8, 0, 0, 102, 104, 5, 8, 0, 0, 103, 102, 1, 0, 0, 0, 103, 104, 1, 0, 0, 0, 104, 105, 1, 0, 0, 0, 105, 106, 5, 4, 0, 0, 106, 107, 5, 4, 0, 0, 107, 109, 5, 8, 0, 0, 108, 97, 1, 0, 0, 0, 108, 103, 1, 0, 0, 0, 109, 116, 1, 0, 0, 0, 110, 112, 3, 18, 9, 0, 111, 110, 1, 0, 0, 0, 111, 112, 1, 0, 0, 0, 112, 117, 1, 0, 0, 0, 113, 115, 3, 22, 11, 0, 114, 113, 1, 0, 0, 0, 114, 115, 1, 0, 0, 0, 115, 117, 1, 0, 0, 0, 116, 111, 1, 0, 0, 0, 116, 114, 1, 0, 0, 0, 117, 17, 1, 0, 0, 0, 118, 119, 5, 2, 0, 0, 119, 120, 3, 20, 10, 0, 120, 19, 1, 0, 0, 0, 121, 122, 5, 8, 0, 0, 122, 21, 1, 0, 0, 0, 123, 124, 5, 4, 0, 0, 124, 125, 5, 8, 0, 0, 125, 23, 1, 0, 0, 0, 126, 127, 5, 1, 0, 0, 127, 25, 1, 0, 0, 0, 128, 129, 5, 1, 0, 0, 129, 27, 1, 0, 0, 0, 20, 29, 33, 36, 45, 49, 53, 62, 68, 73, 78, 84, 88, 91, 93, 99, 103, 108, 111, 114, 116] \ No newline at end of file diff --git a/handlers/hosts/ast/parser/Hosts.tokens b/handlers/hosts/ast/parser/Hosts.tokens index c20b3c1..d53da5d 100644 --- a/handlers/hosts/ast/parser/Hosts.tokens +++ b/handlers/hosts/ast/parser/Hosts.tokens @@ -5,9 +5,7 @@ COLON=4 HASHTAG=5 SEPARATOR=6 NEWLINE=7 -DIGITS=8 -OCTETS=9 -DOMAIN=10 +STRING=8 '/'=2 '.'=3 ':'=4 diff --git a/handlers/hosts/ast/parser/HostsLexer.interp b/handlers/hosts/ast/parser/HostsLexer.interp index e92d869..624bd70 100644 --- a/handlers/hosts/ast/parser/HostsLexer.interp +++ b/handlers/hosts/ast/parser/HostsLexer.interp @@ -8,8 +8,6 @@ null null null null -null -null token symbolic names: null @@ -20,9 +18,7 @@ COLON HASHTAG SEPARATOR NEWLINE -DIGITS -OCTETS -DOMAIN +STRING rule names: COMMENTLINE @@ -32,11 +28,6 @@ COLON HASHTAG SEPARATOR NEWLINE -DIGITS -DIGIT -OCTETS -OCTET -DOMAIN STRING channel names: @@ -47,4 +38,4 @@ mode names: DEFAULT_MODE atn: -[4, 0, 10, 83, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 2, 5, 7, 5, 2, 6, 7, 6, 2, 7, 7, 7, 2, 8, 7, 8, 2, 9, 7, 9, 2, 10, 7, 10, 2, 11, 7, 11, 2, 12, 7, 12, 1, 0, 1, 0, 4, 0, 30, 8, 0, 11, 0, 12, 0, 31, 1, 1, 1, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, 1, 4, 1, 5, 4, 5, 43, 8, 5, 11, 5, 12, 5, 44, 1, 6, 3, 6, 48, 8, 6, 1, 6, 1, 6, 1, 7, 4, 7, 53, 8, 7, 11, 7, 12, 7, 54, 1, 8, 1, 8, 1, 9, 4, 9, 60, 8, 9, 11, 9, 12, 9, 61, 1, 10, 1, 10, 1, 11, 4, 11, 67, 8, 11, 11, 11, 12, 11, 68, 1, 11, 1, 11, 4, 11, 73, 8, 11, 11, 11, 12, 11, 74, 5, 11, 77, 8, 11, 10, 11, 12, 11, 80, 9, 11, 1, 12, 1, 12, 0, 0, 13, 1, 1, 3, 2, 5, 3, 7, 4, 9, 5, 11, 6, 13, 7, 15, 8, 17, 0, 19, 9, 21, 0, 23, 10, 25, 0, 1, 0, 8, 2, 0, 10, 10, 13, 13, 2, 0, 9, 9, 32, 32, 1, 0, 13, 13, 1, 0, 10, 10, 1, 0, 48, 57, 3, 0, 48, 57, 65, 70, 97, 102, 2, 0, 65, 90, 97, 122, 5, 0, 9, 10, 13, 13, 32, 32, 35, 35, 46, 46, 87, 0, 1, 1, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, 5, 1, 0, 0, 0, 0, 7, 1, 0, 0, 0, 0, 9, 1, 0, 0, 0, 0, 11, 1, 0, 0, 0, 0, 13, 1, 0, 0, 0, 0, 15, 1, 0, 0, 0, 0, 19, 1, 0, 0, 0, 0, 23, 1, 0, 0, 0, 1, 27, 1, 0, 0, 0, 3, 33, 1, 0, 0, 0, 5, 35, 1, 0, 0, 0, 7, 37, 1, 0, 0, 0, 9, 39, 1, 0, 0, 0, 11, 42, 1, 0, 0, 0, 13, 47, 1, 0, 0, 0, 15, 52, 1, 0, 0, 0, 17, 56, 1, 0, 0, 0, 19, 59, 1, 0, 0, 0, 21, 63, 1, 0, 0, 0, 23, 66, 1, 0, 0, 0, 25, 81, 1, 0, 0, 0, 27, 29, 3, 9, 4, 0, 28, 30, 8, 0, 0, 0, 29, 28, 1, 0, 0, 0, 30, 31, 1, 0, 0, 0, 31, 29, 1, 0, 0, 0, 31, 32, 1, 0, 0, 0, 32, 2, 1, 0, 0, 0, 33, 34, 5, 47, 0, 0, 34, 4, 1, 0, 0, 0, 35, 36, 5, 46, 0, 0, 36, 6, 1, 0, 0, 0, 37, 38, 5, 58, 0, 0, 38, 8, 1, 0, 0, 0, 39, 40, 5, 35, 0, 0, 40, 10, 1, 0, 0, 0, 41, 43, 7, 1, 0, 0, 42, 41, 1, 0, 0, 0, 43, 44, 1, 0, 0, 0, 44, 42, 1, 0, 0, 0, 44, 45, 1, 0, 0, 0, 45, 12, 1, 0, 0, 0, 46, 48, 7, 2, 0, 0, 47, 46, 1, 0, 0, 0, 47, 48, 1, 0, 0, 0, 48, 49, 1, 0, 0, 0, 49, 50, 7, 3, 0, 0, 50, 14, 1, 0, 0, 0, 51, 53, 3, 17, 8, 0, 52, 51, 1, 0, 0, 0, 53, 54, 1, 0, 0, 0, 54, 52, 1, 0, 0, 0, 54, 55, 1, 0, 0, 0, 55, 16, 1, 0, 0, 0, 56, 57, 7, 4, 0, 0, 57, 18, 1, 0, 0, 0, 58, 60, 3, 21, 10, 0, 59, 58, 1, 0, 0, 0, 60, 61, 1, 0, 0, 0, 61, 59, 1, 0, 0, 0, 61, 62, 1, 0, 0, 0, 62, 20, 1, 0, 0, 0, 63, 64, 7, 5, 0, 0, 64, 22, 1, 0, 0, 0, 65, 67, 3, 25, 12, 0, 66, 65, 1, 0, 0, 0, 67, 68, 1, 0, 0, 0, 68, 66, 1, 0, 0, 0, 68, 69, 1, 0, 0, 0, 69, 78, 1, 0, 0, 0, 70, 72, 3, 5, 2, 0, 71, 73, 7, 6, 0, 0, 72, 71, 1, 0, 0, 0, 73, 74, 1, 0, 0, 0, 74, 72, 1, 0, 0, 0, 74, 75, 1, 0, 0, 0, 75, 77, 1, 0, 0, 0, 76, 70, 1, 0, 0, 0, 77, 80, 1, 0, 0, 0, 78, 76, 1, 0, 0, 0, 78, 79, 1, 0, 0, 0, 79, 24, 1, 0, 0, 0, 80, 78, 1, 0, 0, 0, 81, 82, 8, 7, 0, 0, 82, 26, 1, 0, 0, 0, 9, 0, 31, 44, 47, 54, 61, 68, 74, 78, 0] \ No newline at end of file +[4, 0, 8, 46, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 2, 5, 7, 5, 2, 6, 7, 6, 2, 7, 7, 7, 1, 0, 1, 0, 4, 0, 20, 8, 0, 11, 0, 12, 0, 21, 1, 1, 1, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, 1, 4, 1, 5, 4, 5, 33, 8, 5, 11, 5, 12, 5, 34, 1, 6, 3, 6, 38, 8, 6, 1, 6, 1, 6, 1, 7, 4, 7, 43, 8, 7, 11, 7, 12, 7, 44, 0, 0, 8, 1, 1, 3, 2, 5, 3, 7, 4, 9, 5, 11, 6, 13, 7, 15, 8, 1, 0, 5, 2, 0, 10, 10, 13, 13, 2, 0, 9, 9, 32, 32, 1, 0, 13, 13, 1, 0, 10, 10, 5, 0, 45, 45, 48, 57, 65, 90, 95, 95, 97, 122, 49, 0, 1, 1, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, 5, 1, 0, 0, 0, 0, 7, 1, 0, 0, 0, 0, 9, 1, 0, 0, 0, 0, 11, 1, 0, 0, 0, 0, 13, 1, 0, 0, 0, 0, 15, 1, 0, 0, 0, 1, 17, 1, 0, 0, 0, 3, 23, 1, 0, 0, 0, 5, 25, 1, 0, 0, 0, 7, 27, 1, 0, 0, 0, 9, 29, 1, 0, 0, 0, 11, 32, 1, 0, 0, 0, 13, 37, 1, 0, 0, 0, 15, 42, 1, 0, 0, 0, 17, 19, 3, 9, 4, 0, 18, 20, 8, 0, 0, 0, 19, 18, 1, 0, 0, 0, 20, 21, 1, 0, 0, 0, 21, 19, 1, 0, 0, 0, 21, 22, 1, 0, 0, 0, 22, 2, 1, 0, 0, 0, 23, 24, 5, 47, 0, 0, 24, 4, 1, 0, 0, 0, 25, 26, 5, 46, 0, 0, 26, 6, 1, 0, 0, 0, 27, 28, 5, 58, 0, 0, 28, 8, 1, 0, 0, 0, 29, 30, 5, 35, 0, 0, 30, 10, 1, 0, 0, 0, 31, 33, 7, 1, 0, 0, 32, 31, 1, 0, 0, 0, 33, 34, 1, 0, 0, 0, 34, 32, 1, 0, 0, 0, 34, 35, 1, 0, 0, 0, 35, 12, 1, 0, 0, 0, 36, 38, 7, 2, 0, 0, 37, 36, 1, 0, 0, 0, 37, 38, 1, 0, 0, 0, 38, 39, 1, 0, 0, 0, 39, 40, 7, 3, 0, 0, 40, 14, 1, 0, 0, 0, 41, 43, 7, 4, 0, 0, 42, 41, 1, 0, 0, 0, 43, 44, 1, 0, 0, 0, 44, 42, 1, 0, 0, 0, 44, 45, 1, 0, 0, 0, 45, 16, 1, 0, 0, 0, 5, 0, 21, 34, 37, 44, 0] \ No newline at end of file diff --git a/handlers/hosts/ast/parser/HostsLexer.tokens b/handlers/hosts/ast/parser/HostsLexer.tokens index c20b3c1..d53da5d 100644 --- a/handlers/hosts/ast/parser/HostsLexer.tokens +++ b/handlers/hosts/ast/parser/HostsLexer.tokens @@ -5,9 +5,7 @@ COLON=4 HASHTAG=5 SEPARATOR=6 NEWLINE=7 -DIGITS=8 -OCTETS=9 -DOMAIN=10 +STRING=8 '/'=2 '.'=3 ':'=4 diff --git a/handlers/hosts/ast/parser/hosts_base_listener.go b/handlers/hosts/ast/parser/hosts_base_listener.go index 01d1e3a..d9ddba3 100644 --- a/handlers/hosts/ast/parser/hosts_base_listener.go +++ b/handlers/hosts/ast/parser/hosts_base_listener.go @@ -69,36 +69,12 @@ func (s *BaseHostsListener) EnterIpv4Address(ctx *Ipv4AddressContext) {} // ExitIpv4Address is called when production ipv4Address is exited. func (s *BaseHostsListener) ExitIpv4Address(ctx *Ipv4AddressContext) {} -// EnterSingleIPv4Address is called when production singleIPv4Address is entered. -func (s *BaseHostsListener) EnterSingleIPv4Address(ctx *SingleIPv4AddressContext) {} - -// ExitSingleIPv4Address is called when production singleIPv4Address is exited. -func (s *BaseHostsListener) ExitSingleIPv4Address(ctx *SingleIPv4AddressContext) {} - // EnterIpv6Address is called when production ipv6Address is entered. func (s *BaseHostsListener) EnterIpv6Address(ctx *Ipv6AddressContext) {} // ExitIpv6Address is called when production ipv6Address is exited. func (s *BaseHostsListener) ExitIpv6Address(ctx *Ipv6AddressContext) {} -// EnterSingleIPv6Address is called when production singleIPv6Address is entered. -func (s *BaseHostsListener) EnterSingleIPv6Address(ctx *SingleIPv6AddressContext) {} - -// ExitSingleIPv6Address is called when production singleIPv6Address is exited. -func (s *BaseHostsListener) ExitSingleIPv6Address(ctx *SingleIPv6AddressContext) {} - -// EnterIpv4Digit is called when production ipv4Digit is entered. -func (s *BaseHostsListener) EnterIpv4Digit(ctx *Ipv4DigitContext) {} - -// ExitIpv4Digit is called when production ipv4Digit is exited. -func (s *BaseHostsListener) ExitIpv4Digit(ctx *Ipv4DigitContext) {} - -// EnterIpv6Octet is called when production ipv6Octet is entered. -func (s *BaseHostsListener) EnterIpv6Octet(ctx *Ipv6OctetContext) {} - -// ExitIpv6Octet is called when production ipv6Octet is exited. -func (s *BaseHostsListener) ExitIpv6Octet(ctx *Ipv6OctetContext) {} - // EnterIpRange is called when production ipRange is entered. func (s *BaseHostsListener) EnterIpRange(ctx *IpRangeContext) {} @@ -111,6 +87,12 @@ func (s *BaseHostsListener) EnterIpRangeBits(ctx *IpRangeBitsContext) {} // ExitIpRangeBits is called when production ipRangeBits is exited. func (s *BaseHostsListener) ExitIpRangeBits(ctx *IpRangeBitsContext) {} +// EnterIpPort is called when production ipPort is entered. +func (s *BaseHostsListener) EnterIpPort(ctx *IpPortContext) {} + +// ExitIpPort is called when production ipPort is exited. +func (s *BaseHostsListener) ExitIpPort(ctx *IpPortContext) {} + // EnterComment is called when production comment is entered. func (s *BaseHostsListener) EnterComment(ctx *CommentContext) {} diff --git a/handlers/hosts/ast/parser/hosts_lexer.go b/handlers/hosts/ast/parser/hosts_lexer.go index db0d9e1..2540abe 100644 --- a/handlers/hosts/ast/parser/hosts_lexer.go +++ b/handlers/hosts/ast/parser/hosts_lexer.go @@ -47,51 +47,35 @@ func hostslexerLexerInit() { } staticData.SymbolicNames = []string{ "", "COMMENTLINE", "SLASH", "DOT", "COLON", "HASHTAG", "SEPARATOR", - "NEWLINE", "DIGITS", "OCTETS", "DOMAIN", + "NEWLINE", "STRING", } staticData.RuleNames = []string{ "COMMENTLINE", "SLASH", "DOT", "COLON", "HASHTAG", "SEPARATOR", "NEWLINE", - "DIGITS", "DIGIT", "OCTETS", "OCTET", "DOMAIN", "STRING", + "STRING", } staticData.PredictionContextCache = antlr.NewPredictionContextCache() staticData.serializedATN = []int32{ - 4, 0, 10, 83, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, - 4, 7, 4, 2, 5, 7, 5, 2, 6, 7, 6, 2, 7, 7, 7, 2, 8, 7, 8, 2, 9, 7, 9, 2, - 10, 7, 10, 2, 11, 7, 11, 2, 12, 7, 12, 1, 0, 1, 0, 4, 0, 30, 8, 0, 11, - 0, 12, 0, 31, 1, 1, 1, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, 1, 4, 1, 5, 4, - 5, 43, 8, 5, 11, 5, 12, 5, 44, 1, 6, 3, 6, 48, 8, 6, 1, 6, 1, 6, 1, 7, - 4, 7, 53, 8, 7, 11, 7, 12, 7, 54, 1, 8, 1, 8, 1, 9, 4, 9, 60, 8, 9, 11, - 9, 12, 9, 61, 1, 10, 1, 10, 1, 11, 4, 11, 67, 8, 11, 11, 11, 12, 11, 68, - 1, 11, 1, 11, 4, 11, 73, 8, 11, 11, 11, 12, 11, 74, 5, 11, 77, 8, 11, 10, - 11, 12, 11, 80, 9, 11, 1, 12, 1, 12, 0, 0, 13, 1, 1, 3, 2, 5, 3, 7, 4, - 9, 5, 11, 6, 13, 7, 15, 8, 17, 0, 19, 9, 21, 0, 23, 10, 25, 0, 1, 0, 8, - 2, 0, 10, 10, 13, 13, 2, 0, 9, 9, 32, 32, 1, 0, 13, 13, 1, 0, 10, 10, 1, - 0, 48, 57, 3, 0, 48, 57, 65, 70, 97, 102, 2, 0, 65, 90, 97, 122, 5, 0, - 9, 10, 13, 13, 32, 32, 35, 35, 46, 46, 87, 0, 1, 1, 0, 0, 0, 0, 3, 1, 0, - 0, 0, 0, 5, 1, 0, 0, 0, 0, 7, 1, 0, 0, 0, 0, 9, 1, 0, 0, 0, 0, 11, 1, 0, - 0, 0, 0, 13, 1, 0, 0, 0, 0, 15, 1, 0, 0, 0, 0, 19, 1, 0, 0, 0, 0, 23, 1, - 0, 0, 0, 1, 27, 1, 0, 0, 0, 3, 33, 1, 0, 0, 0, 5, 35, 1, 0, 0, 0, 7, 37, - 1, 0, 0, 0, 9, 39, 1, 0, 0, 0, 11, 42, 1, 0, 0, 0, 13, 47, 1, 0, 0, 0, - 15, 52, 1, 0, 0, 0, 17, 56, 1, 0, 0, 0, 19, 59, 1, 0, 0, 0, 21, 63, 1, - 0, 0, 0, 23, 66, 1, 0, 0, 0, 25, 81, 1, 0, 0, 0, 27, 29, 3, 9, 4, 0, 28, - 30, 8, 0, 0, 0, 29, 28, 1, 0, 0, 0, 30, 31, 1, 0, 0, 0, 31, 29, 1, 0, 0, - 0, 31, 32, 1, 0, 0, 0, 32, 2, 1, 0, 0, 0, 33, 34, 5, 47, 0, 0, 34, 4, 1, - 0, 0, 0, 35, 36, 5, 46, 0, 0, 36, 6, 1, 0, 0, 0, 37, 38, 5, 58, 0, 0, 38, - 8, 1, 0, 0, 0, 39, 40, 5, 35, 0, 0, 40, 10, 1, 0, 0, 0, 41, 43, 7, 1, 0, + 4, 0, 8, 46, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, + 4, 7, 4, 2, 5, 7, 5, 2, 6, 7, 6, 2, 7, 7, 7, 1, 0, 1, 0, 4, 0, 20, 8, 0, + 11, 0, 12, 0, 21, 1, 1, 1, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, 1, 4, 1, 5, + 4, 5, 33, 8, 5, 11, 5, 12, 5, 34, 1, 6, 3, 6, 38, 8, 6, 1, 6, 1, 6, 1, + 7, 4, 7, 43, 8, 7, 11, 7, 12, 7, 44, 0, 0, 8, 1, 1, 3, 2, 5, 3, 7, 4, 9, + 5, 11, 6, 13, 7, 15, 8, 1, 0, 5, 2, 0, 10, 10, 13, 13, 2, 0, 9, 9, 32, + 32, 1, 0, 13, 13, 1, 0, 10, 10, 5, 0, 45, 45, 48, 57, 65, 90, 95, 95, 97, + 122, 49, 0, 1, 1, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, 5, 1, 0, 0, 0, 0, 7, 1, + 0, 0, 0, 0, 9, 1, 0, 0, 0, 0, 11, 1, 0, 0, 0, 0, 13, 1, 0, 0, 0, 0, 15, + 1, 0, 0, 0, 1, 17, 1, 0, 0, 0, 3, 23, 1, 0, 0, 0, 5, 25, 1, 0, 0, 0, 7, + 27, 1, 0, 0, 0, 9, 29, 1, 0, 0, 0, 11, 32, 1, 0, 0, 0, 13, 37, 1, 0, 0, + 0, 15, 42, 1, 0, 0, 0, 17, 19, 3, 9, 4, 0, 18, 20, 8, 0, 0, 0, 19, 18, + 1, 0, 0, 0, 20, 21, 1, 0, 0, 0, 21, 19, 1, 0, 0, 0, 21, 22, 1, 0, 0, 0, + 22, 2, 1, 0, 0, 0, 23, 24, 5, 47, 0, 0, 24, 4, 1, 0, 0, 0, 25, 26, 5, 46, + 0, 0, 26, 6, 1, 0, 0, 0, 27, 28, 5, 58, 0, 0, 28, 8, 1, 0, 0, 0, 29, 30, + 5, 35, 0, 0, 30, 10, 1, 0, 0, 0, 31, 33, 7, 1, 0, 0, 32, 31, 1, 0, 0, 0, + 33, 34, 1, 0, 0, 0, 34, 32, 1, 0, 0, 0, 34, 35, 1, 0, 0, 0, 35, 12, 1, + 0, 0, 0, 36, 38, 7, 2, 0, 0, 37, 36, 1, 0, 0, 0, 37, 38, 1, 0, 0, 0, 38, + 39, 1, 0, 0, 0, 39, 40, 7, 3, 0, 0, 40, 14, 1, 0, 0, 0, 41, 43, 7, 4, 0, 0, 42, 41, 1, 0, 0, 0, 43, 44, 1, 0, 0, 0, 44, 42, 1, 0, 0, 0, 44, 45, - 1, 0, 0, 0, 45, 12, 1, 0, 0, 0, 46, 48, 7, 2, 0, 0, 47, 46, 1, 0, 0, 0, - 47, 48, 1, 0, 0, 0, 48, 49, 1, 0, 0, 0, 49, 50, 7, 3, 0, 0, 50, 14, 1, - 0, 0, 0, 51, 53, 3, 17, 8, 0, 52, 51, 1, 0, 0, 0, 53, 54, 1, 0, 0, 0, 54, - 52, 1, 0, 0, 0, 54, 55, 1, 0, 0, 0, 55, 16, 1, 0, 0, 0, 56, 57, 7, 4, 0, - 0, 57, 18, 1, 0, 0, 0, 58, 60, 3, 21, 10, 0, 59, 58, 1, 0, 0, 0, 60, 61, - 1, 0, 0, 0, 61, 59, 1, 0, 0, 0, 61, 62, 1, 0, 0, 0, 62, 20, 1, 0, 0, 0, - 63, 64, 7, 5, 0, 0, 64, 22, 1, 0, 0, 0, 65, 67, 3, 25, 12, 0, 66, 65, 1, - 0, 0, 0, 67, 68, 1, 0, 0, 0, 68, 66, 1, 0, 0, 0, 68, 69, 1, 0, 0, 0, 69, - 78, 1, 0, 0, 0, 70, 72, 3, 5, 2, 0, 71, 73, 7, 6, 0, 0, 72, 71, 1, 0, 0, - 0, 73, 74, 1, 0, 0, 0, 74, 72, 1, 0, 0, 0, 74, 75, 1, 0, 0, 0, 75, 77, - 1, 0, 0, 0, 76, 70, 1, 0, 0, 0, 77, 80, 1, 0, 0, 0, 78, 76, 1, 0, 0, 0, - 78, 79, 1, 0, 0, 0, 79, 24, 1, 0, 0, 0, 80, 78, 1, 0, 0, 0, 81, 82, 8, - 7, 0, 0, 82, 26, 1, 0, 0, 0, 9, 0, 31, 44, 47, 54, 61, 68, 74, 78, 0, + 1, 0, 0, 0, 45, 16, 1, 0, 0, 0, 5, 0, 21, 34, 37, 44, 0, } deserializer := antlr.NewATNDeserializer(nil) staticData.atn = deserializer.Deserialize(staticData.serializedATN) @@ -139,7 +123,5 @@ const ( HostsLexerHASHTAG = 5 HostsLexerSEPARATOR = 6 HostsLexerNEWLINE = 7 - HostsLexerDIGITS = 8 - HostsLexerOCTETS = 9 - HostsLexerDOMAIN = 10 + HostsLexerSTRING = 8 ) diff --git a/handlers/hosts/ast/parser/hosts_listener.go b/handlers/hosts/ast/parser/hosts_listener.go index fbf964f..8e66aac 100644 --- a/handlers/hosts/ast/parser/hosts_listener.go +++ b/handlers/hosts/ast/parser/hosts_listener.go @@ -32,27 +32,18 @@ type HostsListener interface { // EnterIpv4Address is called when entering the ipv4Address production. EnterIpv4Address(c *Ipv4AddressContext) - // EnterSingleIPv4Address is called when entering the singleIPv4Address production. - EnterSingleIPv4Address(c *SingleIPv4AddressContext) - // EnterIpv6Address is called when entering the ipv6Address production. EnterIpv6Address(c *Ipv6AddressContext) - // EnterSingleIPv6Address is called when entering the singleIPv6Address production. - EnterSingleIPv6Address(c *SingleIPv6AddressContext) - - // EnterIpv4Digit is called when entering the ipv4Digit production. - EnterIpv4Digit(c *Ipv4DigitContext) - - // EnterIpv6Octet is called when entering the ipv6Octet production. - EnterIpv6Octet(c *Ipv6OctetContext) - // EnterIpRange is called when entering the ipRange production. EnterIpRange(c *IpRangeContext) // EnterIpRangeBits is called when entering the ipRangeBits production. EnterIpRangeBits(c *IpRangeBitsContext) + // EnterIpPort is called when entering the ipPort production. + EnterIpPort(c *IpPortContext) + // EnterComment is called when entering the comment production. EnterComment(c *CommentContext) @@ -83,27 +74,18 @@ type HostsListener interface { // ExitIpv4Address is called when exiting the ipv4Address production. ExitIpv4Address(c *Ipv4AddressContext) - // ExitSingleIPv4Address is called when exiting the singleIPv4Address production. - ExitSingleIPv4Address(c *SingleIPv4AddressContext) - // ExitIpv6Address is called when exiting the ipv6Address production. ExitIpv6Address(c *Ipv6AddressContext) - // ExitSingleIPv6Address is called when exiting the singleIPv6Address production. - ExitSingleIPv6Address(c *SingleIPv6AddressContext) - - // ExitIpv4Digit is called when exiting the ipv4Digit production. - ExitIpv4Digit(c *Ipv4DigitContext) - - // ExitIpv6Octet is called when exiting the ipv6Octet production. - ExitIpv6Octet(c *Ipv6OctetContext) - // ExitIpRange is called when exiting the ipRange production. ExitIpRange(c *IpRangeContext) // ExitIpRangeBits is called when exiting the ipRangeBits production. ExitIpRangeBits(c *IpRangeBitsContext) + // ExitIpPort is called when exiting the ipPort production. + ExitIpPort(c *IpPortContext) + // ExitComment is called when exiting the comment production. ExitComment(c *CommentContext) diff --git a/handlers/hosts/ast/parser/hosts_parser.go b/handlers/hosts/ast/parser/hosts_parser.go index 81dca33..5f6503e 100644 --- a/handlers/hosts/ast/parser/hosts_parser.go +++ b/handlers/hosts/ast/parser/hosts_parser.go @@ -37,57 +37,70 @@ func hostsParserInit() { } staticData.SymbolicNames = []string{ "", "COMMENTLINE", "SLASH", "DOT", "COLON", "HASHTAG", "SEPARATOR", - "NEWLINE", "DIGITS", "OCTETS", "DOMAIN", + "NEWLINE", "STRING", } staticData.RuleNames = []string{ "lineStatement", "entry", "aliases", "alias", "hostname", "domain", - "ipAddress", "ipv4Address", "singleIPv4Address", "ipv6Address", "singleIPv6Address", - "ipv4Digit", "ipv6Octet", "ipRange", "ipRangeBits", "comment", "leadingComment", + "ipAddress", "ipv4Address", "ipv6Address", "ipRange", "ipRangeBits", + "ipPort", "comment", "leadingComment", } staticData.PredictionContextCache = antlr.NewPredictionContextCache() staticData.serializedATN = []int32{ - 4, 1, 10, 110, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, + 4, 1, 8, 131, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 2, 5, 7, 5, 2, 6, 7, 6, 2, 7, 7, 7, 2, 8, 7, 8, 2, 9, 7, 9, 2, 10, 7, - 10, 2, 11, 7, 11, 2, 12, 7, 12, 2, 13, 7, 13, 2, 14, 7, 14, 2, 15, 7, 15, - 2, 16, 7, 16, 1, 0, 3, 0, 36, 8, 0, 1, 0, 1, 0, 3, 0, 40, 8, 0, 1, 0, 3, - 0, 43, 8, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 52, 8, 1, - 1, 2, 1, 2, 3, 2, 56, 8, 2, 4, 2, 58, 8, 2, 11, 2, 12, 2, 59, 1, 3, 1, - 3, 1, 4, 1, 4, 1, 5, 1, 5, 1, 6, 1, 6, 3, 6, 70, 8, 6, 1, 7, 1, 7, 3, 7, - 74, 8, 7, 1, 8, 1, 8, 1, 8, 1, 8, 1, 8, 1, 8, 1, 8, 1, 8, 1, 9, 1, 9, 3, - 9, 86, 8, 9, 1, 10, 1, 10, 1, 10, 4, 10, 91, 8, 10, 11, 10, 12, 10, 92, - 1, 10, 1, 10, 1, 11, 1, 11, 1, 12, 1, 12, 1, 13, 1, 13, 1, 13, 1, 14, 1, - 14, 1, 15, 1, 15, 1, 16, 1, 16, 1, 16, 0, 0, 17, 0, 2, 4, 6, 8, 10, 12, - 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 0, 0, 102, 0, 35, 1, 0, 0, 0, 2, - 46, 1, 0, 0, 0, 4, 57, 1, 0, 0, 0, 6, 61, 1, 0, 0, 0, 8, 63, 1, 0, 0, 0, - 10, 65, 1, 0, 0, 0, 12, 69, 1, 0, 0, 0, 14, 71, 1, 0, 0, 0, 16, 75, 1, - 0, 0, 0, 18, 83, 1, 0, 0, 0, 20, 90, 1, 0, 0, 0, 22, 96, 1, 0, 0, 0, 24, - 98, 1, 0, 0, 0, 26, 100, 1, 0, 0, 0, 28, 103, 1, 0, 0, 0, 30, 105, 1, 0, - 0, 0, 32, 107, 1, 0, 0, 0, 34, 36, 5, 6, 0, 0, 35, 34, 1, 0, 0, 0, 35, - 36, 1, 0, 0, 0, 36, 37, 1, 0, 0, 0, 37, 39, 3, 2, 1, 0, 38, 40, 5, 6, 0, - 0, 39, 38, 1, 0, 0, 0, 39, 40, 1, 0, 0, 0, 40, 42, 1, 0, 0, 0, 41, 43, - 3, 32, 16, 0, 42, 41, 1, 0, 0, 0, 42, 43, 1, 0, 0, 0, 43, 44, 1, 0, 0, - 0, 44, 45, 5, 0, 0, 1, 45, 1, 1, 0, 0, 0, 46, 47, 3, 12, 6, 0, 47, 48, - 5, 6, 0, 0, 48, 51, 3, 8, 4, 0, 49, 50, 5, 6, 0, 0, 50, 52, 3, 4, 2, 0, - 51, 49, 1, 0, 0, 0, 51, 52, 1, 0, 0, 0, 52, 3, 1, 0, 0, 0, 53, 55, 3, 6, - 3, 0, 54, 56, 5, 6, 0, 0, 55, 54, 1, 0, 0, 0, 55, 56, 1, 0, 0, 0, 56, 58, - 1, 0, 0, 0, 57, 53, 1, 0, 0, 0, 58, 59, 1, 0, 0, 0, 59, 57, 1, 0, 0, 0, - 59, 60, 1, 0, 0, 0, 60, 5, 1, 0, 0, 0, 61, 62, 5, 10, 0, 0, 62, 7, 1, 0, - 0, 0, 63, 64, 3, 10, 5, 0, 64, 9, 1, 0, 0, 0, 65, 66, 5, 10, 0, 0, 66, - 11, 1, 0, 0, 0, 67, 70, 3, 14, 7, 0, 68, 70, 3, 18, 9, 0, 69, 67, 1, 0, - 0, 0, 69, 68, 1, 0, 0, 0, 70, 13, 1, 0, 0, 0, 71, 73, 3, 16, 8, 0, 72, - 74, 3, 26, 13, 0, 73, 72, 1, 0, 0, 0, 73, 74, 1, 0, 0, 0, 74, 15, 1, 0, - 0, 0, 75, 76, 3, 22, 11, 0, 76, 77, 5, 3, 0, 0, 77, 78, 3, 22, 11, 0, 78, - 79, 5, 3, 0, 0, 79, 80, 3, 22, 11, 0, 80, 81, 5, 3, 0, 0, 81, 82, 3, 22, - 11, 0, 82, 17, 1, 0, 0, 0, 83, 85, 3, 20, 10, 0, 84, 86, 3, 26, 13, 0, - 85, 84, 1, 0, 0, 0, 85, 86, 1, 0, 0, 0, 86, 19, 1, 0, 0, 0, 87, 88, 3, - 24, 12, 0, 88, 89, 5, 4, 0, 0, 89, 91, 1, 0, 0, 0, 90, 87, 1, 0, 0, 0, - 91, 92, 1, 0, 0, 0, 92, 90, 1, 0, 0, 0, 92, 93, 1, 0, 0, 0, 93, 94, 1, - 0, 0, 0, 94, 95, 3, 24, 12, 0, 95, 21, 1, 0, 0, 0, 96, 97, 5, 8, 0, 0, - 97, 23, 1, 0, 0, 0, 98, 99, 5, 9, 0, 0, 99, 25, 1, 0, 0, 0, 100, 101, 5, - 2, 0, 0, 101, 102, 3, 28, 14, 0, 102, 27, 1, 0, 0, 0, 103, 104, 5, 8, 0, - 0, 104, 29, 1, 0, 0, 0, 105, 106, 5, 1, 0, 0, 106, 31, 1, 0, 0, 0, 107, - 108, 5, 1, 0, 0, 108, 33, 1, 0, 0, 0, 10, 35, 39, 42, 51, 55, 59, 69, 73, - 85, 92, + 10, 2, 11, 7, 11, 2, 12, 7, 12, 2, 13, 7, 13, 1, 0, 3, 0, 30, 8, 0, 1, + 0, 1, 0, 3, 0, 34, 8, 0, 1, 0, 3, 0, 37, 8, 0, 1, 0, 1, 0, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 3, 1, 46, 8, 1, 1, 2, 1, 2, 3, 2, 50, 8, 2, 4, 2, 52, + 8, 2, 11, 2, 12, 2, 53, 1, 3, 1, 3, 1, 4, 1, 4, 1, 5, 4, 5, 61, 8, 5, 11, + 5, 12, 5, 62, 1, 5, 1, 5, 5, 5, 67, 8, 5, 10, 5, 12, 5, 70, 9, 5, 5, 5, + 72, 8, 5, 10, 5, 12, 5, 75, 9, 5, 1, 6, 1, 6, 3, 6, 79, 8, 6, 1, 7, 1, + 7, 4, 7, 83, 8, 7, 11, 7, 12, 7, 84, 1, 7, 1, 7, 3, 7, 89, 8, 7, 1, 7, + 3, 7, 92, 8, 7, 3, 7, 94, 8, 7, 1, 8, 1, 8, 4, 8, 98, 8, 8, 11, 8, 12, + 8, 99, 1, 8, 1, 8, 3, 8, 104, 8, 8, 1, 8, 1, 8, 1, 8, 3, 8, 109, 8, 8, + 1, 8, 3, 8, 112, 8, 8, 1, 8, 3, 8, 115, 8, 8, 3, 8, 117, 8, 8, 1, 9, 1, + 9, 1, 9, 1, 10, 1, 10, 1, 11, 1, 11, 1, 11, 1, 12, 1, 12, 1, 13, 1, 13, + 1, 13, 0, 0, 14, 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 0, + 0, 136, 0, 29, 1, 0, 0, 0, 2, 40, 1, 0, 0, 0, 4, 51, 1, 0, 0, 0, 6, 55, + 1, 0, 0, 0, 8, 57, 1, 0, 0, 0, 10, 60, 1, 0, 0, 0, 12, 78, 1, 0, 0, 0, + 14, 82, 1, 0, 0, 0, 16, 108, 1, 0, 0, 0, 18, 118, 1, 0, 0, 0, 20, 121, + 1, 0, 0, 0, 22, 123, 1, 0, 0, 0, 24, 126, 1, 0, 0, 0, 26, 128, 1, 0, 0, + 0, 28, 30, 5, 6, 0, 0, 29, 28, 1, 0, 0, 0, 29, 30, 1, 0, 0, 0, 30, 31, + 1, 0, 0, 0, 31, 33, 3, 2, 1, 0, 32, 34, 5, 6, 0, 0, 33, 32, 1, 0, 0, 0, + 33, 34, 1, 0, 0, 0, 34, 36, 1, 0, 0, 0, 35, 37, 3, 26, 13, 0, 36, 35, 1, + 0, 0, 0, 36, 37, 1, 0, 0, 0, 37, 38, 1, 0, 0, 0, 38, 39, 5, 0, 0, 1, 39, + 1, 1, 0, 0, 0, 40, 41, 3, 12, 6, 0, 41, 42, 5, 6, 0, 0, 42, 45, 3, 8, 4, + 0, 43, 44, 5, 6, 0, 0, 44, 46, 3, 4, 2, 0, 45, 43, 1, 0, 0, 0, 45, 46, + 1, 0, 0, 0, 46, 3, 1, 0, 0, 0, 47, 49, 3, 6, 3, 0, 48, 50, 5, 6, 0, 0, + 49, 48, 1, 0, 0, 0, 49, 50, 1, 0, 0, 0, 50, 52, 1, 0, 0, 0, 51, 47, 1, + 0, 0, 0, 52, 53, 1, 0, 0, 0, 53, 51, 1, 0, 0, 0, 53, 54, 1, 0, 0, 0, 54, + 5, 1, 0, 0, 0, 55, 56, 3, 10, 5, 0, 56, 7, 1, 0, 0, 0, 57, 58, 3, 10, 5, + 0, 58, 9, 1, 0, 0, 0, 59, 61, 5, 8, 0, 0, 60, 59, 1, 0, 0, 0, 61, 62, 1, + 0, 0, 0, 62, 60, 1, 0, 0, 0, 62, 63, 1, 0, 0, 0, 63, 73, 1, 0, 0, 0, 64, + 68, 5, 3, 0, 0, 65, 67, 5, 8, 0, 0, 66, 65, 1, 0, 0, 0, 67, 70, 1, 0, 0, + 0, 68, 66, 1, 0, 0, 0, 68, 69, 1, 0, 0, 0, 69, 72, 1, 0, 0, 0, 70, 68, + 1, 0, 0, 0, 71, 64, 1, 0, 0, 0, 72, 75, 1, 0, 0, 0, 73, 71, 1, 0, 0, 0, + 73, 74, 1, 0, 0, 0, 74, 11, 1, 0, 0, 0, 75, 73, 1, 0, 0, 0, 76, 79, 3, + 14, 7, 0, 77, 79, 3, 16, 8, 0, 78, 76, 1, 0, 0, 0, 78, 77, 1, 0, 0, 0, + 79, 13, 1, 0, 0, 0, 80, 81, 5, 8, 0, 0, 81, 83, 5, 3, 0, 0, 82, 80, 1, + 0, 0, 0, 83, 84, 1, 0, 0, 0, 84, 82, 1, 0, 0, 0, 84, 85, 1, 0, 0, 0, 85, + 86, 1, 0, 0, 0, 86, 93, 5, 8, 0, 0, 87, 89, 3, 18, 9, 0, 88, 87, 1, 0, + 0, 0, 88, 89, 1, 0, 0, 0, 89, 94, 1, 0, 0, 0, 90, 92, 3, 22, 11, 0, 91, + 90, 1, 0, 0, 0, 91, 92, 1, 0, 0, 0, 92, 94, 1, 0, 0, 0, 93, 88, 1, 0, 0, + 0, 93, 91, 1, 0, 0, 0, 94, 15, 1, 0, 0, 0, 95, 96, 5, 8, 0, 0, 96, 98, + 5, 4, 0, 0, 97, 95, 1, 0, 0, 0, 98, 99, 1, 0, 0, 0, 99, 97, 1, 0, 0, 0, + 99, 100, 1, 0, 0, 0, 100, 101, 1, 0, 0, 0, 101, 109, 5, 8, 0, 0, 102, 104, + 5, 8, 0, 0, 103, 102, 1, 0, 0, 0, 103, 104, 1, 0, 0, 0, 104, 105, 1, 0, + 0, 0, 105, 106, 5, 4, 0, 0, 106, 107, 5, 4, 0, 0, 107, 109, 5, 8, 0, 0, + 108, 97, 1, 0, 0, 0, 108, 103, 1, 0, 0, 0, 109, 116, 1, 0, 0, 0, 110, 112, + 3, 18, 9, 0, 111, 110, 1, 0, 0, 0, 111, 112, 1, 0, 0, 0, 112, 117, 1, 0, + 0, 0, 113, 115, 3, 22, 11, 0, 114, 113, 1, 0, 0, 0, 114, 115, 1, 0, 0, + 0, 115, 117, 1, 0, 0, 0, 116, 111, 1, 0, 0, 0, 116, 114, 1, 0, 0, 0, 117, + 17, 1, 0, 0, 0, 118, 119, 5, 2, 0, 0, 119, 120, 3, 20, 10, 0, 120, 19, + 1, 0, 0, 0, 121, 122, 5, 8, 0, 0, 122, 21, 1, 0, 0, 0, 123, 124, 5, 4, + 0, 0, 124, 125, 5, 8, 0, 0, 125, 23, 1, 0, 0, 0, 126, 127, 5, 1, 0, 0, + 127, 25, 1, 0, 0, 0, 128, 129, 5, 1, 0, 0, 129, 27, 1, 0, 0, 0, 20, 29, + 33, 36, 45, 49, 53, 62, 68, 73, 78, 84, 88, 91, 93, 99, 103, 108, 111, + 114, 116, } deserializer := antlr.NewATNDeserializer(nil) staticData.atn = deserializer.Deserialize(staticData.serializedATN) @@ -133,30 +146,25 @@ const ( HostsParserHASHTAG = 5 HostsParserSEPARATOR = 6 HostsParserNEWLINE = 7 - HostsParserDIGITS = 8 - HostsParserOCTETS = 9 - HostsParserDOMAIN = 10 + HostsParserSTRING = 8 ) // HostsParser rules. const ( - HostsParserRULE_lineStatement = 0 - HostsParserRULE_entry = 1 - HostsParserRULE_aliases = 2 - HostsParserRULE_alias = 3 - HostsParserRULE_hostname = 4 - HostsParserRULE_domain = 5 - HostsParserRULE_ipAddress = 6 - HostsParserRULE_ipv4Address = 7 - HostsParserRULE_singleIPv4Address = 8 - HostsParserRULE_ipv6Address = 9 - HostsParserRULE_singleIPv6Address = 10 - HostsParserRULE_ipv4Digit = 11 - HostsParserRULE_ipv6Octet = 12 - HostsParserRULE_ipRange = 13 - HostsParserRULE_ipRangeBits = 14 - HostsParserRULE_comment = 15 - HostsParserRULE_leadingComment = 16 + HostsParserRULE_lineStatement = 0 + HostsParserRULE_entry = 1 + HostsParserRULE_aliases = 2 + HostsParserRULE_alias = 3 + HostsParserRULE_hostname = 4 + HostsParserRULE_domain = 5 + HostsParserRULE_ipAddress = 6 + HostsParserRULE_ipv4Address = 7 + HostsParserRULE_ipv6Address = 8 + HostsParserRULE_ipRange = 9 + HostsParserRULE_ipRangeBits = 10 + HostsParserRULE_ipPort = 11 + HostsParserRULE_comment = 12 + HostsParserRULE_leadingComment = 13 ) // ILineStatementContext is an interface to support dynamic dispatch. @@ -279,7 +287,7 @@ func (p *HostsParser) LineStatement() (localctx ILineStatementContext) { var _la int p.EnterOuterAlt(localctx, 1) - p.SetState(35) + p.SetState(29) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -288,7 +296,7 @@ func (p *HostsParser) LineStatement() (localctx ILineStatementContext) { if _la == HostsParserSEPARATOR { { - p.SetState(34) + p.SetState(28) p.Match(HostsParserSEPARATOR) if p.HasError() { // Recognition error - abort rule @@ -298,10 +306,10 @@ func (p *HostsParser) LineStatement() (localctx ILineStatementContext) { } { - p.SetState(37) + p.SetState(31) p.Entry() } - p.SetState(39) + p.SetState(33) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -310,7 +318,7 @@ func (p *HostsParser) LineStatement() (localctx ILineStatementContext) { if _la == HostsParserSEPARATOR { { - p.SetState(38) + p.SetState(32) p.Match(HostsParserSEPARATOR) if p.HasError() { // Recognition error - abort rule @@ -319,7 +327,7 @@ func (p *HostsParser) LineStatement() (localctx ILineStatementContext) { } } - p.SetState(42) + p.SetState(36) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -328,13 +336,13 @@ func (p *HostsParser) LineStatement() (localctx ILineStatementContext) { if _la == HostsParserCOMMENTLINE { { - p.SetState(41) + p.SetState(35) p.LeadingComment() } } { - p.SetState(44) + p.SetState(38) p.Match(HostsParserEOF) if p.HasError() { // Recognition error - abort rule @@ -486,11 +494,11 @@ func (p *HostsParser) Entry() (localctx IEntryContext) { p.EnterRule(localctx, 2, HostsParserRULE_entry) p.EnterOuterAlt(localctx, 1) { - p.SetState(46) + p.SetState(40) p.IpAddress() } { - p.SetState(47) + p.SetState(41) p.Match(HostsParserSEPARATOR) if p.HasError() { // Recognition error - abort rule @@ -498,15 +506,15 @@ func (p *HostsParser) Entry() (localctx IEntryContext) { } } { - p.SetState(48) + p.SetState(42) p.Hostname() } - p.SetState(51) + p.SetState(45) p.GetErrorHandler().Sync(p) if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 3, p.GetParserRuleContext()) == 1 { { - p.SetState(49) + p.SetState(43) p.Match(HostsParserSEPARATOR) if p.HasError() { // Recognition error - abort rule @@ -514,7 +522,7 @@ func (p *HostsParser) Entry() (localctx IEntryContext) { } } { - p.SetState(50) + p.SetState(44) p.Aliases() } @@ -659,24 +667,24 @@ func (p *HostsParser) Aliases() (localctx IAliasesContext) { var _la int p.EnterOuterAlt(localctx, 1) - p.SetState(57) + p.SetState(51) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit } _la = p.GetTokenStream().LA(1) - for ok := true; ok; ok = _la == HostsParserDOMAIN { + for ok := true; ok; ok = _la == HostsParserSTRING { { - p.SetState(53) + p.SetState(47) p.Alias() } - p.SetState(55) + p.SetState(49) p.GetErrorHandler().Sync(p) if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 4, p.GetParserRuleContext()) == 1 { { - p.SetState(54) + p.SetState(48) p.Match(HostsParserSEPARATOR) if p.HasError() { // Recognition error - abort rule @@ -688,7 +696,7 @@ func (p *HostsParser) Aliases() (localctx IAliasesContext) { goto errorExit } - p.SetState(59) + p.SetState(53) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -717,7 +725,7 @@ type IAliasContext interface { GetParser() antlr.Parser // Getter signatures - DOMAIN() antlr.TerminalNode + Domain() IDomainContext // IsAliasContext differentiates from other interfaces. IsAliasContext() @@ -755,8 +763,20 @@ func NewAliasContext(parser antlr.Parser, parent antlr.ParserRuleContext, invoki func (s *AliasContext) GetParser() antlr.Parser { return s.parser } -func (s *AliasContext) DOMAIN() antlr.TerminalNode { - return s.GetToken(HostsParserDOMAIN, 0) +func (s *AliasContext) Domain() IDomainContext { + var t antlr.RuleContext + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(IDomainContext); ok { + t = ctx.(antlr.RuleContext) + break + } + } + + if t == nil { + return nil + } + + return t.(IDomainContext) } func (s *AliasContext) GetRuleContext() antlr.RuleContext { @@ -784,12 +804,8 @@ func (p *HostsParser) Alias() (localctx IAliasContext) { p.EnterRule(localctx, 6, HostsParserRULE_alias) p.EnterOuterAlt(localctx, 1) { - p.SetState(61) - p.Match(HostsParserDOMAIN) - if p.HasError() { - // Recognition error - abort rule - goto errorExit - } + p.SetState(55) + p.Domain() } errorExit: @@ -892,7 +908,7 @@ func (p *HostsParser) Hostname() (localctx IHostnameContext) { p.EnterRule(localctx, 8, HostsParserRULE_hostname) p.EnterOuterAlt(localctx, 1) { - p.SetState(63) + p.SetState(57) p.Domain() } @@ -917,7 +933,10 @@ type IDomainContext interface { GetParser() antlr.Parser // Getter signatures - DOMAIN() antlr.TerminalNode + AllSTRING() []antlr.TerminalNode + STRING(i int) antlr.TerminalNode + AllDOT() []antlr.TerminalNode + DOT(i int) antlr.TerminalNode // IsDomainContext differentiates from other interfaces. IsDomainContext() @@ -955,8 +974,20 @@ func NewDomainContext(parser antlr.Parser, parent antlr.ParserRuleContext, invok func (s *DomainContext) GetParser() antlr.Parser { return s.parser } -func (s *DomainContext) DOMAIN() antlr.TerminalNode { - return s.GetToken(HostsParserDOMAIN, 0) +func (s *DomainContext) AllSTRING() []antlr.TerminalNode { + return s.GetTokens(HostsParserSTRING) +} + +func (s *DomainContext) STRING(i int) antlr.TerminalNode { + return s.GetToken(HostsParserSTRING, i) +} + +func (s *DomainContext) AllDOT() []antlr.TerminalNode { + return s.GetTokens(HostsParserDOT) +} + +func (s *DomainContext) DOT(i int) antlr.TerminalNode { + return s.GetToken(HostsParserDOT, i) } func (s *DomainContext) GetRuleContext() antlr.RuleContext { @@ -982,14 +1013,95 @@ func (s *DomainContext) ExitRule(listener antlr.ParseTreeListener) { func (p *HostsParser) Domain() (localctx IDomainContext) { localctx = NewDomainContext(p, p.GetParserRuleContext(), p.GetState()) p.EnterRule(localctx, 10, HostsParserRULE_domain) + var _la int + + var _alt int + p.EnterOuterAlt(localctx, 1) - { - p.SetState(65) - p.Match(HostsParserDOMAIN) - if p.HasError() { - // Recognition error - abort rule + p.SetState(60) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _alt = 1 + for ok := true; ok; ok = _alt != 2 && _alt != antlr.ATNInvalidAltNumber { + switch _alt { + case 1: + { + p.SetState(59) + p.Match(HostsParserSTRING) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + + default: + p.SetError(antlr.NewNoViableAltException(p, nil, nil, nil, nil, nil)) goto errorExit } + + p.SetState(62) + p.GetErrorHandler().Sync(p) + _alt = p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 6, p.GetParserRuleContext()) + if p.HasError() { + goto errorExit + } + } + p.SetState(73) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + for _la == HostsParserDOT { + { + p.SetState(64) + p.Match(HostsParserDOT) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + p.SetState(68) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _alt = p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 7, p.GetParserRuleContext()) + if p.HasError() { + goto errorExit + } + for _alt != 2 && _alt != antlr.ATNInvalidAltNumber { + if _alt == 1 { + { + p.SetState(65) + p.Match(HostsParserSTRING) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + + } + p.SetState(70) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _alt = p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 7, p.GetParserRuleContext()) + if p.HasError() { + goto errorExit + } + } + + p.SetState(75) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) } errorExit: @@ -1108,27 +1220,26 @@ func (p *HostsParser) IpAddress() (localctx IIpAddressContext) { localctx = NewIpAddressContext(p, p.GetParserRuleContext(), p.GetState()) p.EnterRule(localctx, 12, HostsParserRULE_ipAddress) p.EnterOuterAlt(localctx, 1) - p.SetState(69) + p.SetState(78) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit } - switch p.GetTokenStream().LA(1) { - case HostsParserDIGITS: + switch p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 9, p.GetParserRuleContext()) { + case 1: { - p.SetState(67) + p.SetState(76) p.Ipv4Address() } - case HostsParserOCTETS: + case 2: { - p.SetState(68) + p.SetState(77) p.Ipv6Address() } - default: - p.SetError(antlr.NewNoViableAltException(p, nil, nil, nil, nil, nil)) + case antlr.ATNInvalidAltNumber: goto errorExit } @@ -1153,8 +1264,12 @@ type IIpv4AddressContext interface { GetParser() antlr.Parser // Getter signatures - SingleIPv4Address() ISingleIPv4AddressContext + AllSTRING() []antlr.TerminalNode + STRING(i int) antlr.TerminalNode + AllDOT() []antlr.TerminalNode + DOT(i int) antlr.TerminalNode IpRange() IIpRangeContext + IpPort() IIpPortContext // IsIpv4AddressContext differentiates from other interfaces. IsIpv4AddressContext() @@ -1192,20 +1307,20 @@ func NewIpv4AddressContext(parser antlr.Parser, parent antlr.ParserRuleContext, func (s *Ipv4AddressContext) GetParser() antlr.Parser { return s.parser } -func (s *Ipv4AddressContext) SingleIPv4Address() ISingleIPv4AddressContext { - var t antlr.RuleContext - for _, ctx := range s.GetChildren() { - if _, ok := ctx.(ISingleIPv4AddressContext); ok { - t = ctx.(antlr.RuleContext) - break - } - } +func (s *Ipv4AddressContext) AllSTRING() []antlr.TerminalNode { + return s.GetTokens(HostsParserSTRING) +} - if t == nil { - return nil - } +func (s *Ipv4AddressContext) STRING(i int) antlr.TerminalNode { + return s.GetToken(HostsParserSTRING, i) +} - return t.(ISingleIPv4AddressContext) +func (s *Ipv4AddressContext) AllDOT() []antlr.TerminalNode { + return s.GetTokens(HostsParserDOT) +} + +func (s *Ipv4AddressContext) DOT(i int) antlr.TerminalNode { + return s.GetToken(HostsParserDOT, i) } func (s *Ipv4AddressContext) IpRange() IIpRangeContext { @@ -1224,6 +1339,22 @@ func (s *Ipv4AddressContext) IpRange() IIpRangeContext { return t.(IIpRangeContext) } +func (s *Ipv4AddressContext) IpPort() IIpPortContext { + var t antlr.RuleContext + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(IIpPortContext); ok { + t = ctx.(antlr.RuleContext) + break + } + } + + if t == nil { + return nil + } + + return t.(IIpPortContext) +} + func (s *Ipv4AddressContext) GetRuleContext() antlr.RuleContext { return s } @@ -1249,200 +1380,96 @@ func (p *HostsParser) Ipv4Address() (localctx IIpv4AddressContext) { p.EnterRule(localctx, 14, HostsParserRULE_ipv4Address) var _la int + var _alt int + p.EnterOuterAlt(localctx, 1) - { - p.SetState(71) - p.SingleIPv4Address() - } - p.SetState(73) + p.SetState(82) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit } - _la = p.GetTokenStream().LA(1) - - if _la == HostsParserSLASH { - { - p.SetState(72) - p.IpRange() - } - - } - -errorExit: - if p.HasError() { - v := p.GetError() - localctx.SetException(v) - p.GetErrorHandler().ReportError(p, v) - p.GetErrorHandler().Recover(p, v) - p.SetError(nil) - } - p.ExitRule() - return localctx - goto errorExit // Trick to prevent compiler error if the label is not used -} - -// ISingleIPv4AddressContext is an interface to support dynamic dispatch. -type ISingleIPv4AddressContext interface { - antlr.ParserRuleContext - - // GetParser returns the parser. - GetParser() antlr.Parser - - // Getter signatures - AllIpv4Digit() []IIpv4DigitContext - Ipv4Digit(i int) IIpv4DigitContext - AllDOT() []antlr.TerminalNode - DOT(i int) antlr.TerminalNode - - // IsSingleIPv4AddressContext differentiates from other interfaces. - IsSingleIPv4AddressContext() -} - -type SingleIPv4AddressContext struct { - antlr.BaseParserRuleContext - parser antlr.Parser -} - -func NewEmptySingleIPv4AddressContext() *SingleIPv4AddressContext { - var p = new(SingleIPv4AddressContext) - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) - p.RuleIndex = HostsParserRULE_singleIPv4Address - return p -} - -func InitEmptySingleIPv4AddressContext(p *SingleIPv4AddressContext) { - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) - p.RuleIndex = HostsParserRULE_singleIPv4Address -} - -func (*SingleIPv4AddressContext) IsSingleIPv4AddressContext() {} - -func NewSingleIPv4AddressContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *SingleIPv4AddressContext { - var p = new(SingleIPv4AddressContext) - - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) - - p.parser = parser - p.RuleIndex = HostsParserRULE_singleIPv4Address - - return p -} - -func (s *SingleIPv4AddressContext) GetParser() antlr.Parser { return s.parser } - -func (s *SingleIPv4AddressContext) AllIpv4Digit() []IIpv4DigitContext { - children := s.GetChildren() - len := 0 - for _, ctx := range children { - if _, ok := ctx.(IIpv4DigitContext); ok { - len++ - } - } - - tst := make([]IIpv4DigitContext, len) - i := 0 - for _, ctx := range children { - if t, ok := ctx.(IIpv4DigitContext); ok { - tst[i] = t.(IIpv4DigitContext) - i++ - } - } - - return tst -} - -func (s *SingleIPv4AddressContext) Ipv4Digit(i int) IIpv4DigitContext { - var t antlr.RuleContext - j := 0 - for _, ctx := range s.GetChildren() { - if _, ok := ctx.(IIpv4DigitContext); ok { - if j == i { - t = ctx.(antlr.RuleContext) - break + _alt = 1 + for ok := true; ok; ok = _alt != 2 && _alt != antlr.ATNInvalidAltNumber { + switch _alt { + case 1: + { + p.SetState(80) + p.Match(HostsParserSTRING) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } } - j++ + { + p.SetState(81) + p.Match(HostsParserDOT) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + + default: + p.SetError(antlr.NewNoViableAltException(p, nil, nil, nil, nil, nil)) + goto errorExit + } + + p.SetState(84) + p.GetErrorHandler().Sync(p) + _alt = p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 10, p.GetParserRuleContext()) + if p.HasError() { + goto errorExit } } - - if t == nil { - return nil - } - - return t.(IIpv4DigitContext) -} - -func (s *SingleIPv4AddressContext) AllDOT() []antlr.TerminalNode { - return s.GetTokens(HostsParserDOT) -} - -func (s *SingleIPv4AddressContext) DOT(i int) antlr.TerminalNode { - return s.GetToken(HostsParserDOT, i) -} - -func (s *SingleIPv4AddressContext) GetRuleContext() antlr.RuleContext { - return s -} - -func (s *SingleIPv4AddressContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { - return antlr.TreesStringTree(s, ruleNames, recog) -} - -func (s *SingleIPv4AddressContext) EnterRule(listener antlr.ParseTreeListener) { - if listenerT, ok := listener.(HostsListener); ok { - listenerT.EnterSingleIPv4Address(s) - } -} - -func (s *SingleIPv4AddressContext) ExitRule(listener antlr.ParseTreeListener) { - if listenerT, ok := listener.(HostsListener); ok { - listenerT.ExitSingleIPv4Address(s) - } -} - -func (p *HostsParser) SingleIPv4Address() (localctx ISingleIPv4AddressContext) { - localctx = NewSingleIPv4AddressContext(p, p.GetParserRuleContext(), p.GetState()) - p.EnterRule(localctx, 16, HostsParserRULE_singleIPv4Address) - p.EnterOuterAlt(localctx, 1) { - p.SetState(75) - p.Ipv4Digit() - } - { - p.SetState(76) - p.Match(HostsParserDOT) + p.SetState(86) + p.Match(HostsParserSTRING) if p.HasError() { // Recognition error - abort rule goto errorExit } } - { - p.SetState(77) - p.Ipv4Digit() + p.SetState(93) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit } - { - p.SetState(78) - p.Match(HostsParserDOT) + + switch p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 13, p.GetParserRuleContext()) { + case 1: + p.SetState(88) + p.GetErrorHandler().Sync(p) if p.HasError() { - // Recognition error - abort rule goto errorExit } - } - { - p.SetState(79) - p.Ipv4Digit() - } - { - p.SetState(80) - p.Match(HostsParserDOT) + _la = p.GetTokenStream().LA(1) + + if _la == HostsParserSLASH { + { + p.SetState(87) + p.IpRange() + } + + } + + case 2: + p.SetState(91) + p.GetErrorHandler().Sync(p) if p.HasError() { - // Recognition error - abort rule goto errorExit } - } - { - p.SetState(81) - p.Ipv4Digit() + _la = p.GetTokenStream().LA(1) + + if _la == HostsParserCOLON { + { + p.SetState(90) + p.IpPort() + } + + } + + case antlr.ATNInvalidAltNumber: + goto errorExit } errorExit: @@ -1466,8 +1493,12 @@ type IIpv6AddressContext interface { GetParser() antlr.Parser // Getter signatures - SingleIPv6Address() ISingleIPv6AddressContext + AllSTRING() []antlr.TerminalNode + STRING(i int) antlr.TerminalNode + AllCOLON() []antlr.TerminalNode + COLON(i int) antlr.TerminalNode IpRange() IIpRangeContext + IpPort() IIpPortContext // IsIpv6AddressContext differentiates from other interfaces. IsIpv6AddressContext() @@ -1505,20 +1536,20 @@ func NewIpv6AddressContext(parser antlr.Parser, parent antlr.ParserRuleContext, func (s *Ipv6AddressContext) GetParser() antlr.Parser { return s.parser } -func (s *Ipv6AddressContext) SingleIPv6Address() ISingleIPv6AddressContext { - var t antlr.RuleContext - for _, ctx := range s.GetChildren() { - if _, ok := ctx.(ISingleIPv6AddressContext); ok { - t = ctx.(antlr.RuleContext) - break - } - } +func (s *Ipv6AddressContext) AllSTRING() []antlr.TerminalNode { + return s.GetTokens(HostsParserSTRING) +} - if t == nil { - return nil - } +func (s *Ipv6AddressContext) STRING(i int) antlr.TerminalNode { + return s.GetToken(HostsParserSTRING, i) +} - return t.(ISingleIPv6AddressContext) +func (s *Ipv6AddressContext) AllCOLON() []antlr.TerminalNode { + return s.GetTokens(HostsParserCOLON) +} + +func (s *Ipv6AddressContext) COLON(i int) antlr.TerminalNode { + return s.GetToken(HostsParserCOLON, i) } func (s *Ipv6AddressContext) IpRange() IIpRangeContext { @@ -1537,6 +1568,22 @@ func (s *Ipv6AddressContext) IpRange() IIpRangeContext { return t.(IIpRangeContext) } +func (s *Ipv6AddressContext) IpPort() IIpPortContext { + var t antlr.RuleContext + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(IIpPortContext); ok { + t = ctx.(antlr.RuleContext) + break + } + } + + if t == nil { + return nil + } + + return t.(IIpPortContext) +} + func (s *Ipv6AddressContext) GetRuleContext() antlr.RuleContext { return s } @@ -1559,395 +1606,155 @@ func (s *Ipv6AddressContext) ExitRule(listener antlr.ParseTreeListener) { func (p *HostsParser) Ipv6Address() (localctx IIpv6AddressContext) { localctx = NewIpv6AddressContext(p, p.GetParserRuleContext(), p.GetState()) - p.EnterRule(localctx, 18, HostsParserRULE_ipv6Address) + p.EnterRule(localctx, 16, HostsParserRULE_ipv6Address) var _la int - p.EnterOuterAlt(localctx, 1) - { - p.SetState(83) - p.SingleIPv6Address() - } - p.SetState(85) - p.GetErrorHandler().Sync(p) - if p.HasError() { - goto errorExit - } - _la = p.GetTokenStream().LA(1) - - if _la == HostsParserSLASH { - { - p.SetState(84) - p.IpRange() - } - - } - -errorExit: - if p.HasError() { - v := p.GetError() - localctx.SetException(v) - p.GetErrorHandler().ReportError(p, v) - p.GetErrorHandler().Recover(p, v) - p.SetError(nil) - } - p.ExitRule() - return localctx - goto errorExit // Trick to prevent compiler error if the label is not used -} - -// ISingleIPv6AddressContext is an interface to support dynamic dispatch. -type ISingleIPv6AddressContext interface { - antlr.ParserRuleContext - - // GetParser returns the parser. - GetParser() antlr.Parser - - // Getter signatures - AllIpv6Octet() []IIpv6OctetContext - Ipv6Octet(i int) IIpv6OctetContext - AllCOLON() []antlr.TerminalNode - COLON(i int) antlr.TerminalNode - - // IsSingleIPv6AddressContext differentiates from other interfaces. - IsSingleIPv6AddressContext() -} - -type SingleIPv6AddressContext struct { - antlr.BaseParserRuleContext - parser antlr.Parser -} - -func NewEmptySingleIPv6AddressContext() *SingleIPv6AddressContext { - var p = new(SingleIPv6AddressContext) - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) - p.RuleIndex = HostsParserRULE_singleIPv6Address - return p -} - -func InitEmptySingleIPv6AddressContext(p *SingleIPv6AddressContext) { - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) - p.RuleIndex = HostsParserRULE_singleIPv6Address -} - -func (*SingleIPv6AddressContext) IsSingleIPv6AddressContext() {} - -func NewSingleIPv6AddressContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *SingleIPv6AddressContext { - var p = new(SingleIPv6AddressContext) - - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) - - p.parser = parser - p.RuleIndex = HostsParserRULE_singleIPv6Address - - return p -} - -func (s *SingleIPv6AddressContext) GetParser() antlr.Parser { return s.parser } - -func (s *SingleIPv6AddressContext) AllIpv6Octet() []IIpv6OctetContext { - children := s.GetChildren() - len := 0 - for _, ctx := range children { - if _, ok := ctx.(IIpv6OctetContext); ok { - len++ - } - } - - tst := make([]IIpv6OctetContext, len) - i := 0 - for _, ctx := range children { - if t, ok := ctx.(IIpv6OctetContext); ok { - tst[i] = t.(IIpv6OctetContext) - i++ - } - } - - return tst -} - -func (s *SingleIPv6AddressContext) Ipv6Octet(i int) IIpv6OctetContext { - var t antlr.RuleContext - j := 0 - for _, ctx := range s.GetChildren() { - if _, ok := ctx.(IIpv6OctetContext); ok { - if j == i { - t = ctx.(antlr.RuleContext) - break - } - j++ - } - } - - if t == nil { - return nil - } - - return t.(IIpv6OctetContext) -} - -func (s *SingleIPv6AddressContext) AllCOLON() []antlr.TerminalNode { - return s.GetTokens(HostsParserCOLON) -} - -func (s *SingleIPv6AddressContext) COLON(i int) antlr.TerminalNode { - return s.GetToken(HostsParserCOLON, i) -} - -func (s *SingleIPv6AddressContext) GetRuleContext() antlr.RuleContext { - return s -} - -func (s *SingleIPv6AddressContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { - return antlr.TreesStringTree(s, ruleNames, recog) -} - -func (s *SingleIPv6AddressContext) EnterRule(listener antlr.ParseTreeListener) { - if listenerT, ok := listener.(HostsListener); ok { - listenerT.EnterSingleIPv6Address(s) - } -} - -func (s *SingleIPv6AddressContext) ExitRule(listener antlr.ParseTreeListener) { - if listenerT, ok := listener.(HostsListener); ok { - listenerT.ExitSingleIPv6Address(s) - } -} - -func (p *HostsParser) SingleIPv6Address() (localctx ISingleIPv6AddressContext) { - localctx = NewSingleIPv6AddressContext(p, p.GetParserRuleContext(), p.GetState()) - p.EnterRule(localctx, 20, HostsParserRULE_singleIPv6Address) var _alt int p.EnterOuterAlt(localctx, 1) - p.SetState(90) + p.SetState(108) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit } - _alt = 1 - for ok := true; ok; ok = _alt != 2 && _alt != antlr.ATNInvalidAltNumber { - switch _alt { - case 1: - { - p.SetState(87) - p.Ipv6Octet() + + switch p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 16, p.GetParserRuleContext()) { + case 1: + p.SetState(97) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _alt = 1 + for ok := true; ok; ok = _alt != 2 && _alt != antlr.ATNInvalidAltNumber { + switch _alt { + case 1: + { + p.SetState(95) + p.Match(HostsParserSTRING) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + { + p.SetState(96) + p.Match(HostsParserCOLON) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + + default: + p.SetError(antlr.NewNoViableAltException(p, nil, nil, nil, nil, nil)) + goto errorExit } + + p.SetState(99) + p.GetErrorHandler().Sync(p) + _alt = p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 14, p.GetParserRuleContext()) + if p.HasError() { + goto errorExit + } + } + { + p.SetState(101) + p.Match(HostsParserSTRING) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + + case 2: + p.SetState(103) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + if _la == HostsParserSTRING { { - p.SetState(88) - p.Match(HostsParserCOLON) + p.SetState(102) + p.Match(HostsParserSTRING) if p.HasError() { // Recognition error - abort rule goto errorExit } } - default: - p.SetError(antlr.NewNoViableAltException(p, nil, nil, nil, nil, nil)) - goto errorExit + } + { + p.SetState(105) + p.Match(HostsParserCOLON) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + { + p.SetState(106) + p.Match(HostsParserCOLON) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + { + p.SetState(107) + p.Match(HostsParserSTRING) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } } - p.SetState(92) + case antlr.ATNInvalidAltNumber: + goto errorExit + } + p.SetState(116) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + + switch p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 19, p.GetParserRuleContext()) { + case 1: + p.SetState(111) p.GetErrorHandler().Sync(p) - _alt = p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 9, p.GetParserRuleContext()) if p.HasError() { goto errorExit } - } - { - p.SetState(94) - p.Ipv6Octet() - } + _la = p.GetTokenStream().LA(1) -errorExit: - if p.HasError() { - v := p.GetError() - localctx.SetException(v) - p.GetErrorHandler().ReportError(p, v) - p.GetErrorHandler().Recover(p, v) - p.SetError(nil) - } - p.ExitRule() - return localctx - goto errorExit // Trick to prevent compiler error if the label is not used -} + if _la == HostsParserSLASH { + { + p.SetState(110) + p.IpRange() + } -// IIpv4DigitContext is an interface to support dynamic dispatch. -type IIpv4DigitContext interface { - antlr.ParserRuleContext + } - // GetParser returns the parser. - GetParser() antlr.Parser - - // Getter signatures - DIGITS() antlr.TerminalNode - - // IsIpv4DigitContext differentiates from other interfaces. - IsIpv4DigitContext() -} - -type Ipv4DigitContext struct { - antlr.BaseParserRuleContext - parser antlr.Parser -} - -func NewEmptyIpv4DigitContext() *Ipv4DigitContext { - var p = new(Ipv4DigitContext) - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) - p.RuleIndex = HostsParserRULE_ipv4Digit - return p -} - -func InitEmptyIpv4DigitContext(p *Ipv4DigitContext) { - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) - p.RuleIndex = HostsParserRULE_ipv4Digit -} - -func (*Ipv4DigitContext) IsIpv4DigitContext() {} - -func NewIpv4DigitContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *Ipv4DigitContext { - var p = new(Ipv4DigitContext) - - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) - - p.parser = parser - p.RuleIndex = HostsParserRULE_ipv4Digit - - return p -} - -func (s *Ipv4DigitContext) GetParser() antlr.Parser { return s.parser } - -func (s *Ipv4DigitContext) DIGITS() antlr.TerminalNode { - return s.GetToken(HostsParserDIGITS, 0) -} - -func (s *Ipv4DigitContext) GetRuleContext() antlr.RuleContext { - return s -} - -func (s *Ipv4DigitContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { - return antlr.TreesStringTree(s, ruleNames, recog) -} - -func (s *Ipv4DigitContext) EnterRule(listener antlr.ParseTreeListener) { - if listenerT, ok := listener.(HostsListener); ok { - listenerT.EnterIpv4Digit(s) - } -} - -func (s *Ipv4DigitContext) ExitRule(listener antlr.ParseTreeListener) { - if listenerT, ok := listener.(HostsListener); ok { - listenerT.ExitIpv4Digit(s) - } -} - -func (p *HostsParser) Ipv4Digit() (localctx IIpv4DigitContext) { - localctx = NewIpv4DigitContext(p, p.GetParserRuleContext(), p.GetState()) - p.EnterRule(localctx, 22, HostsParserRULE_ipv4Digit) - p.EnterOuterAlt(localctx, 1) - { - p.SetState(96) - p.Match(HostsParserDIGITS) + case 2: + p.SetState(114) + p.GetErrorHandler().Sync(p) if p.HasError() { - // Recognition error - abort rule goto errorExit } - } + _la = p.GetTokenStream().LA(1) -errorExit: - if p.HasError() { - v := p.GetError() - localctx.SetException(v) - p.GetErrorHandler().ReportError(p, v) - p.GetErrorHandler().Recover(p, v) - p.SetError(nil) - } - p.ExitRule() - return localctx - goto errorExit // Trick to prevent compiler error if the label is not used -} + if _la == HostsParserCOLON { + { + p.SetState(113) + p.IpPort() + } -// IIpv6OctetContext is an interface to support dynamic dispatch. -type IIpv6OctetContext interface { - antlr.ParserRuleContext - - // GetParser returns the parser. - GetParser() antlr.Parser - - // Getter signatures - OCTETS() antlr.TerminalNode - - // IsIpv6OctetContext differentiates from other interfaces. - IsIpv6OctetContext() -} - -type Ipv6OctetContext struct { - antlr.BaseParserRuleContext - parser antlr.Parser -} - -func NewEmptyIpv6OctetContext() *Ipv6OctetContext { - var p = new(Ipv6OctetContext) - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) - p.RuleIndex = HostsParserRULE_ipv6Octet - return p -} - -func InitEmptyIpv6OctetContext(p *Ipv6OctetContext) { - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) - p.RuleIndex = HostsParserRULE_ipv6Octet -} - -func (*Ipv6OctetContext) IsIpv6OctetContext() {} - -func NewIpv6OctetContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *Ipv6OctetContext { - var p = new(Ipv6OctetContext) - - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) - - p.parser = parser - p.RuleIndex = HostsParserRULE_ipv6Octet - - return p -} - -func (s *Ipv6OctetContext) GetParser() antlr.Parser { return s.parser } - -func (s *Ipv6OctetContext) OCTETS() antlr.TerminalNode { - return s.GetToken(HostsParserOCTETS, 0) -} - -func (s *Ipv6OctetContext) GetRuleContext() antlr.RuleContext { - return s -} - -func (s *Ipv6OctetContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { - return antlr.TreesStringTree(s, ruleNames, recog) -} - -func (s *Ipv6OctetContext) EnterRule(listener antlr.ParseTreeListener) { - if listenerT, ok := listener.(HostsListener); ok { - listenerT.EnterIpv6Octet(s) - } -} - -func (s *Ipv6OctetContext) ExitRule(listener antlr.ParseTreeListener) { - if listenerT, ok := listener.(HostsListener); ok { - listenerT.ExitIpv6Octet(s) - } -} - -func (p *HostsParser) Ipv6Octet() (localctx IIpv6OctetContext) { - localctx = NewIpv6OctetContext(p, p.GetParserRuleContext(), p.GetState()) - p.EnterRule(localctx, 24, HostsParserRULE_ipv6Octet) - p.EnterOuterAlt(localctx, 1) - { - p.SetState(98) - p.Match(HostsParserOCTETS) - if p.HasError() { - // Recognition error - abort rule - goto errorExit } + + case antlr.ATNInvalidAltNumber: + goto errorExit } errorExit: @@ -2052,10 +1859,10 @@ func (s *IpRangeContext) ExitRule(listener antlr.ParseTreeListener) { func (p *HostsParser) IpRange() (localctx IIpRangeContext) { localctx = NewIpRangeContext(p, p.GetParserRuleContext(), p.GetState()) - p.EnterRule(localctx, 26, HostsParserRULE_ipRange) + p.EnterRule(localctx, 18, HostsParserRULE_ipRange) p.EnterOuterAlt(localctx, 1) { - p.SetState(100) + p.SetState(118) p.Match(HostsParserSLASH) if p.HasError() { // Recognition error - abort rule @@ -2063,7 +1870,7 @@ func (p *HostsParser) IpRange() (localctx IIpRangeContext) { } } { - p.SetState(101) + p.SetState(119) p.IpRangeBits() } @@ -2088,7 +1895,7 @@ type IIpRangeBitsContext interface { GetParser() antlr.Parser // Getter signatures - DIGITS() antlr.TerminalNode + STRING() antlr.TerminalNode // IsIpRangeBitsContext differentiates from other interfaces. IsIpRangeBitsContext() @@ -2126,8 +1933,8 @@ func NewIpRangeBitsContext(parser antlr.Parser, parent antlr.ParserRuleContext, func (s *IpRangeBitsContext) GetParser() antlr.Parser { return s.parser } -func (s *IpRangeBitsContext) DIGITS() antlr.TerminalNode { - return s.GetToken(HostsParserDIGITS, 0) +func (s *IpRangeBitsContext) STRING() antlr.TerminalNode { + return s.GetToken(HostsParserSTRING, 0) } func (s *IpRangeBitsContext) GetRuleContext() antlr.RuleContext { @@ -2152,11 +1959,120 @@ func (s *IpRangeBitsContext) ExitRule(listener antlr.ParseTreeListener) { func (p *HostsParser) IpRangeBits() (localctx IIpRangeBitsContext) { localctx = NewIpRangeBitsContext(p, p.GetParserRuleContext(), p.GetState()) - p.EnterRule(localctx, 28, HostsParserRULE_ipRangeBits) + p.EnterRule(localctx, 20, HostsParserRULE_ipRangeBits) p.EnterOuterAlt(localctx, 1) { - p.SetState(103) - p.Match(HostsParserDIGITS) + p.SetState(121) + p.Match(HostsParserSTRING) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} + +// IIpPortContext is an interface to support dynamic dispatch. +type IIpPortContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + + // Getter signatures + COLON() antlr.TerminalNode + STRING() antlr.TerminalNode + + // IsIpPortContext differentiates from other interfaces. + IsIpPortContext() +} + +type IpPortContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptyIpPortContext() *IpPortContext { + var p = new(IpPortContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = HostsParserRULE_ipPort + return p +} + +func InitEmptyIpPortContext(p *IpPortContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = HostsParserRULE_ipPort +} + +func (*IpPortContext) IsIpPortContext() {} + +func NewIpPortContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *IpPortContext { + var p = new(IpPortContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = HostsParserRULE_ipPort + + return p +} + +func (s *IpPortContext) GetParser() antlr.Parser { return s.parser } + +func (s *IpPortContext) COLON() antlr.TerminalNode { + return s.GetToken(HostsParserCOLON, 0) +} + +func (s *IpPortContext) STRING() antlr.TerminalNode { + return s.GetToken(HostsParserSTRING, 0) +} + +func (s *IpPortContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *IpPortContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +func (s *IpPortContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(HostsListener); ok { + listenerT.EnterIpPort(s) + } +} + +func (s *IpPortContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(HostsListener); ok { + listenerT.ExitIpPort(s) + } +} + +func (p *HostsParser) IpPort() (localctx IIpPortContext) { + localctx = NewIpPortContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 22, HostsParserRULE_ipPort) + p.EnterOuterAlt(localctx, 1) + { + p.SetState(123) + p.Match(HostsParserCOLON) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + { + p.SetState(124) + p.Match(HostsParserSTRING) if p.HasError() { // Recognition error - abort rule goto errorExit @@ -2248,10 +2164,10 @@ func (s *CommentContext) ExitRule(listener antlr.ParseTreeListener) { func (p *HostsParser) Comment() (localctx ICommentContext) { localctx = NewCommentContext(p, p.GetParserRuleContext(), p.GetState()) - p.EnterRule(localctx, 30, HostsParserRULE_comment) + p.EnterRule(localctx, 24, HostsParserRULE_comment) p.EnterOuterAlt(localctx, 1) { - p.SetState(105) + p.SetState(126) p.Match(HostsParserCOMMENTLINE) if p.HasError() { // Recognition error - abort rule @@ -2344,10 +2260,10 @@ func (s *LeadingCommentContext) ExitRule(listener antlr.ParseTreeListener) { func (p *HostsParser) LeadingComment() (localctx ILeadingCommentContext) { localctx = NewLeadingCommentContext(p, p.GetParserRuleContext(), p.GetState()) - p.EnterRule(localctx, 32, HostsParserRULE_leadingComment) + p.EnterRule(localctx, 26, HostsParserRULE_leadingComment) p.EnterOuterAlt(localctx, 1) { - p.SetState(107) + p.SetState(128) p.Match(HostsParserCOMMENTLINE) if p.HasError() { // Recognition error - abort rule diff --git a/handlers/hosts/ast/parser_test.go b/handlers/hosts/ast/parser_test.go new file mode 100644 index 0000000..e390a96 --- /dev/null +++ b/handlers/hosts/ast/parser_test.go @@ -0,0 +1,20 @@ +package ast + +import ( + "config-lsp/utils" + "testing" +) + +func TestParserInvalidWithPort( + t *testing.T, +) { + input := utils.Dedent(` +1.2.3.4:80 hello.com +`) + parser := NewHostsParser() + errors := parser.Parse(input) + + if len(errors) != 1 { + t.Fatalf("Expected 1 error, but got %v", errors) + } +} diff --git a/handlers/hosts/lsp/text-document-did-change.go b/handlers/hosts/lsp/text-document-did-change.go index af39187..e0504e1 100644 --- a/handlers/hosts/lsp/text-document-did-change.go +++ b/handlers/hosts/lsp/text-document-did-change.go @@ -29,10 +29,10 @@ func TextDocumentDidChange( return err.ToDiagnostic() }, )...) + } else { + diagnostics = append(diagnostics, analyzer.Analyze(document)...) } - diagnostics = append(diagnostics, analyzer.Analyze(document)...) - if len(diagnostics) > 0 { common.SendDiagnostics(context, params.TextDocument.URI, diagnostics) } diff --git a/handlers/hosts/lsp/text-document-did-open.go b/handlers/hosts/lsp/text-document-did-open.go index 2e07550..e9f1306 100644 --- a/handlers/hosts/lsp/text-document-did-open.go +++ b/handlers/hosts/lsp/text-document-did-open.go @@ -7,6 +7,8 @@ import ( "config-lsp/handlers/hosts/ast" "config-lsp/handlers/hosts/indexes" "config-lsp/utils" + "fmt" + "github.com/tliron/glsp" protocol "github.com/tliron/glsp/protocol_3_16" ) @@ -26,18 +28,22 @@ func TextDocumentDidOpen( hosts.DocumentParserMap[params.TextDocument.URI] = &document errors := parser.Parse(params.TextDocument.Text) + diagnostics := make([]protocol.Diagnostic, 0) - diagnostics := utils.Map( - errors, - func(err common.LSPError) protocol.Diagnostic { - return err.ToDiagnostic() - }, - ) - - diagnostics = append( - diagnostics, - analyzer.Analyze(&document)..., - ) + println(fmt.Sprintf("Errors: %v", errors)) + if len(errors) > 0 { + diagnostics = utils.Map( + errors, + func(err common.LSPError) protocol.Diagnostic { + return err.ToDiagnostic() + }, + ) + } else { + diagnostics = append( + diagnostics, + analyzer.Analyze(&document)..., + ) + } if len(diagnostics) > 0 { common.SendDiagnostics(context, params.TextDocument.URI, diagnostics) From 65572886f2fa709416c21a06b2fe9b0532d89546 Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Sun, 8 Sep 2024 21:59:35 +0200 Subject: [PATCH 002/133] chore(hosts): Use TreeMap for entries --- handlers/hosts/analyzer/double_ips.go | 14 ++-- handlers/hosts/analyzer/handler_test.go | 76 ++++++++++--------- .../analyzer/{resolve.go => resolver.go} | 7 +- handlers/hosts/analyzer/values.go | 13 +++- handlers/hosts/ast/hosts.go | 4 +- handlers/hosts/ast/listener.go | 18 +++-- handlers/hosts/ast/parser.go | 7 +- handlers/hosts/ast/parser_test.go | 31 ++++++++ handlers/hosts/fields/documentation-fields.go | 2 +- handlers/hosts/handlers/code-actions.go | 9 ++- handlers/hosts/lsp/text-document-hover.go | 3 +- 11 files changed, 121 insertions(+), 63 deletions(-) rename handlers/hosts/analyzer/{resolve.go => resolver.go} (93%) diff --git a/handlers/hosts/analyzer/double_ips.go b/handlers/hosts/analyzer/double_ips.go index 4fcd2f4..8ad1bbf 100644 --- a/handlers/hosts/analyzer/double_ips.go +++ b/handlers/hosts/analyzer/double_ips.go @@ -3,10 +3,9 @@ package analyzer import ( "config-lsp/common" "config-lsp/handlers/hosts" + "config-lsp/handlers/hosts/ast" "config-lsp/handlers/hosts/shared" - "config-lsp/utils" "net" - "slices" ) func ipToString(ip net.IPAddr) string { @@ -19,14 +18,11 @@ func analyzeDoubleIPs(d *hosts.HostsDocument) []common.LSPError { d.Indexes.DoubleIPs = make(map[uint32]shared.DuplicateIPDeclaration) - // TODO: `range` does not seem to properly - // iterate in a sorted way. - // Instead, use a treemap - lines := utils.KeysOfMap(d.Parser.Tree.Entries) - slices.Sort(lines) + it := d.Parser.Tree.Entries.Iterator() - for _, lineNumber := range lines { - entry := d.Parser.Tree.Entries[lineNumber] + for it.Next() { + lineNumber := it.Key().(uint32) + entry := it.Value().(*ast.HostsEntry) if entry.IPAddress != nil { key := ipToString(entry.IPAddress.Value) diff --git a/handlers/hosts/analyzer/handler_test.go b/handlers/hosts/analyzer/handler_test.go index ce274c6..b7182a2 100644 --- a/handlers/hosts/analyzer/handler_test.go +++ b/handlers/hosts/analyzer/handler_test.go @@ -21,48 +21,50 @@ func TestValidSimpleExampleWorks( t.Fatalf("Expected no errors, but got %v", errors) } - if !(len(parser.Tree.Entries) == 1) { - t.Errorf("Expected 1 entry, but got %v", len(parser.Tree.Entries)) + if !(parser.Tree.Entries.Size() == 1) { + t.Errorf("Expected 1 entry, but got %v", parser.Tree.Entries.Size()) } - if parser.Tree.Entries[0].IPAddress == nil { - t.Errorf("Expected IP address to be present, but got nil") + rawEntry, found := parser.Tree.Entries.Get(uint32(0)) + if !found { + t.Fatalf("Expected IP address to be present, but got nil") } - if !(parser.Tree.Entries[0].IPAddress.Value.String() == net.ParseIP("1.2.3.4").String()) { - t.Errorf("Expected IP address to be 1.2.3.4, but got %v", parser.Tree.Entries[0].IPAddress.Value) + entry := rawEntry.(*ast.HostsEntry) + if !(entry.IPAddress.Value.String() == net.ParseIP("1.2.3.4").String()) { + t.Errorf("Expected IP address to be 1.2.3.4, but got %v", entry.IPAddress.Value) } - if !(parser.Tree.Entries[0].Hostname.Value == "hello.com") { - t.Errorf("Expected hostname to be hello.com, but got %v", parser.Tree.Entries[0].Hostname.Value) + if !(entry.Hostname.Value == "hello.com") { + t.Errorf("Expected hostname to be hello.com, but got %v", entry.Hostname.Value) } - if !(parser.Tree.Entries[0].Aliases == nil) { - t.Errorf("Expected no aliases, but got %v", parser.Tree.Entries[0].Aliases) + if !(entry.Aliases == nil) { + t.Errorf("Expected no aliases, but got %v", entry.Aliases) } - if !(parser.Tree.Entries[0].Location.Start.Line == 0) { - t.Errorf("Expected line to be 1, but got %v", parser.Tree.Entries[0].Location.Start.Line) + if !(entry.Location.Start.Line == 0) { + t.Errorf("Expected line to be 1, but got %v", entry.Location.Start.Line) } - if !(parser.Tree.Entries[0].Location.Start.Character == 0) { - t.Errorf("Expected start to be 0, but got %v", parser.Tree.Entries[0].Location.Start) + if !(entry.Location.Start.Character == 0) { + t.Errorf("Expected start to be 0, but got %v", entry.Location.Start) } - if !(parser.Tree.Entries[0].Location.End.Character == 17) { - t.Errorf("Expected end to be 17, but got %v", parser.Tree.Entries[0].Location.End.Character) + if !(entry.Location.End.Character == 17) { + t.Errorf("Expected end to be 17, but got %v", entry.Location.End.Character) } - if !(parser.Tree.Entries[0].IPAddress.Location.Start.Line == 0) { - t.Errorf("Expected IP address line to be 1, but got %v", parser.Tree.Entries[0].IPAddress.Location.Start.Line) + if !(entry.IPAddress.Location.Start.Line == 0) { + t.Errorf("Expected IP address line to be 1, but got %v", entry.IPAddress.Location.Start.Line) } - if !(parser.Tree.Entries[0].IPAddress.Location.Start.Character == 0) { - t.Errorf("Expected IP address start to be 0, but got %v", parser.Tree.Entries[0].IPAddress.Location.Start.Character) + if !(entry.IPAddress.Location.Start.Character == 0) { + t.Errorf("Expected IP address start to be 0, but got %v", entry.IPAddress.Location.Start.Character) } - if !(parser.Tree.Entries[0].IPAddress.Location.End.Character == 7) { - t.Errorf("Expected IP address end to be 7, but got %v", parser.Tree.Entries[0].IPAddress.Location.End.Character) + if !(entry.IPAddress.Location.End.Character == 7) { + t.Errorf("Expected IP address end to be 7, but got %v", entry.IPAddress.Location.End.Character) } if !(len(parser.CommentLines) == 0) { @@ -88,16 +90,18 @@ func TestValidComplexExampleWorks( t.Fatalf("Expected no errors, but got %v", errors) } - if !(len(parser.Tree.Entries) == 3) { - t.Errorf("Expected 3 entries, but got %v", len(parser.Tree.Entries)) + if !(parser.Tree.Entries.Size() == 3) { + t.Fatalf("Expected 3 entries, but got %v", parser.Tree.Entries.Size()) } - if parser.Tree.Entries[2].IPAddress == nil { + rawEntry, _ := parser.Tree.Entries.Get(uint32(2)) + entry := rawEntry.(*ast.HostsEntry) + if entry.IPAddress == nil { t.Errorf("Expected IP address to be present, but got nil") } - if !(parser.Tree.Entries[2].IPAddress.Value.String() == net.ParseIP("1.2.3.4").String()) { - t.Errorf("Expected IP address to be 1.2.3.4, but got %v", parser.Tree.Entries[2].IPAddress.Value) + if !(entry.IPAddress.Value.String() == net.ParseIP("1.2.3.4").String()) { + t.Errorf("Expected IP address to be 1.2.3.4, but got %v", entry.IPAddress.Value) } if !(len(parser.CommentLines) == 1) { @@ -123,23 +127,25 @@ func TestInvalidExampleWorks( t.Fatalf("Expected errors, but got none") } - if !(len(parser.Tree.Entries) == 1) { - t.Errorf("Expected 1 entries, but got %v", len(parser.Tree.Entries)) + if !(parser.Tree.Entries.Size() == 1) { + t.Errorf("Expected 1 entries, but got %v", parser.Tree.Entries.Size()) } if !(len(parser.CommentLines) == 0) { t.Errorf("Expected no comment lines, but got %v", len(parser.CommentLines)) } - if !(parser.Tree.Entries[0].IPAddress.Value.String() == net.ParseIP("1.2.3.4").String()) { - t.Errorf("Expected IP address to be nil, but got %v", parser.Tree.Entries[0].IPAddress) + rawEntry, _ := parser.Tree.Entries.Get(uint32(0)) + entry := rawEntry.(*ast.HostsEntry) + if !(entry.IPAddress.Value.String() == net.ParseIP("1.2.3.4").String()) { + t.Errorf("Expected IP address to be nil, but got %v", entry.IPAddress) } - if !(parser.Tree.Entries[0].Hostname == nil) { - t.Errorf("Expected hostname to be nil, but got %v", parser.Tree.Entries[0].Hostname) + if !(entry.Hostname == nil) { + t.Errorf("Expected hostname to be nil, but got %v", entry.Hostname) } - if !(parser.Tree.Entries[0].Aliases == nil) { - t.Errorf("Expected aliases to be nil, but got %v", parser.Tree.Entries[0].Aliases) + if !(entry.Aliases == nil) { + t.Errorf("Expected aliases to be nil, but got %v", entry.Aliases) } } diff --git a/handlers/hosts/analyzer/resolve.go b/handlers/hosts/analyzer/resolver.go similarity index 93% rename from handlers/hosts/analyzer/resolve.go rename to handlers/hosts/analyzer/resolver.go index 846af98..d59b412 100644 --- a/handlers/hosts/analyzer/resolve.go +++ b/handlers/hosts/analyzer/resolver.go @@ -38,7 +38,12 @@ func createResolverFromParser(p ast.HostsParser) (indexes.Resolver, []common.LSP Entries: make(map[string]indexes.ResolverEntry), } - for lineNumber, entry := range p.Tree.Entries { + it := p.Tree.Entries.Iterator() + + for it.Next() { + lineNumber := it.Key().(uint32) + entry := it.Value().(*ast.HostsEntry) + if entry.IPAddress != nil && entry.Hostname != nil { hostNames := append( []hostnameEntry{ diff --git a/handlers/hosts/analyzer/values.go b/handlers/hosts/analyzer/values.go index e6da88e..d1c4e0a 100644 --- a/handlers/hosts/analyzer/values.go +++ b/handlers/hosts/analyzer/values.go @@ -14,7 +14,12 @@ func analyzeEntriesSetCorrectly( ) []common.LSPError { err := make([]common.LSPError, 0) - for lineNumber, entry := range parser.Tree.Entries { + it := parser.Tree.Entries.Iterator() + + for it.Next() { + lineNumber := it.Key().(uint32) + entry := it.Value().(*ast.HostsEntry) + if entry.IPAddress == nil { err = append(err, common.LSPError{ Range: common.CreateFullLineRange(lineNumber), @@ -40,7 +45,11 @@ func analyzeEntriesAreValid( ) []common.LSPError { err := make([]common.LSPError, 0) - for _, entry := range parser.Tree.Entries { + it := parser.Tree.Entries.Iterator() + + for it.Next() { + entry := it.Value().(*ast.HostsEntry) + err = append( err, utils.Map( diff --git a/handlers/hosts/ast/hosts.go b/handlers/hosts/ast/hosts.go index 5f28219..99b8fa0 100644 --- a/handlers/hosts/ast/hosts.go +++ b/handlers/hosts/ast/hosts.go @@ -4,6 +4,8 @@ import ( "config-lsp/common" "fmt" "net" + + "github.com/emirpasic/gods/maps/treemap" ) type HostsParser struct { @@ -13,7 +15,7 @@ type HostsParser struct { type HostsTree struct { // [line]entry - Entries map[uint32]*HostsEntry + Entries *treemap.Map } type HostsEntry struct { diff --git a/handlers/hosts/ast/listener.go b/handlers/hosts/ast/listener.go index 11d9083..6bcf3f1 100644 --- a/handlers/hosts/ast/listener.go +++ b/handlers/hosts/ast/listener.go @@ -31,9 +31,9 @@ func (s *hostsParserListener) EnterEntry(ctx *parser2.EntryContext) { location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext) location.ChangeBothLines(s.hostsContext.line) - s.Parser.Tree.Entries[location.Start.Line] = &HostsEntry{ + s.Parser.Tree.Entries.Put(location.Start.Line, &HostsEntry{ Location: location, - } + }) } var containsPortPattern = regexp.MustCompile(`:[0-9]+$`) @@ -69,7 +69,8 @@ func (s *hostsParserListener) EnterIpAddress(ctx *parser2.IpAddressContext) { }) } - entry := s.Parser.Tree.Entries[location.Start.Line] + rawEntry, _ := s.Parser.Tree.Entries.Get(location.Start.Line) + entry := rawEntry.(*HostsEntry) entry.IPAddress = &HostsIPAddress{ Location: location, @@ -81,21 +82,21 @@ func (s *hostsParserListener) EnterHostname(ctx *parser2.HostnameContext) { location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext) location.ChangeBothLines(s.hostsContext.line) - entry := s.Parser.Tree.Entries[location.Start.Line] + rawEntry, _ := s.Parser.Tree.Entries.Get(location.Start.Line) + entry := rawEntry.(*HostsEntry) entry.Hostname = &HostsHostname{ Location: location, Value: ctx.GetText(), } - - s.Parser.Tree.Entries[location.Start.Line] = entry } func (s *hostsParserListener) EnterAliases(ctx *parser2.AliasesContext) { location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext) location.ChangeBothLines(s.hostsContext.line) - entry := s.Parser.Tree.Entries[location.Start.Line] + rawEntry, _ := s.Parser.Tree.Entries.Get(location.Start.Line) + entry := rawEntry.(*HostsEntry) aliases := make([]*HostsHostname, 0) @@ -106,7 +107,8 @@ func (s *hostsParserListener) EnterAlias(ctx *parser2.AliasContext) { location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext) location.ChangeBothLines(s.hostsContext.line) - entry := s.Parser.Tree.Entries[location.Start.Line] + rawEntry, _ := s.Parser.Tree.Entries.Get(location.Start.Line) + entry := rawEntry.(*HostsEntry) alias := HostsHostname{ Location: location, diff --git a/handlers/hosts/ast/parser.go b/handlers/hosts/ast/parser.go index 42dd6c6..99b760c 100644 --- a/handlers/hosts/ast/parser.go +++ b/handlers/hosts/ast/parser.go @@ -7,11 +7,14 @@ import ( "regexp" "github.com/antlr4-go/antlr/v4" + "github.com/emirpasic/gods/maps/treemap" + + gods "github.com/emirpasic/gods/utils" ) func (p *HostsParser) Clear() { p.Tree = HostsTree{ - Entries: make(map[uint32]*HostsEntry), + Entries: treemap.NewWith(gods.UInt32Comparator), } p.CommentLines = make(map[uint32]struct{}) } @@ -44,8 +47,8 @@ func (p *HostsParser) parseStatement( antlrParser.LineStatement(), ) - errors = append(errors, errorListener.Errors...) errors = append(errors, listener.Errors...) + errors = append(errors, errorListener.Errors...) return errors } diff --git a/handlers/hosts/ast/parser_test.go b/handlers/hosts/ast/parser_test.go index e390a96..c62b075 100644 --- a/handlers/hosts/ast/parser_test.go +++ b/handlers/hosts/ast/parser_test.go @@ -18,3 +18,34 @@ func TestParserInvalidWithPort( t.Fatalf("Expected 1 error, but got %v", errors) } } + +func TestParserValidComplexExample( + t *testing.T, +) { + input := utils.Dedent(` +1.2.3.4 hello.com alias.com example.com +1.2.3.5 hello1.com alias1.com example1.com +192.168.1.1 goodbye.com +`) + parser := NewHostsParser() + errors := parser.Parse(input) + + if len(errors) != 0 { + t.Fatalf("Expected no errors, but got %v", errors) + } + + if !(parser.Tree.Entries.Size() == 3) { + t.Fatalf("Expected 3 entries, but got %v", parser.Tree.Entries.Size()) + } + + rawEntry, _ := parser.Tree.Entries.Get(uint32(0)) + entry := rawEntry.(*HostsEntry) + + if !(entry.IPAddress.Value.String() == "1.2.3.4") { + t.Errorf("Expected IP address to be 1.2.3.4, but got %v", entry.IPAddress.Value) + } + + if !(entry.Hostname.Value == "hello.com") { + t.Errorf("Expected hostname to be hello.com, but got %v", entry.Hostname.Value) + } +} diff --git a/handlers/hosts/fields/documentation-fields.go b/handlers/hosts/fields/documentation-fields.go index 83837a8..9d15411 100644 --- a/handlers/hosts/fields/documentation-fields.go +++ b/handlers/hosts/fields/documentation-fields.go @@ -9,5 +9,5 @@ var IPAddressField = docvalues.IPAddressValue{ var HostnameField = docvalues.DocumentationValue{ Documentation: `Host names may contain only alphanumeric characters, minus signs ("-"), and periods ("."). They must begin with an alphabetic character and end with an alphanumeric character. Optional aliases provide for name changes, alternate spellings, shorter hostnames, or generic hostnames (for example, localhost).`, - Value: docvalues.DomainValue(), + Value: docvalues.StringValue{}, } diff --git a/handlers/hosts/handlers/code-actions.go b/handlers/hosts/handlers/code-actions.go index 7618226..4d91dcf 100644 --- a/handlers/hosts/handlers/code-actions.go +++ b/handlers/hosts/handlers/code-actions.go @@ -36,14 +36,17 @@ func CodeActionInlineAliasesArgsFromArguments(arguments map[string]any) CodeActi } func (args CodeActionInlineAliasesArgs) RunCommand(hostsParser ast.HostsParser) (*protocol.ApplyWorkspaceEditParams, error) { - fromEntry := hostsParser.Tree.Entries[args.FromLine] - toEntry := hostsParser.Tree.Entries[args.ToLine] + rawFromEntry, foundFromEntry := hostsParser.Tree.Entries.Get(args.FromLine) + rawToEntry, foundToEntry := hostsParser.Tree.Entries.Get(args.ToLine) - if fromEntry == nil || toEntry == nil { + if !foundFromEntry || !foundToEntry { // Weird return nil, nil } + fromEntry := rawFromEntry.(*ast.HostsEntry) + toEntry := rawToEntry.(*ast.HostsEntry) + var insertCharacter uint32 if toEntry.Aliases != nil { diff --git a/handlers/hosts/lsp/text-document-hover.go b/handlers/hosts/lsp/text-document-hover.go index 1c6484e..086daa5 100644 --- a/handlers/hosts/lsp/text-document-hover.go +++ b/handlers/hosts/lsp/text-document-hover.go @@ -25,13 +25,14 @@ func TextDocumentHover( return nil, nil } - entry, found := document.Parser.Tree.Entries[line] + rawEntry, found := document.Parser.Tree.Entries.Get(line) if !found { // Empty line return nil, nil } + entry := rawEntry.(*ast.HostsEntry) target := handlers.GetHoverTargetInEntry(*entry, character) var hostname *ast.HostsHostname From a7dc7fc6e847b1fe2d20c418568a6d832659c379 Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Sun, 8 Sep 2024 22:08:00 +0200 Subject: [PATCH 003/133] fix(hosts): Fix ip address detection --- handlers/hosts/analyzer/resolver.go | 23 ++++++++++++----- handlers/hosts/analyzer/resolver_test.go | 33 ++++++++++++++++++++++++ handlers/hosts/indexes/resolver.go | 6 ++--- 3 files changed, 53 insertions(+), 9 deletions(-) diff --git a/handlers/hosts/analyzer/resolver.go b/handlers/hosts/analyzer/resolver.go index d59b412..bedbfe5 100644 --- a/handlers/hosts/analyzer/resolver.go +++ b/handlers/hosts/analyzer/resolver.go @@ -19,9 +19,9 @@ func createEntry( } if ipv4 := ip.To4(); ipv4 != nil { - entry.IPv4Address = ipv4 + entry.IPv4Address = &ipv4 } else if ipv6 := ip.To16(); ipv6 != nil { - entry.IPv6Address = ipv6 + entry.IPv6Address = &ipv6 } return entry @@ -35,7 +35,7 @@ type hostnameEntry struct { func createResolverFromParser(p ast.HostsParser) (indexes.Resolver, []common.LSPError) { errors := make([]common.LSPError, 0) resolver := indexes.Resolver{ - Entries: make(map[string]indexes.ResolverEntry), + Entries: make(map[string]*indexes.ResolverEntry), } it := p.Tree.Entries.Iterator() @@ -64,12 +64,22 @@ func createResolverFromParser(p ast.HostsParser) (indexes.Resolver, []common.LSP ) for _, hostName := range hostNames { - entry := createEntry( + newResolv := createEntry( lineNumber, entry.IPAddress.Value.IP, ) if resolv, found := resolver.Entries[hostName.HostName]; found { + if resolv.IPv4Address == nil && newResolv.IPv4Address != nil { + resolv.IPv4Address = newResolv.IPv4Address + continue + } + + if resolv.IPv6Address == nil && newResolv.IPv6Address != nil { + resolv.IPv6Address = newResolv.IPv6Address + continue + } + errors = append( errors, common.LSPError{ @@ -80,9 +90,10 @@ func createResolverFromParser(p ast.HostsParser) (indexes.Resolver, []common.LSP }, }, ) - } else { - resolver.Entries[hostName.HostName] = entry + continue } + + resolver.Entries[hostName.HostName] = &newResolv } } } diff --git a/handlers/hosts/analyzer/resolver_test.go b/handlers/hosts/analyzer/resolver_test.go index 0dd8337..d4deb2f 100644 --- a/handlers/hosts/analyzer/resolver_test.go +++ b/handlers/hosts/analyzer/resolver_test.go @@ -115,3 +115,36 @@ func TestResolverEntriesWithComplexOverlapping( t.Errorf("Expected test.com to have no IPv4 address, but got %v", resolver.Entries["test.com"].IPv4Address) } } + +func TestResolverEntriesWithDoubleHostNameButDifferentIPs( + t *testing.T, +) { + input := utils.Dedent(` +127.0.0.1 hello.com +::1 hello.com +`) + parser := ast.NewHostsParser() + errors := parser.Parse(input) + + if len(errors) != 0 { + t.Fatalf("PARER FAILED! Expected no errors, but got %v", errors) + } + + resolver, errors := createResolverFromParser(parser) + + if len(errors) != 0 { + t.Fatalf("Expected no errors, but got %v", errors) + } + + if len(resolver.Entries) != 1 { + t.Errorf("Expected 1 entry, but got %v", len(resolver.Entries)) + } + + if !(resolver.Entries["hello.com"].IPv4Address.String() == "127.0.0.1") { + t.Errorf("Expected hello.com's ipv4 address to be 127.0.0.1, but got %v", resolver.Entries["hello.com"].IPv4Address) + } + + if !(resolver.Entries["hello.com"].IPv6Address.String() == "::1") { + t.Errorf("Expected hello.com's ipv6 address to be ::1, but got %v", resolver.Entries["hello.com"].IPv6Address) + } +} diff --git a/handlers/hosts/indexes/resolver.go b/handlers/hosts/indexes/resolver.go index aabb6f4..dc3655c 100644 --- a/handlers/hosts/indexes/resolver.go +++ b/handlers/hosts/indexes/resolver.go @@ -5,8 +5,8 @@ import ( ) type ResolverEntry struct { - IPv4Address net.IP - IPv6Address net.IP + IPv4Address *net.IP + IPv6Address *net.IP Line uint32 } @@ -19,5 +19,5 @@ func (e ResolverEntry) GetInfo() string { } type Resolver struct { - Entries map[string]ResolverEntry + Entries map[string]*ResolverEntry } From e0c9c44f389fd69dd8ea8dc1845662d0d9cb0594 Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Sun, 8 Sep 2024 22:55:25 +0200 Subject: [PATCH 004/133] fix(fstab): Several improvements and bugfixes --- doc-values/value-array.go | 2 +- doc-values/value-or.go | 2 +- handlers/fstab/fstab_test.go | 41 ++++++++------- .../completions.go} | 52 +++++-------------- handlers/fstab/{ => handlers}/hover-fields.go | 2 +- .../hover.go} | 45 +++++----------- .../fstab/lsp/text-document-completion.go | 34 ++++++++++++ .../{ => lsp}/text-document-did-change.go | 13 ++--- handlers/fstab/lsp/text-document-did-close.go | 13 +++++ handlers/fstab/lsp/text-document-did-open.go | 43 +++++++++++++++ handlers/fstab/lsp/text-document-hover.go | 29 +++++++++++ handlers/fstab/{ => parser}/parser.go | 37 +++++++------ handlers/fstab/shared.go | 7 --- handlers/fstab/shared/document.go | 8 +++ handlers/fstab/text-document-did-open.go | 30 ----------- root-handler/text-document-code-action.go | 2 +- root-handler/text-document-completion.go | 2 +- root-handler/text-document-did-change.go | 2 +- root-handler/text-document-did-close.go | 4 +- root-handler/text-document-did-open.go | 5 +- root-handler/text-document-hover.go | 2 +- 21 files changed, 214 insertions(+), 161 deletions(-) rename handlers/fstab/{text-document-completion.go => handlers/completions.go} (62%) rename handlers/fstab/{ => handlers}/hover-fields.go (99%) rename handlers/fstab/{text-document-hover.go => handlers/hover.go} (51%) create mode 100644 handlers/fstab/lsp/text-document-completion.go rename handlers/fstab/{ => lsp}/text-document-did-change.go (76%) create mode 100644 handlers/fstab/lsp/text-document-did-close.go create mode 100644 handlers/fstab/lsp/text-document-did-open.go create mode 100644 handlers/fstab/lsp/text-document-hover.go rename handlers/fstab/{ => parser}/parser.go (94%) delete mode 100644 handlers/fstab/shared.go create mode 100644 handlers/fstab/shared/document.go delete mode 100644 handlers/fstab/text-document-did-open.go diff --git a/doc-values/value-array.go b/doc-values/value-array.go index 0f200d0..1fd7263 100644 --- a/doc-values/value-array.go +++ b/doc-values/value-array.go @@ -126,7 +126,7 @@ func (v ArrayValue) getCurrentValue(line string, cursor uint32) (string, uint32) line, v.Separator, // defaults - min(len(line)-1, int(cursor)), + min(len(line)-1, int(cursor)-1), ) if found { diff --git a/doc-values/value-or.go b/doc-values/value-or.go index 8f9e681..3991a75 100644 --- a/doc-values/value-or.go +++ b/doc-values/value-or.go @@ -63,7 +63,7 @@ func (v OrValue) FetchCompletions(line string, cursor uint32) []protocol.Complet _, found := utils.FindPreviousCharacter( line, keyEnumValue.Separator, - max(0, int(cursor-1)), + int(cursor-1), ) if found { diff --git a/handlers/fstab/fstab_test.go b/handlers/fstab/fstab_test.go index 4e6d47d..1bdeed2 100644 --- a/handlers/fstab/fstab_test.go +++ b/handlers/fstab/fstab_test.go @@ -2,6 +2,8 @@ package fstab import ( fstabdocumentation "config-lsp/handlers/fstab/documentation" + handlers "config-lsp/handlers/fstab/handlers" + "config-lsp/handlers/fstab/parser" "config-lsp/utils" "testing" ) @@ -17,53 +19,55 @@ LABEL=test /mnt/test btrfs subvol=backup,fat=32 0 0 // to be wrong. Use a treemap instead of a map. func TestValidBasicExample(t *testing.T) { // Arrange - parser := FstabParser{} + p := parser.FstabParser{} + p.Clear() - errors := parser.ParseFromContent(sampleValidBasicExample) + errors := p.ParseFromContent(sampleValidBasicExample) if len(errors) > 0 { t.Fatal("ParseFromContent failed with error", errors) } // Get hover for first field - entry := parser.entries[0] + rawEntry, _ := p.Entries.Get(uint32(0)) + entry := rawEntry.(parser.FstabEntry) println("Getting hover info") { - hover, err := getHoverInfo(&entry, uint32(0)) + hover, err := handlers.GetHoverInfo(&entry, uint32(0)) if err != nil { t.Fatal("getHoverInfo failed with error", err) } - if hover.Contents != SpecHoverField.Contents { - t.Fatal("getHoverInfo failed to return correct hover content. Got:", hover.Contents, "but expected:", SpecHoverField.Contents) + if hover.Contents != handlers.SpecHoverField.Contents { + t.Fatal("getHoverInfo failed to return correct hover content. Got:", hover.Contents, "but expected:", handlers.SpecHoverField.Contents) } // Get hover for second field - hover, err = getHoverInfo(&entry, uint32(11)) + hover, err = handlers.GetHoverInfo(&entry, uint32(11)) if err != nil { t.Fatal("getHoverInfo failed with error", err) } - if hover.Contents != MountPointHoverField.Contents { - t.Fatal("getHoverInfo failed to return correct hover content. Got:", hover.Contents, "but expected:", MountPointHoverField.Contents) + if hover.Contents != handlers.MountPointHoverField.Contents { + t.Fatal("getHoverInfo failed to return correct hover content. Got:", hover.Contents, "but expected:", handlers.MountPointHoverField.Contents) } - hover, err = getHoverInfo(&entry, uint32(20)) + hover, err = handlers.GetHoverInfo(&entry, uint32(20)) if err != nil { t.Fatal("getHoverInfo failed with error", err) } - if hover.Contents != MountPointHoverField.Contents { - t.Fatal("getHoverInfo failed to return correct hover content. Got:", hover.Contents, "but expected:", MountPointHoverField.Contents) + if hover.Contents != handlers.MountPointHoverField.Contents { + t.Fatal("getHoverInfo failed to return correct hover content. Got:", hover.Contents, "but expected:", handlers.MountPointHoverField.Contents) } } println("Getting completions") { - completions, err := getCompletion(entry.Line, uint32(0)) + completions, err := handlers.GetCompletion(entry.Line, uint32(0)) if err != nil { t.Fatal("getCompletion failed with error", err) @@ -79,7 +83,7 @@ func TestValidBasicExample(t *testing.T) { } { - completions, err := getCompletion(entry.Line, uint32(21)) + completions, err := handlers.GetCompletion(entry.Line, uint32(21)) if err != nil { t.Fatal("getCompletion failed with error", err) @@ -93,7 +97,7 @@ func TestValidBasicExample(t *testing.T) { println("Checking values") { - diagnostics := parser.AnalyzeValues() + diagnostics := p.AnalyzeValues() if len(diagnostics) > 0 { t.Fatal("AnalyzeValues failed with error", diagnostics) @@ -103,9 +107,10 @@ func TestValidBasicExample(t *testing.T) { func TestInvalidOptionsExample(t *testing.T) { // Arrange - parser := FstabParser{} + p := parser.FstabParser{} + p.Clear() - errors := parser.ParseFromContent(sampleInvalidOptionsExample) + errors := p.ParseFromContent(sampleInvalidOptionsExample) if len(errors) > 0 { t.Fatal("ParseFromContent returned error", errors) @@ -114,7 +119,7 @@ func TestInvalidOptionsExample(t *testing.T) { // Get hover for first field println("Checking values") { - diagnostics := parser.AnalyzeValues() + diagnostics := p.AnalyzeValues() if len(diagnostics) == 0 { t.Fatal("AnalyzeValues should have returned error") diff --git a/handlers/fstab/text-document-completion.go b/handlers/fstab/handlers/completions.go similarity index 62% rename from handlers/fstab/text-document-completion.go rename to handlers/fstab/handlers/completions.go index 5358634..66f07d6 100644 --- a/handlers/fstab/text-document-completion.go +++ b/handlers/fstab/handlers/completions.go @@ -1,65 +1,41 @@ -package fstab +package handlers import ( - docvalues "config-lsp/doc-values" - fstabdocumentation "config-lsp/handlers/fstab/documentation" - - "github.com/tliron/glsp" - protocol "github.com/tliron/glsp/protocol_3_16" + "config-lsp/doc-values" + "config-lsp/handlers/fstab/documentation" + "config-lsp/handlers/fstab/parser" + "github.com/tliron/glsp/protocol_3_16" ) -func TextDocumentCompletion(context *glsp.Context, params *protocol.CompletionParams) (any, error) { - parser := documentParserMap[params.TextDocument.URI] - - entry, found := parser.GetEntry(params.Position.Line) - - if !found { - // Empty line, return spec completions - return fstabdocumentation.SpecField.FetchCompletions( - "", - params.Position.Character, - ), nil - } - - if entry.Type == FstabEntryTypeComment { - return nil, nil - } - - cursor := params.Position.Character - line := entry.Line - - return getCompletion(line, cursor) -} - -func getCompletion( - line FstabLine, +func GetCompletion( + line parser.FstabLine, cursor uint32, ) ([]protocol.CompletionItem, error) { targetField := line.GetFieldAtPosition(cursor) switch targetField { - case FstabFieldSpec: + case parser.FstabFieldSpec: value, cursor := GetFieldSafely(line.Fields.Spec, cursor) return fstabdocumentation.SpecField.FetchCompletions( value, cursor, ), nil - case FstabFieldMountPoint: + case parser.FstabFieldMountPoint: value, cursor := GetFieldSafely(line.Fields.MountPoint, cursor) return fstabdocumentation.MountPointField.FetchCompletions( value, cursor, ), nil - case FstabFieldFileSystemType: + case parser.FstabFieldFileSystemType: value, cursor := GetFieldSafely(line.Fields.FilesystemType, cursor) return fstabdocumentation.FileSystemTypeField.FetchCompletions( value, cursor, ), nil - case FstabFieldOptions: + case parser.FstabFieldOptions: fileSystemType := line.Fields.FilesystemType.Value var optionsField docvalues.Value @@ -78,14 +54,14 @@ func getCompletion( ) return completions, nil - case FstabFieldFreq: + case parser.FstabFieldFreq: value, cursor := GetFieldSafely(line.Fields.Freq, cursor) return fstabdocumentation.FreqField.FetchCompletions( value, cursor, ), nil - case FstabFieldPass: + case parser.FstabFieldPass: value, cursor := GetFieldSafely(line.Fields.Pass, cursor) return fstabdocumentation.PassField.FetchCompletions( @@ -99,7 +75,7 @@ func getCompletion( // Safely get value and new cursor position // If field is nil, return empty string and 0 -func GetFieldSafely(field *Field, character uint32) (string, uint32) { +func GetFieldSafely(field *parser.Field, character uint32) (string, uint32) { if field == nil { return "", 0 } diff --git a/handlers/fstab/hover-fields.go b/handlers/fstab/handlers/hover-fields.go similarity index 99% rename from handlers/fstab/hover-fields.go rename to handlers/fstab/handlers/hover-fields.go index 38a5aec..4310b52 100644 --- a/handlers/fstab/hover-fields.go +++ b/handlers/fstab/handlers/hover-fields.go @@ -1,4 +1,4 @@ -package fstab +package handlers import protocol "github.com/tliron/glsp/protocol_3_16" diff --git a/handlers/fstab/text-document-hover.go b/handlers/fstab/handlers/hover.go similarity index 51% rename from handlers/fstab/text-document-hover.go rename to handlers/fstab/handlers/hover.go index 96fa182..d857b6b 100644 --- a/handlers/fstab/text-document-hover.go +++ b/handlers/fstab/handlers/hover.go @@ -1,46 +1,25 @@ -package fstab +package handlers import ( - docvalues "config-lsp/doc-values" - fstabdocumentation "config-lsp/handlers/fstab/documentation" + "config-lsp/doc-values" + "config-lsp/handlers/fstab/documentation" + "config-lsp/handlers/fstab/parser" + "github.com/tliron/glsp/protocol_3_16" "strings" - - "github.com/tliron/glsp" - protocol "github.com/tliron/glsp/protocol_3_16" ) -func TextDocumentHover(context *glsp.Context, params *protocol.HoverParams) (*protocol.Hover, error) { - cursor := params.Position.Character - - parser := documentParserMap[params.TextDocument.URI] - - entry, found := parser.GetEntry(params.Position.Line) - - // Empty line - if !found { - return nil, nil - } - - // Comment line - if entry.Type == FstabEntryTypeComment { - return nil, nil - } - - return getHoverInfo(entry, cursor) -} - -func getHoverInfo(entry *FstabEntry, cursor uint32) (*protocol.Hover, error) { +func GetHoverInfo(entry *parser.FstabEntry, cursor uint32) (*protocol.Hover, error) { line := entry.Line targetField := line.GetFieldAtPosition(cursor) switch targetField { - case FstabFieldSpec: + case parser.FstabFieldSpec: return &SpecHoverField, nil - case FstabFieldMountPoint: + case parser.FstabFieldMountPoint: return &MountPointHoverField, nil - case FstabFieldFileSystemType: + case parser.FstabFieldFileSystemType: return &FileSystemTypeField, nil - case FstabFieldOptions: + case parser.FstabFieldOptions: fileSystemType := line.Fields.FilesystemType.Value var optionsField docvalues.Value @@ -61,9 +40,9 @@ func getHoverInfo(entry *FstabEntry, cursor uint32) (*protocol.Hover, error) { } return &hover, nil - case FstabFieldFreq: + case parser.FstabFieldFreq: return &FreqHoverField, nil - case FstabFieldPass: + case parser.FstabFieldPass: return &PassHoverField, nil } diff --git a/handlers/fstab/lsp/text-document-completion.go b/handlers/fstab/lsp/text-document-completion.go new file mode 100644 index 0000000..4c43e6f --- /dev/null +++ b/handlers/fstab/lsp/text-document-completion.go @@ -0,0 +1,34 @@ +package lsp + +import ( + fstabdocumentation "config-lsp/handlers/fstab/documentation" + "config-lsp/handlers/fstab/handlers" + "config-lsp/handlers/fstab/parser" + "config-lsp/handlers/fstab/shared" + + "github.com/tliron/glsp" + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func TextDocumentCompletion(context *glsp.Context, params *protocol.CompletionParams) (any, error) { + p := shared.DocumentParserMap[params.TextDocument.URI] + + entry, found := p.GetEntry(params.Position.Line) + + if !found { + // Empty line, return spec completions + return fstabdocumentation.SpecField.FetchCompletions( + "", + params.Position.Character, + ), nil + } + + if entry.Type == parser.FstabEntryTypeComment { + return nil, nil + } + + cursor := params.Position.Character + line := entry.Line + + return handlers.GetCompletion(line, cursor) +} diff --git a/handlers/fstab/text-document-did-change.go b/handlers/fstab/lsp/text-document-did-change.go similarity index 76% rename from handlers/fstab/text-document-did-change.go rename to handlers/fstab/lsp/text-document-did-change.go index 8b465b3..2864e19 100644 --- a/handlers/fstab/text-document-did-change.go +++ b/handlers/fstab/lsp/text-document-did-change.go @@ -1,7 +1,8 @@ -package fstab +package lsp import ( "config-lsp/common" + "config-lsp/handlers/fstab/shared" "config-lsp/utils" "github.com/tliron/glsp" protocol "github.com/tliron/glsp/protocol_3_16" @@ -14,11 +15,11 @@ func TextDocumentDidChange( content := params.ContentChanges[0].(protocol.TextDocumentContentChangeEventWhole).Text common.ClearDiagnostics(context, params.TextDocument.URI) - parser := documentParserMap[params.TextDocument.URI] - parser.Clear() + p := shared.DocumentParserMap[params.TextDocument.URI] + p.Clear() diagnostics := make([]protocol.Diagnostic, 0) - errors := parser.ParseFromContent(content) + errors := p.ParseFromContent(content) if len(errors) > 0 { diagnostics = append(diagnostics, utils.Map( @@ -27,10 +28,10 @@ func TextDocumentDidChange( return err.ToDiagnostic() }, )...) + } else { + diagnostics = append(diagnostics, p.AnalyzeValues()...) } - diagnostics = append(diagnostics, parser.AnalyzeValues()...) - if len(diagnostics) > 0 { common.SendDiagnostics(context, params.TextDocument.URI, diagnostics) } diff --git a/handlers/fstab/lsp/text-document-did-close.go b/handlers/fstab/lsp/text-document-did-close.go new file mode 100644 index 0000000..a602a65 --- /dev/null +++ b/handlers/fstab/lsp/text-document-did-close.go @@ -0,0 +1,13 @@ +package lsp + +import ( + shared "config-lsp/handlers/fstab/shared" + "github.com/tliron/glsp" + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func TextDocumentDidClose(context *glsp.Context, params *protocol.DidCloseTextDocumentParams) error { + delete(shared.DocumentParserMap, params.TextDocument.URI) + + return nil +} diff --git a/handlers/fstab/lsp/text-document-did-open.go b/handlers/fstab/lsp/text-document-did-open.go new file mode 100644 index 0000000..6658b21 --- /dev/null +++ b/handlers/fstab/lsp/text-document-did-open.go @@ -0,0 +1,43 @@ +package lsp + +import ( + "config-lsp/common" + "config-lsp/handlers/fstab/parser" + "config-lsp/handlers/fstab/shared" + "config-lsp/utils" + "github.com/tliron/glsp" + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func TextDocumentDidOpen( + context *glsp.Context, + params *protocol.DidOpenTextDocumentParams, +) error { + common.ClearDiagnostics(context, params.TextDocument.URI) + + p := parser.FstabParser{} + p.Clear() + shared.DocumentParserMap[params.TextDocument.URI] = &p + + content := params.TextDocument.Text + + diagnostics := make([]protocol.Diagnostic, 0) + errors := p.ParseFromContent(content) + + if len(errors) > 0 { + diagnostics = append(diagnostics, utils.Map( + errors, + func(err common.ParseError) protocol.Diagnostic { + return err.ToDiagnostic() + }, + )...) + } else { + diagnostics = append(diagnostics, p.AnalyzeValues()...) + } + + if len(diagnostics) > 0 { + common.SendDiagnostics(context, params.TextDocument.URI, diagnostics) + } + + return nil +} diff --git a/handlers/fstab/lsp/text-document-hover.go b/handlers/fstab/lsp/text-document-hover.go new file mode 100644 index 0000000..310706e --- /dev/null +++ b/handlers/fstab/lsp/text-document-hover.go @@ -0,0 +1,29 @@ +package lsp + +import ( + "config-lsp/handlers/fstab/handlers" + "config-lsp/handlers/fstab/parser" + "config-lsp/handlers/fstab/shared" + "github.com/tliron/glsp" + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func TextDocumentHover(context *glsp.Context, params *protocol.HoverParams) (*protocol.Hover, error) { + cursor := params.Position.Character + + p := shared.DocumentParserMap[params.TextDocument.URI] + + entry, found := p.GetEntry(params.Position.Line) + + // Empty line + if !found { + return nil, nil + } + + // Comment line + if entry.Type == parser.FstabEntryTypeComment { + return nil, nil + } + + return handlers.GetHoverInfo(entry, cursor) +} diff --git a/handlers/fstab/parser.go b/handlers/fstab/parser/parser.go similarity index 94% rename from handlers/fstab/parser.go rename to handlers/fstab/parser/parser.go index 782f346..15ee905 100644 --- a/handlers/fstab/parser.go +++ b/handlers/fstab/parser/parser.go @@ -1,4 +1,4 @@ -package fstab +package parser import ( "config-lsp/common" @@ -6,10 +6,12 @@ import ( fstabdocumentation "config-lsp/handlers/fstab/documentation" "fmt" "regexp" - "slices" "strings" + "github.com/emirpasic/gods/maps/treemap" protocol "github.com/tliron/glsp/protocol_3_16" + + gods "github.com/emirpasic/gods/utils" ) var commentPattern = regexp.MustCompile(`^\s*#`) @@ -203,7 +205,8 @@ type FstabEntry struct { } type FstabParser struct { - entries []FstabEntry + // [uint32]FstabEntry - line number to entry mapping + Entries *treemap.Map } func (p *FstabParser) AddLine(line string, lineNumber int) error { @@ -302,7 +305,7 @@ func (p *FstabParser) AddLine(line string, lineNumber int) error { }, }, } - p.entries = append(p.entries, entry) + p.Entries.Put(entry.Line.Line, entry) return nil } @@ -311,7 +314,7 @@ func (p *FstabParser) AddCommentLine(line string, lineNumber int) { entry := FstabLine{ Line: uint32(lineNumber), } - p.entries = append(p.entries, FstabEntry{ + p.Entries.Put(entry.Line, FstabEntry{ Type: FstabEntryTypeComment, Line: entry, }) @@ -345,33 +348,29 @@ func (p *FstabParser) ParseFromContent(content string) []common.ParseError { } func (p *FstabParser) GetEntry(line uint32) (*FstabEntry, bool) { - index, found := slices.BinarySearchFunc(p.entries, line, func(entry FstabEntry, line uint32) int { - if entry.Line.Line < line { - return -1 - } - - if entry.Line.Line > line { - return 1 - } - - return 0 - }) + rawEntry, found := p.Entries.Get(line) if !found { return nil, false } - return &p.entries[index], true + entry := rawEntry.(FstabEntry) + + return &entry, true } func (p *FstabParser) Clear() { - p.entries = []FstabEntry{} + p.Entries = treemap.NewWith(gods.UInt32Comparator) } func (p *FstabParser) AnalyzeValues() []protocol.Diagnostic { diagnostics := []protocol.Diagnostic{} - for _, entry := range p.entries { + it := p.Entries.Iterator() + + for it.Next() { + entry := it.Value().(FstabEntry) + switch entry.Type { case FstabEntryTypeLine: newDiagnostics := entry.Line.CheckIsValid() diff --git a/handlers/fstab/shared.go b/handlers/fstab/shared.go deleted file mode 100644 index 05aaebb..0000000 --- a/handlers/fstab/shared.go +++ /dev/null @@ -1,7 +0,0 @@ -package fstab - -import ( - protocol "github.com/tliron/glsp/protocol_3_16" -) - -var documentParserMap = map[protocol.DocumentUri]*FstabParser{} diff --git a/handlers/fstab/shared/document.go b/handlers/fstab/shared/document.go new file mode 100644 index 0000000..e25de3b --- /dev/null +++ b/handlers/fstab/shared/document.go @@ -0,0 +1,8 @@ +package shared + +import ( + "config-lsp/handlers/fstab/parser" + protocol "github.com/tliron/glsp/protocol_3_16" +) + +var DocumentParserMap = map[protocol.DocumentUri]*parser.FstabParser{} diff --git a/handlers/fstab/text-document-did-open.go b/handlers/fstab/text-document-did-open.go deleted file mode 100644 index d64f3ea..0000000 --- a/handlers/fstab/text-document-did-open.go +++ /dev/null @@ -1,30 +0,0 @@ -package fstab - -import ( - "config-lsp/common" - "config-lsp/utils" - "github.com/tliron/glsp" - protocol "github.com/tliron/glsp/protocol_3_16" -) - -func TextDocumentDidOpen( - context *glsp.Context, - params *protocol.DidOpenTextDocumentParams, -) error { - common.ClearDiagnostics(context, params.TextDocument.URI) - - parser := FstabParser{} - documentParserMap[params.TextDocument.URI] = &parser - - errors := parser.ParseFromContent(params.TextDocument.Text) - diagnostics := utils.Map( - errors, - func(err common.ParseError) protocol.Diagnostic { - return err.ToDiagnostic() - }, - ) - - common.SendDiagnostics(context, params.TextDocument.URI, diagnostics) - - return nil -} diff --git a/root-handler/text-document-code-action.go b/root-handler/text-document-code-action.go index a1f0642..f1da029 100644 --- a/root-handler/text-document-code-action.go +++ b/root-handler/text-document-code-action.go @@ -24,7 +24,7 @@ func TextDocumentCodeAction(context *glsp.Context, params *protocol.CodeActionPa switch *language { case LanguageFstab: - fallthrough + return nil, nil case LanguageHosts: return hosts.TextDocumentCodeAction(context, params) case LanguageSSHDConfig: diff --git a/root-handler/text-document-completion.go b/root-handler/text-document-completion.go index bd37e79..160bcb2 100644 --- a/root-handler/text-document-completion.go +++ b/root-handler/text-document-completion.go @@ -2,7 +2,7 @@ package roothandler import ( aliases "config-lsp/handlers/aliases/lsp" - "config-lsp/handlers/fstab" + fstab "config-lsp/handlers/fstab/lsp" hosts "config-lsp/handlers/hosts/lsp" wireguard "config-lsp/handlers/wireguard/lsp" diff --git a/root-handler/text-document-did-change.go b/root-handler/text-document-did-change.go index 087abc3..a6291af 100644 --- a/root-handler/text-document-did-change.go +++ b/root-handler/text-document-did-change.go @@ -2,7 +2,7 @@ package roothandler import ( aliases "config-lsp/handlers/aliases/lsp" - "config-lsp/handlers/fstab" + fstab "config-lsp/handlers/fstab/lsp" hosts "config-lsp/handlers/hosts/lsp" wireguard "config-lsp/handlers/wireguard/lsp" diff --git a/root-handler/text-document-did-close.go b/root-handler/text-document-did-close.go index 1790fca..0d56091 100644 --- a/root-handler/text-document-did-close.go +++ b/root-handler/text-document-did-close.go @@ -2,6 +2,7 @@ package roothandler import ( aliases "config-lsp/handlers/aliases/lsp" + fstab "config-lsp/handlers/fstab/lsp" hosts "config-lsp/handlers/hosts/lsp" wireguard "config-lsp/handlers/wireguard/lsp" @@ -26,8 +27,9 @@ func TextDocumentDidClose(context *glsp.Context, params *protocol.DidCloseTextDo rootHandler.RemoveDocument(params.TextDocument.URI) switch *language { - case LanguageFstab: case LanguageSSHDConfig: + case LanguageFstab: + return fstab.TextDocumentDidClose(context, params) case LanguageWireguard: return wireguard.TextDocumentDidClose(context, params) case LanguageHosts: diff --git a/root-handler/text-document-did-open.go b/root-handler/text-document-did-open.go index 181afa2..799d6aa 100644 --- a/root-handler/text-document-did-open.go +++ b/root-handler/text-document-did-open.go @@ -2,11 +2,12 @@ package roothandler import ( "config-lsp/common" + "fmt" + aliases "config-lsp/handlers/aliases/lsp" - fstab "config-lsp/handlers/fstab" + fstab "config-lsp/handlers/fstab/lsp" hosts "config-lsp/handlers/hosts/lsp" wireguard "config-lsp/handlers/wireguard/lsp" - "fmt" "github.com/tliron/glsp" protocol "github.com/tliron/glsp/protocol_3_16" diff --git a/root-handler/text-document-hover.go b/root-handler/text-document-hover.go index 3e94d15..dfc15c6 100644 --- a/root-handler/text-document-hover.go +++ b/root-handler/text-document-hover.go @@ -2,7 +2,7 @@ package roothandler import ( aliases "config-lsp/handlers/aliases/lsp" - "config-lsp/handlers/fstab" + fstab "config-lsp/handlers/fstab/lsp" hosts "config-lsp/handlers/hosts/lsp" wireguard "config-lsp/handlers/wireguard/lsp" From 492c33a7a9dc26fef0397438598d0bd4c2c19540 Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Sun, 8 Sep 2024 23:43:11 +0200 Subject: [PATCH 005/133] fix(fstab): Fix tests --- handlers/fstab/fstab_test.go | 28 +++++++++++++--------------- 1 file changed, 13 insertions(+), 15 deletions(-) diff --git a/handlers/fstab/fstab_test.go b/handlers/fstab/fstab_test.go index 1bdeed2..da39d0c 100644 --- a/handlers/fstab/fstab_test.go +++ b/handlers/fstab/fstab_test.go @@ -8,21 +8,14 @@ import ( "testing" ) -var sampleValidBasicExample = ` -LABEL=test /mnt/test ext4 defaults 0 0 -` -var sampleInvalidOptionsExample = ` -LABEL=test /mnt/test btrfs subvol=backup,fat=32 0 0 -` - -// TODO: Improve `entries`, sometimes the indexes seem -// to be wrong. Use a treemap instead of a map. func TestValidBasicExample(t *testing.T) { - // Arrange + input := utils.Dedent(` +LABEL=test /mnt/test ext4 defaults 0 0 +`) p := parser.FstabParser{} p.Clear() - errors := p.ParseFromContent(sampleValidBasicExample) + errors := p.ParseFromContent(input) if len(errors) > 0 { t.Fatal("ParseFromContent failed with error", errors) @@ -77,8 +70,11 @@ func TestValidBasicExample(t *testing.T) { t.Fatal("getCompletion failed to return correct number of completions. Got:", len(completions), "but expected:", 4) } - if completions[0].Label != "UUID" && completions[0].Label != "PARTUID" { - t.Fatal("getCompletion failed to return correct label. Got:", completions[0].Label, "but expected:", "UUID") + if !(completions[0].Label == "LABEL" || + completions[1].Label == "LABEL" || + completions[2].Label == "LABEL" || + completions[3].Label == "LABEL") { + t.Fatal("getCompletion failed to return correct label. Got:", completions[0].Label, "but expected:", "LABEL") } } @@ -106,11 +102,13 @@ func TestValidBasicExample(t *testing.T) { } func TestInvalidOptionsExample(t *testing.T) { - // Arrange + input := utils.Dedent(` +LABEL=test /mnt/test btrfs subvol=backup,fat=32 0 0 +`) p := parser.FstabParser{} p.Clear() - errors := p.ParseFromContent(sampleInvalidOptionsExample) + errors := p.ParseFromContent(input) if len(errors) > 0 { t.Fatal("ParseFromContent returned error", errors) From af580fa624d8e5cccb3efd2f9314aeeda16913ba Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Mon, 9 Sep 2024 22:32:04 +0200 Subject: [PATCH 006/133] feat(sshd_config): Add first iteration of new sshd_config handler; Add ast; Add parser --- handlers/sshd_config/Config.g4 | 42 + handlers/sshd_config/ast/error-listener.go | 45 + handlers/sshd_config/ast/listener.go | 117 +++ handlers/sshd_config/ast/parser.go | 86 ++ handlers/sshd_config/ast/parser/Config.interp | 26 + handlers/sshd_config/ast/parser/Config.tokens | 6 + .../sshd_config/ast/parser/ConfigLexer.interp | 32 + .../sshd_config/ast/parser/ConfigLexer.tokens | 6 + .../ast/parser/config_base_listener.go | 52 + .../sshd_config/ast/parser/config_lexer.go | 118 +++ .../sshd_config/ast/parser/config_listener.go | 40 + .../sshd_config/ast/parser/config_parser.go | 919 ++++++++++++++++++ handlers/sshd_config/ast/sshd_config.go | 59 ++ 13 files changed, 1548 insertions(+) create mode 100644 handlers/sshd_config/Config.g4 create mode 100644 handlers/sshd_config/ast/error-listener.go create mode 100644 handlers/sshd_config/ast/listener.go create mode 100644 handlers/sshd_config/ast/parser.go create mode 100644 handlers/sshd_config/ast/parser/Config.interp create mode 100644 handlers/sshd_config/ast/parser/Config.tokens create mode 100644 handlers/sshd_config/ast/parser/ConfigLexer.interp create mode 100644 handlers/sshd_config/ast/parser/ConfigLexer.tokens create mode 100644 handlers/sshd_config/ast/parser/config_base_listener.go create mode 100644 handlers/sshd_config/ast/parser/config_lexer.go create mode 100644 handlers/sshd_config/ast/parser/config_listener.go create mode 100644 handlers/sshd_config/ast/parser/config_parser.go create mode 100644 handlers/sshd_config/ast/sshd_config.go diff --git a/handlers/sshd_config/Config.g4 b/handlers/sshd_config/Config.g4 new file mode 100644 index 0000000..65c951a --- /dev/null +++ b/handlers/sshd_config/Config.g4 @@ -0,0 +1,42 @@ +grammar Config; + +lineStatement + : (entry | (WHITESPACE? leadingComment) | WHITESPACE?) EOF + ; + +entry + : WHITESPACE? key? WHITESPACE value? WHITESPACE? leadingComment? + ; + +key + : STRING + ; + +value + : STRING + ; + +leadingComment + : HASH WHITESPACE? (STRING WHITESPACE?)+ + ; + + +HASH + : '#' + ; + +MATCH + : ('M' | 'm') ('A' | 'a') ('T' | 't') ('C' | 'c') ('H' | 'h') + ; + +WHITESPACE + : [ \t]+ + ; + +STRING + : ~(' ' | '\t' | '\r' | '\n' | '#')+ + ; + +NEWLINE + : '\r'? '\n' + ; diff --git a/handlers/sshd_config/ast/error-listener.go b/handlers/sshd_config/ast/error-listener.go new file mode 100644 index 0000000..74d4387 --- /dev/null +++ b/handlers/sshd_config/ast/error-listener.go @@ -0,0 +1,45 @@ +package ast + +import ( + "config-lsp/common" + + "github.com/antlr4-go/antlr/v4" +) + +type errorListenerContext struct { + line uint32 +} + +type errorListener struct { + *antlr.DefaultErrorListener + Errors []common.LSPError + context errorListenerContext +} + +func (d *errorListener) SyntaxError( + recognizer antlr.Recognizer, + offendingSymbol interface{}, + _ int, + character int, + message string, + error antlr.RecognitionException, +) { + line := d.context.line + d.Errors = append(d.Errors, common.LSPError{ + Range: common.CreateSingleCharRange(uint32(line), uint32(character)), + Err: common.SyntaxError{ + Message: message, + }, + }) +} + +func createErrorListener( + line uint32, +) errorListener { + return errorListener{ + Errors: make([]common.LSPError, 0), + context: errorListenerContext{ + line: line, + }, + } +} diff --git a/handlers/sshd_config/ast/listener.go b/handlers/sshd_config/ast/listener.go new file mode 100644 index 0000000..c574f96 --- /dev/null +++ b/handlers/sshd_config/ast/listener.go @@ -0,0 +1,117 @@ +package ast + +import ( + "config-lsp/common" + "config-lsp/handlers/sshd_config/ast/parser" + "strings" +) + +func createListener( + config *SSHConfig, + context *sshListenerContext, +) sshParserListener { + return sshParserListener{ + Config: config, + Errors: make([]common.LSPError, 0), + sshContext: context, + } +} + +type sshListenerContext struct { + line uint32 + currentOption *SSHOption + currentMatchBlock *SSHMatchBlock + isKeyAMatchBlock bool +} + +func createSSHListenerContext() *sshListenerContext { + context := new(sshListenerContext) + context.isKeyAMatchBlock = false + + return context +} + +type sshParserListener struct { + *parser.BaseConfigListener + Config *SSHConfig + Errors []common.LSPError + sshContext *sshListenerContext +} + +func (s *sshParserListener) EnterEntry(ctx *parser.EntryContext) { + location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext) + location.ChangeBothLines(s.sshContext.line) + + option := &SSHOption{ + LocationRange: location, + Value: ctx.GetText(), + } + + if s.sshContext.currentMatchBlock == nil { + s.Config.Options.Put( + location.Start.Line, + option, + ) + + s.sshContext.currentOption = option + } else { + s.sshContext.currentMatchBlock.Options.Put( + location.Start.Line, + option, + ) + + s.sshContext.currentOption = option + } +} + +func (s *sshParserListener) EnterKey(ctx *parser.KeyContext) { + location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext) + location.ChangeBothLines(s.sshContext.line) + + text := ctx.GetText() + + if strings.ToLower(text) == "match" { + s.sshContext.isKeyAMatchBlock = true + } + + s.sshContext.currentOption.Key = &SSHKey{ + LocationRange: location, + Value: ctx.GetText(), + } +} + +func (s *sshParserListener) EnterValue(ctx *parser.ValueContext) { + location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext) + location.ChangeBothLines(s.sshContext.line) + + s.sshContext.currentOption.OptionValue = &SSHValue{ + LocationRange: location, + Value: ctx.GetText(), + } +} + +func (s *sshParserListener) ExitValue(ctx *parser.ValueContext) { + if s.sshContext.isKeyAMatchBlock { + location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext) + location.ChangeBothLines(s.sshContext.line) + + rawEntry, _ := s.Config.Options.Get(location.Start.Line) + entry := rawEntry.(*SSHOption) + + // Overwrite the current match block + matchBlock := &SSHMatchBlock{ + LocationRange: location, + MatchEntry: entry, + } + s.Config.Options.Put( + location.Start.Line, + matchBlock, + ) + + s.sshContext.currentMatchBlock = matchBlock + s.sshContext.isKeyAMatchBlock = false + } + + s.sshContext.currentOption = nil +} + diff --git a/handlers/sshd_config/ast/parser.go b/handlers/sshd_config/ast/parser.go new file mode 100644 index 0000000..9143211 --- /dev/null +++ b/handlers/sshd_config/ast/parser.go @@ -0,0 +1,86 @@ +package ast + +import ( + "config-lsp/common" + "config-lsp/handlers/sshd_config/ast/parser" + "config-lsp/utils" + "regexp" + + "github.com/antlr4-go/antlr/v4" + "github.com/emirpasic/gods/maps/treemap" + + gods "github.com/emirpasic/gods/utils" +) + +func NewSSHConfig() *SSHConfig { + config := &SSHConfig{} + config.Clear() + + return config +} + +func (c *SSHConfig) Clear() { + c.Options = treemap.NewWith(gods.UInt32Comparator) + c.CommentLines = make(map[uint32]struct{}) +} + +var commentPattern = regexp.MustCompile(`^\s*#.*$`) +var emptyPattern = regexp.MustCompile(`^\s*$`) + +func (c *SSHConfig) Parse(input string) []common.LSPError { + errors := make([]common.LSPError, 0) + lines := utils.SplitIntoLines(input) + context := createSSHListenerContext() + + for rawLineNumber, line := range lines { + context.line = uint32(rawLineNumber) + + if commentPattern.MatchString(line) { + c.CommentLines[context.line] = struct{}{} + continue + } + + if emptyPattern.MatchString(line) { + continue + } + + errors = append( + errors, + c.parseStatement(context, line)..., + ) + } + + return errors +} + +func (c *SSHConfig) parseStatement( + context *sshListenerContext, + input string, +) []common.LSPError { + stream := antlr.NewInputStream(input) + + lexerErrorListener := createErrorListener(context.line) + lexer := parser.NewConfigLexer(&stream) + lexer.RemoveErrorListeners() + lexer.AddErrorListener(&lexerErrorListener) + + tokenStream := antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel) + + parserErrorListener := createErrorListener(context.line) + antlrParser := parser.NewConfigParser(tokenStream) + antlrParser.RemoveErrorListeners() + antlrParser.AddErrorListener(&parserErrorListener) + + listener := createListener(c, context) + antlr.ParseTreeWalkerDefault.Walk( + &listener, + antlrParser.LineStatement(), + ) + + errors := lexerErrorListener.Errors + errors = append(errors, parserErrorListener.Errors...) + errors = append(errors, listener.Errors...) + + return errors +} + diff --git a/handlers/sshd_config/ast/parser/Config.interp b/handlers/sshd_config/ast/parser/Config.interp new file mode 100644 index 0000000..74f62e9 --- /dev/null +++ b/handlers/sshd_config/ast/parser/Config.interp @@ -0,0 +1,26 @@ +token literal names: +null +'#' +null +null +null +null + +token symbolic names: +null +HASH +MATCH +WHITESPACE +STRING +NEWLINE + +rule names: +lineStatement +entry +key +value +leadingComment + + +atn: +[4, 1, 5, 55, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 1, 0, 1, 0, 3, 0, 13, 8, 0, 1, 0, 1, 0, 3, 0, 17, 8, 0, 3, 0, 19, 8, 0, 1, 0, 1, 0, 1, 1, 3, 1, 24, 8, 1, 1, 1, 3, 1, 27, 8, 1, 1, 1, 1, 1, 3, 1, 31, 8, 1, 1, 1, 3, 1, 34, 8, 1, 1, 1, 3, 1, 37, 8, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, 1, 4, 3, 4, 45, 8, 4, 1, 4, 1, 4, 3, 4, 49, 8, 4, 4, 4, 51, 8, 4, 11, 4, 12, 4, 52, 1, 4, 0, 0, 5, 0, 2, 4, 6, 8, 0, 0, 61, 0, 18, 1, 0, 0, 0, 2, 23, 1, 0, 0, 0, 4, 38, 1, 0, 0, 0, 6, 40, 1, 0, 0, 0, 8, 42, 1, 0, 0, 0, 10, 19, 3, 2, 1, 0, 11, 13, 5, 3, 0, 0, 12, 11, 1, 0, 0, 0, 12, 13, 1, 0, 0, 0, 13, 14, 1, 0, 0, 0, 14, 19, 3, 8, 4, 0, 15, 17, 5, 3, 0, 0, 16, 15, 1, 0, 0, 0, 16, 17, 1, 0, 0, 0, 17, 19, 1, 0, 0, 0, 18, 10, 1, 0, 0, 0, 18, 12, 1, 0, 0, 0, 18, 16, 1, 0, 0, 0, 19, 20, 1, 0, 0, 0, 20, 21, 5, 0, 0, 1, 21, 1, 1, 0, 0, 0, 22, 24, 5, 3, 0, 0, 23, 22, 1, 0, 0, 0, 23, 24, 1, 0, 0, 0, 24, 26, 1, 0, 0, 0, 25, 27, 3, 4, 2, 0, 26, 25, 1, 0, 0, 0, 26, 27, 1, 0, 0, 0, 27, 28, 1, 0, 0, 0, 28, 30, 5, 3, 0, 0, 29, 31, 3, 6, 3, 0, 30, 29, 1, 0, 0, 0, 30, 31, 1, 0, 0, 0, 31, 33, 1, 0, 0, 0, 32, 34, 5, 3, 0, 0, 33, 32, 1, 0, 0, 0, 33, 34, 1, 0, 0, 0, 34, 36, 1, 0, 0, 0, 35, 37, 3, 8, 4, 0, 36, 35, 1, 0, 0, 0, 36, 37, 1, 0, 0, 0, 37, 3, 1, 0, 0, 0, 38, 39, 5, 4, 0, 0, 39, 5, 1, 0, 0, 0, 40, 41, 5, 4, 0, 0, 41, 7, 1, 0, 0, 0, 42, 44, 5, 1, 0, 0, 43, 45, 5, 3, 0, 0, 44, 43, 1, 0, 0, 0, 44, 45, 1, 0, 0, 0, 45, 50, 1, 0, 0, 0, 46, 48, 5, 4, 0, 0, 47, 49, 5, 3, 0, 0, 48, 47, 1, 0, 0, 0, 48, 49, 1, 0, 0, 0, 49, 51, 1, 0, 0, 0, 50, 46, 1, 0, 0, 0, 51, 52, 1, 0, 0, 0, 52, 50, 1, 0, 0, 0, 52, 53, 1, 0, 0, 0, 53, 9, 1, 0, 0, 0, 11, 12, 16, 18, 23, 26, 30, 33, 36, 44, 48, 52] \ No newline at end of file diff --git a/handlers/sshd_config/ast/parser/Config.tokens b/handlers/sshd_config/ast/parser/Config.tokens new file mode 100644 index 0000000..30ff5e0 --- /dev/null +++ b/handlers/sshd_config/ast/parser/Config.tokens @@ -0,0 +1,6 @@ +HASH=1 +MATCH=2 +WHITESPACE=3 +STRING=4 +NEWLINE=5 +'#'=1 diff --git a/handlers/sshd_config/ast/parser/ConfigLexer.interp b/handlers/sshd_config/ast/parser/ConfigLexer.interp new file mode 100644 index 0000000..4ac663c --- /dev/null +++ b/handlers/sshd_config/ast/parser/ConfigLexer.interp @@ -0,0 +1,32 @@ +token literal names: +null +'#' +null +null +null +null + +token symbolic names: +null +HASH +MATCH +WHITESPACE +STRING +NEWLINE + +rule names: +HASH +MATCH +WHITESPACE +STRING +NEWLINE + +channel names: +DEFAULT_TOKEN_CHANNEL +HIDDEN + +mode names: +DEFAULT_MODE + +atn: +[4, 0, 5, 34, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 4, 2, 21, 8, 2, 11, 2, 12, 2, 22, 1, 3, 4, 3, 26, 8, 3, 11, 3, 12, 3, 27, 1, 4, 3, 4, 31, 8, 4, 1, 4, 1, 4, 0, 0, 5, 1, 1, 3, 2, 5, 3, 7, 4, 9, 5, 1, 0, 7, 2, 0, 77, 77, 109, 109, 2, 0, 65, 65, 97, 97, 2, 0, 84, 84, 116, 116, 2, 0, 67, 67, 99, 99, 2, 0, 72, 72, 104, 104, 2, 0, 9, 9, 32, 32, 4, 0, 9, 10, 13, 13, 32, 32, 35, 35, 36, 0, 1, 1, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, 5, 1, 0, 0, 0, 0, 7, 1, 0, 0, 0, 0, 9, 1, 0, 0, 0, 1, 11, 1, 0, 0, 0, 3, 13, 1, 0, 0, 0, 5, 20, 1, 0, 0, 0, 7, 25, 1, 0, 0, 0, 9, 30, 1, 0, 0, 0, 11, 12, 5, 35, 0, 0, 12, 2, 1, 0, 0, 0, 13, 14, 7, 0, 0, 0, 14, 15, 7, 1, 0, 0, 15, 16, 7, 2, 0, 0, 16, 17, 7, 3, 0, 0, 17, 18, 7, 4, 0, 0, 18, 4, 1, 0, 0, 0, 19, 21, 7, 5, 0, 0, 20, 19, 1, 0, 0, 0, 21, 22, 1, 0, 0, 0, 22, 20, 1, 0, 0, 0, 22, 23, 1, 0, 0, 0, 23, 6, 1, 0, 0, 0, 24, 26, 8, 6, 0, 0, 25, 24, 1, 0, 0, 0, 26, 27, 1, 0, 0, 0, 27, 25, 1, 0, 0, 0, 27, 28, 1, 0, 0, 0, 28, 8, 1, 0, 0, 0, 29, 31, 5, 13, 0, 0, 30, 29, 1, 0, 0, 0, 30, 31, 1, 0, 0, 0, 31, 32, 1, 0, 0, 0, 32, 33, 5, 10, 0, 0, 33, 10, 1, 0, 0, 0, 4, 0, 22, 27, 30, 0] \ No newline at end of file diff --git a/handlers/sshd_config/ast/parser/ConfigLexer.tokens b/handlers/sshd_config/ast/parser/ConfigLexer.tokens new file mode 100644 index 0000000..30ff5e0 --- /dev/null +++ b/handlers/sshd_config/ast/parser/ConfigLexer.tokens @@ -0,0 +1,6 @@ +HASH=1 +MATCH=2 +WHITESPACE=3 +STRING=4 +NEWLINE=5 +'#'=1 diff --git a/handlers/sshd_config/ast/parser/config_base_listener.go b/handlers/sshd_config/ast/parser/config_base_listener.go new file mode 100644 index 0000000..a161a6a --- /dev/null +++ b/handlers/sshd_config/ast/parser/config_base_listener.go @@ -0,0 +1,52 @@ +// Code generated from Config.g4 by ANTLR 4.13.0. DO NOT EDIT. + +package parser // Config + +import "github.com/antlr4-go/antlr/v4" + +// BaseConfigListener is a complete listener for a parse tree produced by ConfigParser. +type BaseConfigListener struct{} + +var _ ConfigListener = &BaseConfigListener{} + +// VisitTerminal is called when a terminal node is visited. +func (s *BaseConfigListener) VisitTerminal(node antlr.TerminalNode) {} + +// VisitErrorNode is called when an error node is visited. +func (s *BaseConfigListener) VisitErrorNode(node antlr.ErrorNode) {} + +// EnterEveryRule is called when any rule is entered. +func (s *BaseConfigListener) EnterEveryRule(ctx antlr.ParserRuleContext) {} + +// ExitEveryRule is called when any rule is exited. +func (s *BaseConfigListener) ExitEveryRule(ctx antlr.ParserRuleContext) {} + +// EnterLineStatement is called when production lineStatement is entered. +func (s *BaseConfigListener) EnterLineStatement(ctx *LineStatementContext) {} + +// ExitLineStatement is called when production lineStatement is exited. +func (s *BaseConfigListener) ExitLineStatement(ctx *LineStatementContext) {} + +// EnterEntry is called when production entry is entered. +func (s *BaseConfigListener) EnterEntry(ctx *EntryContext) {} + +// ExitEntry is called when production entry is exited. +func (s *BaseConfigListener) ExitEntry(ctx *EntryContext) {} + +// EnterKey is called when production key is entered. +func (s *BaseConfigListener) EnterKey(ctx *KeyContext) {} + +// ExitKey is called when production key is exited. +func (s *BaseConfigListener) ExitKey(ctx *KeyContext) {} + +// EnterValue is called when production value is entered. +func (s *BaseConfigListener) EnterValue(ctx *ValueContext) {} + +// ExitValue is called when production value is exited. +func (s *BaseConfigListener) ExitValue(ctx *ValueContext) {} + +// EnterLeadingComment is called when production leadingComment is entered. +func (s *BaseConfigListener) EnterLeadingComment(ctx *LeadingCommentContext) {} + +// ExitLeadingComment is called when production leadingComment is exited. +func (s *BaseConfigListener) ExitLeadingComment(ctx *LeadingCommentContext) {} diff --git a/handlers/sshd_config/ast/parser/config_lexer.go b/handlers/sshd_config/ast/parser/config_lexer.go new file mode 100644 index 0000000..cf0a348 --- /dev/null +++ b/handlers/sshd_config/ast/parser/config_lexer.go @@ -0,0 +1,118 @@ +// Code generated from Config.g4 by ANTLR 4.13.0. DO NOT EDIT. + +package parser + +import ( + "fmt" + "github.com/antlr4-go/antlr/v4" + "sync" + "unicode" +) + +// Suppress unused import error +var _ = fmt.Printf +var _ = sync.Once{} +var _ = unicode.IsLetter + +type ConfigLexer struct { + *antlr.BaseLexer + channelNames []string + modeNames []string + // TODO: EOF string +} + +var ConfigLexerLexerStaticData struct { + once sync.Once + serializedATN []int32 + ChannelNames []string + ModeNames []string + LiteralNames []string + SymbolicNames []string + RuleNames []string + PredictionContextCache *antlr.PredictionContextCache + atn *antlr.ATN + decisionToDFA []*antlr.DFA +} + +func configlexerLexerInit() { + staticData := &ConfigLexerLexerStaticData + staticData.ChannelNames = []string{ + "DEFAULT_TOKEN_CHANNEL", "HIDDEN", + } + staticData.ModeNames = []string{ + "DEFAULT_MODE", + } + staticData.LiteralNames = []string{ + "", "'#'", + } + staticData.SymbolicNames = []string{ + "", "HASH", "MATCH", "WHITESPACE", "STRING", "NEWLINE", + } + staticData.RuleNames = []string{ + "HASH", "MATCH", "WHITESPACE", "STRING", "NEWLINE", + } + staticData.PredictionContextCache = antlr.NewPredictionContextCache() + staticData.serializedATN = []int32{ + 4, 0, 5, 34, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, + 4, 7, 4, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 4, 2, 21, + 8, 2, 11, 2, 12, 2, 22, 1, 3, 4, 3, 26, 8, 3, 11, 3, 12, 3, 27, 1, 4, 3, + 4, 31, 8, 4, 1, 4, 1, 4, 0, 0, 5, 1, 1, 3, 2, 5, 3, 7, 4, 9, 5, 1, 0, 7, + 2, 0, 77, 77, 109, 109, 2, 0, 65, 65, 97, 97, 2, 0, 84, 84, 116, 116, 2, + 0, 67, 67, 99, 99, 2, 0, 72, 72, 104, 104, 2, 0, 9, 9, 32, 32, 4, 0, 9, + 10, 13, 13, 32, 32, 35, 35, 36, 0, 1, 1, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, + 5, 1, 0, 0, 0, 0, 7, 1, 0, 0, 0, 0, 9, 1, 0, 0, 0, 1, 11, 1, 0, 0, 0, 3, + 13, 1, 0, 0, 0, 5, 20, 1, 0, 0, 0, 7, 25, 1, 0, 0, 0, 9, 30, 1, 0, 0, 0, + 11, 12, 5, 35, 0, 0, 12, 2, 1, 0, 0, 0, 13, 14, 7, 0, 0, 0, 14, 15, 7, + 1, 0, 0, 15, 16, 7, 2, 0, 0, 16, 17, 7, 3, 0, 0, 17, 18, 7, 4, 0, 0, 18, + 4, 1, 0, 0, 0, 19, 21, 7, 5, 0, 0, 20, 19, 1, 0, 0, 0, 21, 22, 1, 0, 0, + 0, 22, 20, 1, 0, 0, 0, 22, 23, 1, 0, 0, 0, 23, 6, 1, 0, 0, 0, 24, 26, 8, + 6, 0, 0, 25, 24, 1, 0, 0, 0, 26, 27, 1, 0, 0, 0, 27, 25, 1, 0, 0, 0, 27, + 28, 1, 0, 0, 0, 28, 8, 1, 0, 0, 0, 29, 31, 5, 13, 0, 0, 30, 29, 1, 0, 0, + 0, 30, 31, 1, 0, 0, 0, 31, 32, 1, 0, 0, 0, 32, 33, 5, 10, 0, 0, 33, 10, + 1, 0, 0, 0, 4, 0, 22, 27, 30, 0, + } + deserializer := antlr.NewATNDeserializer(nil) + staticData.atn = deserializer.Deserialize(staticData.serializedATN) + atn := staticData.atn + staticData.decisionToDFA = make([]*antlr.DFA, len(atn.DecisionToState)) + decisionToDFA := staticData.decisionToDFA + for index, state := range atn.DecisionToState { + decisionToDFA[index] = antlr.NewDFA(state, index) + } +} + +// ConfigLexerInit initializes any static state used to implement ConfigLexer. By default the +// static state used to implement the lexer is lazily initialized during the first call to +// NewConfigLexer(). You can call this function if you wish to initialize the static state ahead +// of time. +func ConfigLexerInit() { + staticData := &ConfigLexerLexerStaticData + staticData.once.Do(configlexerLexerInit) +} + +// NewConfigLexer produces a new lexer instance for the optional input antlr.CharStream. +func NewConfigLexer(input antlr.CharStream) *ConfigLexer { + ConfigLexerInit() + l := new(ConfigLexer) + l.BaseLexer = antlr.NewBaseLexer(input) + staticData := &ConfigLexerLexerStaticData + l.Interpreter = antlr.NewLexerATNSimulator(l, staticData.atn, staticData.decisionToDFA, staticData.PredictionContextCache) + l.channelNames = staticData.ChannelNames + l.modeNames = staticData.ModeNames + l.RuleNames = staticData.RuleNames + l.LiteralNames = staticData.LiteralNames + l.SymbolicNames = staticData.SymbolicNames + l.GrammarFileName = "Config.g4" + // TODO: l.EOF = antlr.TokenEOF + + return l +} + +// ConfigLexer tokens. +const ( + ConfigLexerHASH = 1 + ConfigLexerMATCH = 2 + ConfigLexerWHITESPACE = 3 + ConfigLexerSTRING = 4 + ConfigLexerNEWLINE = 5 +) diff --git a/handlers/sshd_config/ast/parser/config_listener.go b/handlers/sshd_config/ast/parser/config_listener.go new file mode 100644 index 0000000..00c5695 --- /dev/null +++ b/handlers/sshd_config/ast/parser/config_listener.go @@ -0,0 +1,40 @@ +// Code generated from Config.g4 by ANTLR 4.13.0. DO NOT EDIT. + +package parser // Config + +import "github.com/antlr4-go/antlr/v4" + +// ConfigListener is a complete listener for a parse tree produced by ConfigParser. +type ConfigListener interface { + antlr.ParseTreeListener + + // EnterLineStatement is called when entering the lineStatement production. + EnterLineStatement(c *LineStatementContext) + + // EnterEntry is called when entering the entry production. + EnterEntry(c *EntryContext) + + // EnterKey is called when entering the key production. + EnterKey(c *KeyContext) + + // EnterValue is called when entering the value production. + EnterValue(c *ValueContext) + + // EnterLeadingComment is called when entering the leadingComment production. + EnterLeadingComment(c *LeadingCommentContext) + + // ExitLineStatement is called when exiting the lineStatement production. + ExitLineStatement(c *LineStatementContext) + + // ExitEntry is called when exiting the entry production. + ExitEntry(c *EntryContext) + + // ExitKey is called when exiting the key production. + ExitKey(c *KeyContext) + + // ExitValue is called when exiting the value production. + ExitValue(c *ValueContext) + + // ExitLeadingComment is called when exiting the leadingComment production. + ExitLeadingComment(c *LeadingCommentContext) +} diff --git a/handlers/sshd_config/ast/parser/config_parser.go b/handlers/sshd_config/ast/parser/config_parser.go new file mode 100644 index 0000000..a52548d --- /dev/null +++ b/handlers/sshd_config/ast/parser/config_parser.go @@ -0,0 +1,919 @@ +// Code generated from Config.g4 by ANTLR 4.13.0. DO NOT EDIT. + +package parser // Config + +import ( + "fmt" + "strconv" + "sync" + + "github.com/antlr4-go/antlr/v4" +) + +// Suppress unused import errors +var _ = fmt.Printf +var _ = strconv.Itoa +var _ = sync.Once{} + +type ConfigParser struct { + *antlr.BaseParser +} + +var ConfigParserStaticData struct { + once sync.Once + serializedATN []int32 + LiteralNames []string + SymbolicNames []string + RuleNames []string + PredictionContextCache *antlr.PredictionContextCache + atn *antlr.ATN + decisionToDFA []*antlr.DFA +} + +func configParserInit() { + staticData := &ConfigParserStaticData + staticData.LiteralNames = []string{ + "", "'#'", + } + staticData.SymbolicNames = []string{ + "", "HASH", "MATCH", "WHITESPACE", "STRING", "NEWLINE", + } + staticData.RuleNames = []string{ + "lineStatement", "entry", "key", "value", "leadingComment", + } + staticData.PredictionContextCache = antlr.NewPredictionContextCache() + staticData.serializedATN = []int32{ + 4, 1, 5, 55, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, + 1, 0, 1, 0, 3, 0, 13, 8, 0, 1, 0, 1, 0, 3, 0, 17, 8, 0, 3, 0, 19, 8, 0, + 1, 0, 1, 0, 1, 1, 3, 1, 24, 8, 1, 1, 1, 3, 1, 27, 8, 1, 1, 1, 1, 1, 3, + 1, 31, 8, 1, 1, 1, 3, 1, 34, 8, 1, 1, 1, 3, 1, 37, 8, 1, 1, 2, 1, 2, 1, + 3, 1, 3, 1, 4, 1, 4, 3, 4, 45, 8, 4, 1, 4, 1, 4, 3, 4, 49, 8, 4, 4, 4, + 51, 8, 4, 11, 4, 12, 4, 52, 1, 4, 0, 0, 5, 0, 2, 4, 6, 8, 0, 0, 61, 0, + 18, 1, 0, 0, 0, 2, 23, 1, 0, 0, 0, 4, 38, 1, 0, 0, 0, 6, 40, 1, 0, 0, 0, + 8, 42, 1, 0, 0, 0, 10, 19, 3, 2, 1, 0, 11, 13, 5, 3, 0, 0, 12, 11, 1, 0, + 0, 0, 12, 13, 1, 0, 0, 0, 13, 14, 1, 0, 0, 0, 14, 19, 3, 8, 4, 0, 15, 17, + 5, 3, 0, 0, 16, 15, 1, 0, 0, 0, 16, 17, 1, 0, 0, 0, 17, 19, 1, 0, 0, 0, + 18, 10, 1, 0, 0, 0, 18, 12, 1, 0, 0, 0, 18, 16, 1, 0, 0, 0, 19, 20, 1, + 0, 0, 0, 20, 21, 5, 0, 0, 1, 21, 1, 1, 0, 0, 0, 22, 24, 5, 3, 0, 0, 23, + 22, 1, 0, 0, 0, 23, 24, 1, 0, 0, 0, 24, 26, 1, 0, 0, 0, 25, 27, 3, 4, 2, + 0, 26, 25, 1, 0, 0, 0, 26, 27, 1, 0, 0, 0, 27, 28, 1, 0, 0, 0, 28, 30, + 5, 3, 0, 0, 29, 31, 3, 6, 3, 0, 30, 29, 1, 0, 0, 0, 30, 31, 1, 0, 0, 0, + 31, 33, 1, 0, 0, 0, 32, 34, 5, 3, 0, 0, 33, 32, 1, 0, 0, 0, 33, 34, 1, + 0, 0, 0, 34, 36, 1, 0, 0, 0, 35, 37, 3, 8, 4, 0, 36, 35, 1, 0, 0, 0, 36, + 37, 1, 0, 0, 0, 37, 3, 1, 0, 0, 0, 38, 39, 5, 4, 0, 0, 39, 5, 1, 0, 0, + 0, 40, 41, 5, 4, 0, 0, 41, 7, 1, 0, 0, 0, 42, 44, 5, 1, 0, 0, 43, 45, 5, + 3, 0, 0, 44, 43, 1, 0, 0, 0, 44, 45, 1, 0, 0, 0, 45, 50, 1, 0, 0, 0, 46, + 48, 5, 4, 0, 0, 47, 49, 5, 3, 0, 0, 48, 47, 1, 0, 0, 0, 48, 49, 1, 0, 0, + 0, 49, 51, 1, 0, 0, 0, 50, 46, 1, 0, 0, 0, 51, 52, 1, 0, 0, 0, 52, 50, + 1, 0, 0, 0, 52, 53, 1, 0, 0, 0, 53, 9, 1, 0, 0, 0, 11, 12, 16, 18, 23, + 26, 30, 33, 36, 44, 48, 52, + } + deserializer := antlr.NewATNDeserializer(nil) + staticData.atn = deserializer.Deserialize(staticData.serializedATN) + atn := staticData.atn + staticData.decisionToDFA = make([]*antlr.DFA, len(atn.DecisionToState)) + decisionToDFA := staticData.decisionToDFA + for index, state := range atn.DecisionToState { + decisionToDFA[index] = antlr.NewDFA(state, index) + } +} + +// ConfigParserInit initializes any static state used to implement ConfigParser. By default the +// static state used to implement the parser is lazily initialized during the first call to +// NewConfigParser(). You can call this function if you wish to initialize the static state ahead +// of time. +func ConfigParserInit() { + staticData := &ConfigParserStaticData + staticData.once.Do(configParserInit) +} + +// NewConfigParser produces a new parser instance for the optional input antlr.TokenStream. +func NewConfigParser(input antlr.TokenStream) *ConfigParser { + ConfigParserInit() + this := new(ConfigParser) + this.BaseParser = antlr.NewBaseParser(input) + staticData := &ConfigParserStaticData + this.Interpreter = antlr.NewParserATNSimulator(this, staticData.atn, staticData.decisionToDFA, staticData.PredictionContextCache) + this.RuleNames = staticData.RuleNames + this.LiteralNames = staticData.LiteralNames + this.SymbolicNames = staticData.SymbolicNames + this.GrammarFileName = "Config.g4" + + return this +} + +// ConfigParser tokens. +const ( + ConfigParserEOF = antlr.TokenEOF + ConfigParserHASH = 1 + ConfigParserMATCH = 2 + ConfigParserWHITESPACE = 3 + ConfigParserSTRING = 4 + ConfigParserNEWLINE = 5 +) + +// ConfigParser rules. +const ( + ConfigParserRULE_lineStatement = 0 + ConfigParserRULE_entry = 1 + ConfigParserRULE_key = 2 + ConfigParserRULE_value = 3 + ConfigParserRULE_leadingComment = 4 +) + +// ILineStatementContext is an interface to support dynamic dispatch. +type ILineStatementContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + + // Getter signatures + EOF() antlr.TerminalNode + Entry() IEntryContext + LeadingComment() ILeadingCommentContext + WHITESPACE() antlr.TerminalNode + + // IsLineStatementContext differentiates from other interfaces. + IsLineStatementContext() +} + +type LineStatementContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptyLineStatementContext() *LineStatementContext { + var p = new(LineStatementContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_lineStatement + return p +} + +func InitEmptyLineStatementContext(p *LineStatementContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_lineStatement +} + +func (*LineStatementContext) IsLineStatementContext() {} + +func NewLineStatementContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *LineStatementContext { + var p = new(LineStatementContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = ConfigParserRULE_lineStatement + + return p +} + +func (s *LineStatementContext) GetParser() antlr.Parser { return s.parser } + +func (s *LineStatementContext) EOF() antlr.TerminalNode { + return s.GetToken(ConfigParserEOF, 0) +} + +func (s *LineStatementContext) Entry() IEntryContext { + var t antlr.RuleContext + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(IEntryContext); ok { + t = ctx.(antlr.RuleContext) + break + } + } + + if t == nil { + return nil + } + + return t.(IEntryContext) +} + +func (s *LineStatementContext) LeadingComment() ILeadingCommentContext { + var t antlr.RuleContext + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(ILeadingCommentContext); ok { + t = ctx.(antlr.RuleContext) + break + } + } + + if t == nil { + return nil + } + + return t.(ILeadingCommentContext) +} + +func (s *LineStatementContext) WHITESPACE() antlr.TerminalNode { + return s.GetToken(ConfigParserWHITESPACE, 0) +} + +func (s *LineStatementContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *LineStatementContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +func (s *LineStatementContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.EnterLineStatement(s) + } +} + +func (s *LineStatementContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.ExitLineStatement(s) + } +} + +func (p *ConfigParser) LineStatement() (localctx ILineStatementContext) { + localctx = NewLineStatementContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 0, ConfigParserRULE_lineStatement) + var _la int + + p.EnterOuterAlt(localctx, 1) + p.SetState(18) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + + switch p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 2, p.GetParserRuleContext()) { + case 1: + { + p.SetState(10) + p.Entry() + } + + case 2: + p.SetState(12) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + if _la == ConfigParserWHITESPACE { + { + p.SetState(11) + p.Match(ConfigParserWHITESPACE) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + + } + { + p.SetState(14) + p.LeadingComment() + } + + case 3: + p.SetState(16) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + if _la == ConfigParserWHITESPACE { + { + p.SetState(15) + p.Match(ConfigParserWHITESPACE) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + + } + + case antlr.ATNInvalidAltNumber: + goto errorExit + } + { + p.SetState(20) + p.Match(ConfigParserEOF) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} + +// IEntryContext is an interface to support dynamic dispatch. +type IEntryContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + + // Getter signatures + AllWHITESPACE() []antlr.TerminalNode + WHITESPACE(i int) antlr.TerminalNode + Key() IKeyContext + Value() IValueContext + LeadingComment() ILeadingCommentContext + + // IsEntryContext differentiates from other interfaces. + IsEntryContext() +} + +type EntryContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptyEntryContext() *EntryContext { + var p = new(EntryContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_entry + return p +} + +func InitEmptyEntryContext(p *EntryContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_entry +} + +func (*EntryContext) IsEntryContext() {} + +func NewEntryContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *EntryContext { + var p = new(EntryContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = ConfigParserRULE_entry + + return p +} + +func (s *EntryContext) GetParser() antlr.Parser { return s.parser } + +func (s *EntryContext) AllWHITESPACE() []antlr.TerminalNode { + return s.GetTokens(ConfigParserWHITESPACE) +} + +func (s *EntryContext) WHITESPACE(i int) antlr.TerminalNode { + return s.GetToken(ConfigParserWHITESPACE, i) +} + +func (s *EntryContext) Key() IKeyContext { + var t antlr.RuleContext + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(IKeyContext); ok { + t = ctx.(antlr.RuleContext) + break + } + } + + if t == nil { + return nil + } + + return t.(IKeyContext) +} + +func (s *EntryContext) Value() IValueContext { + var t antlr.RuleContext + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(IValueContext); ok { + t = ctx.(antlr.RuleContext) + break + } + } + + if t == nil { + return nil + } + + return t.(IValueContext) +} + +func (s *EntryContext) LeadingComment() ILeadingCommentContext { + var t antlr.RuleContext + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(ILeadingCommentContext); ok { + t = ctx.(antlr.RuleContext) + break + } + } + + if t == nil { + return nil + } + + return t.(ILeadingCommentContext) +} + +func (s *EntryContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *EntryContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +func (s *EntryContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.EnterEntry(s) + } +} + +func (s *EntryContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.ExitEntry(s) + } +} + +func (p *ConfigParser) Entry() (localctx IEntryContext) { + localctx = NewEntryContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 2, ConfigParserRULE_entry) + var _la int + + p.EnterOuterAlt(localctx, 1) + p.SetState(23) + p.GetErrorHandler().Sync(p) + + if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 3, p.GetParserRuleContext()) == 1 { + { + p.SetState(22) + p.Match(ConfigParserWHITESPACE) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + + } else if p.HasError() { // JIM + goto errorExit + } + p.SetState(26) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + if _la == ConfigParserSTRING { + { + p.SetState(25) + p.Key() + } + + } + { + p.SetState(28) + p.Match(ConfigParserWHITESPACE) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + p.SetState(30) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + if _la == ConfigParserSTRING { + { + p.SetState(29) + p.Value() + } + + } + p.SetState(33) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + if _la == ConfigParserWHITESPACE { + { + p.SetState(32) + p.Match(ConfigParserWHITESPACE) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + + } + p.SetState(36) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + if _la == ConfigParserHASH { + { + p.SetState(35) + p.LeadingComment() + } + + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} + +// IKeyContext is an interface to support dynamic dispatch. +type IKeyContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + + // Getter signatures + STRING() antlr.TerminalNode + + // IsKeyContext differentiates from other interfaces. + IsKeyContext() +} + +type KeyContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptyKeyContext() *KeyContext { + var p = new(KeyContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_key + return p +} + +func InitEmptyKeyContext(p *KeyContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_key +} + +func (*KeyContext) IsKeyContext() {} + +func NewKeyContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *KeyContext { + var p = new(KeyContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = ConfigParserRULE_key + + return p +} + +func (s *KeyContext) GetParser() antlr.Parser { return s.parser } + +func (s *KeyContext) STRING() antlr.TerminalNode { + return s.GetToken(ConfigParserSTRING, 0) +} + +func (s *KeyContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *KeyContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +func (s *KeyContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.EnterKey(s) + } +} + +func (s *KeyContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.ExitKey(s) + } +} + +func (p *ConfigParser) Key() (localctx IKeyContext) { + localctx = NewKeyContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 4, ConfigParserRULE_key) + p.EnterOuterAlt(localctx, 1) + { + p.SetState(38) + p.Match(ConfigParserSTRING) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} + +// IValueContext is an interface to support dynamic dispatch. +type IValueContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + + // Getter signatures + STRING() antlr.TerminalNode + + // IsValueContext differentiates from other interfaces. + IsValueContext() +} + +type ValueContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptyValueContext() *ValueContext { + var p = new(ValueContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_value + return p +} + +func InitEmptyValueContext(p *ValueContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_value +} + +func (*ValueContext) IsValueContext() {} + +func NewValueContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *ValueContext { + var p = new(ValueContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = ConfigParserRULE_value + + return p +} + +func (s *ValueContext) GetParser() antlr.Parser { return s.parser } + +func (s *ValueContext) STRING() antlr.TerminalNode { + return s.GetToken(ConfigParserSTRING, 0) +} + +func (s *ValueContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *ValueContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +func (s *ValueContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.EnterValue(s) + } +} + +func (s *ValueContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.ExitValue(s) + } +} + +func (p *ConfigParser) Value() (localctx IValueContext) { + localctx = NewValueContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 6, ConfigParserRULE_value) + p.EnterOuterAlt(localctx, 1) + { + p.SetState(40) + p.Match(ConfigParserSTRING) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} + +// ILeadingCommentContext is an interface to support dynamic dispatch. +type ILeadingCommentContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + + // Getter signatures + HASH() antlr.TerminalNode + AllWHITESPACE() []antlr.TerminalNode + WHITESPACE(i int) antlr.TerminalNode + AllSTRING() []antlr.TerminalNode + STRING(i int) antlr.TerminalNode + + // IsLeadingCommentContext differentiates from other interfaces. + IsLeadingCommentContext() +} + +type LeadingCommentContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptyLeadingCommentContext() *LeadingCommentContext { + var p = new(LeadingCommentContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_leadingComment + return p +} + +func InitEmptyLeadingCommentContext(p *LeadingCommentContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_leadingComment +} + +func (*LeadingCommentContext) IsLeadingCommentContext() {} + +func NewLeadingCommentContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *LeadingCommentContext { + var p = new(LeadingCommentContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = ConfigParserRULE_leadingComment + + return p +} + +func (s *LeadingCommentContext) GetParser() antlr.Parser { return s.parser } + +func (s *LeadingCommentContext) HASH() antlr.TerminalNode { + return s.GetToken(ConfigParserHASH, 0) +} + +func (s *LeadingCommentContext) AllWHITESPACE() []antlr.TerminalNode { + return s.GetTokens(ConfigParserWHITESPACE) +} + +func (s *LeadingCommentContext) WHITESPACE(i int) antlr.TerminalNode { + return s.GetToken(ConfigParserWHITESPACE, i) +} + +func (s *LeadingCommentContext) AllSTRING() []antlr.TerminalNode { + return s.GetTokens(ConfigParserSTRING) +} + +func (s *LeadingCommentContext) STRING(i int) antlr.TerminalNode { + return s.GetToken(ConfigParserSTRING, i) +} + +func (s *LeadingCommentContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *LeadingCommentContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +func (s *LeadingCommentContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.EnterLeadingComment(s) + } +} + +func (s *LeadingCommentContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.ExitLeadingComment(s) + } +} + +func (p *ConfigParser) LeadingComment() (localctx ILeadingCommentContext) { + localctx = NewLeadingCommentContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 8, ConfigParserRULE_leadingComment) + var _la int + + p.EnterOuterAlt(localctx, 1) + { + p.SetState(42) + p.Match(ConfigParserHASH) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + p.SetState(44) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + if _la == ConfigParserWHITESPACE { + { + p.SetState(43) + p.Match(ConfigParserWHITESPACE) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + + } + p.SetState(50) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + for ok := true; ok; ok = _la == ConfigParserSTRING { + { + p.SetState(46) + p.Match(ConfigParserSTRING) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + p.SetState(48) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + if _la == ConfigParserWHITESPACE { + { + p.SetState(47) + p.Match(ConfigParserWHITESPACE) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + + } + + p.SetState(52) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} diff --git a/handlers/sshd_config/ast/sshd_config.go b/handlers/sshd_config/ast/sshd_config.go new file mode 100644 index 0000000..6364bb9 --- /dev/null +++ b/handlers/sshd_config/ast/sshd_config.go @@ -0,0 +1,59 @@ +package ast + +import ( + "config-lsp/common" + + "github.com/emirpasic/gods/maps/treemap" +) + +type SSHKey struct { + common.LocationRange + Value string +} + +type SSHValue struct { + common.LocationRange + Value string +} + +type SSHEntryType uint + +const ( + SSHEntryTypeOption SSHEntryType = iota + SSHEntryTypeMatchBlock +) + +type SSHEntry interface { + GetType() SSHEntryType +} + +type SSHOption struct { + common.LocationRange + Value string + + Key *SSHKey + OptionValue *SSHValue +} + +func (o SSHOption) GetType() SSHEntryType { + return SSHEntryTypeOption +} + +type SSHMatchBlock struct { + common.LocationRange + MatchEntry *SSHOption + + // [uint32]*SSHOption -> line number -> *SSHOption + Options *treemap.Map +} + +func (m SSHMatchBlock) GetType() SSHEntryType { + return SSHEntryTypeMatchBlock +} + +type SSHConfig struct { + // [uint32]SSHOption -> line number -> *SSHEntry + Options *treemap.Map + // [uint32]{} -> line number -> {} + CommentLines map[uint32]struct{} +} From 82a08d64590affed9120a695c2cc2cc9fb795d2d Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Tue, 10 Sep 2024 21:16:47 +0200 Subject: [PATCH 007/133] test(sshd_config): Add tests --- handlers/sshd_config/ast/listener.go | 11 +++-- handlers/sshd_config/ast/parser.go | 3 +- handlers/sshd_config/ast/parser_test.go | 60 +++++++++++++++++++++++++ 3 files changed, 66 insertions(+), 8 deletions(-) create mode 100644 handlers/sshd_config/ast/parser_test.go diff --git a/handlers/sshd_config/ast/listener.go b/handlers/sshd_config/ast/listener.go index c574f96..d7d51db 100644 --- a/handlers/sshd_config/ast/listener.go +++ b/handlers/sshd_config/ast/listener.go @@ -11,15 +11,15 @@ func createListener( context *sshListenerContext, ) sshParserListener { return sshParserListener{ - Config: config, - Errors: make([]common.LSPError, 0), + Config: config, + Errors: make([]common.LSPError, 0), sshContext: context, } } type sshListenerContext struct { line uint32 - currentOption *SSHOption + currentOption *SSHOption currentMatchBlock *SSHMatchBlock isKeyAMatchBlock bool } @@ -94,14 +94,14 @@ func (s *sshParserListener) ExitValue(ctx *parser.ValueContext) { if s.sshContext.isKeyAMatchBlock { location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext) location.ChangeBothLines(s.sshContext.line) - + rawEntry, _ := s.Config.Options.Get(location.Start.Line) entry := rawEntry.(*SSHOption) // Overwrite the current match block matchBlock := &SSHMatchBlock{ LocationRange: location, - MatchEntry: entry, + MatchEntry: entry, } s.Config.Options.Put( location.Start.Line, @@ -114,4 +114,3 @@ func (s *sshParserListener) ExitValue(ctx *parser.ValueContext) { s.sshContext.currentOption = nil } - diff --git a/handlers/sshd_config/ast/parser.go b/handlers/sshd_config/ast/parser.go index 9143211..fc510ee 100644 --- a/handlers/sshd_config/ast/parser.go +++ b/handlers/sshd_config/ast/parser.go @@ -60,7 +60,7 @@ func (c *SSHConfig) parseStatement( stream := antlr.NewInputStream(input) lexerErrorListener := createErrorListener(context.line) - lexer := parser.NewConfigLexer(&stream) + lexer := parser.NewConfigLexer(stream) lexer.RemoveErrorListeners() lexer.AddErrorListener(&lexerErrorListener) @@ -83,4 +83,3 @@ func (c *SSHConfig) parseStatement( return errors } - diff --git a/handlers/sshd_config/ast/parser_test.go b/handlers/sshd_config/ast/parser_test.go new file mode 100644 index 0000000..3b3626e --- /dev/null +++ b/handlers/sshd_config/ast/parser_test.go @@ -0,0 +1,60 @@ +package ast + +import ( + "config-lsp/utils" + "testing" +) + +func TestSimpleParserExample( + t *testing.T, +) { + input := utils.Dedent(` +PermitRootLogin no +PasswordAuthentication yes +`) + p := NewSSHConfig() + errors := p.Parse(input) + + if len(errors) != 0 { + t.Fatalf("Expected no errors, got %v", errors) + } + + if !(p.Options.Size() == 2 && + len(utils.KeysOfMap(p.CommentLines)) == 0) { + t.Errorf("Expected 2 options and no comment lines, but got: %v, %v", p.Options, p.CommentLines) + } + + rawFirstEntry, _ := p.Options.Get(uint32(0)) + firstEntry := rawFirstEntry.(*SSHOption) + + if !(firstEntry.Value == "PermitRootLogin no" && + firstEntry.LocationRange.Start.Line == 0 && + firstEntry.LocationRange.End.Line == 0 && + firstEntry.LocationRange.Start.Character == 0 && + firstEntry.LocationRange.End.Character == 18 && + firstEntry.Key.Value == "PermitRootLogin" && + firstEntry.Key.LocationRange.Start.Character == 0 && + firstEntry.Key.LocationRange.End.Character == 15 && + firstEntry.OptionValue.Value == "no" && + firstEntry.OptionValue.LocationRange.Start.Character == 16 && + firstEntry.OptionValue.LocationRange.End.Character == 18) { + t.Errorf("Expected first entry to be PermitRootLogin no, but got: %v", firstEntry) + } + + rawSecondEntry, _ := p.Options.Get(uint32(1)) + secondEntry := rawSecondEntry.(*SSHOption) + + if !(secondEntry.Value == "PasswordAuthentication yes" && + secondEntry.LocationRange.Start.Line == 1 && + secondEntry.LocationRange.End.Line == 1 && + secondEntry.LocationRange.Start.Character == 0 && + secondEntry.LocationRange.End.Character == 26 && + secondEntry.Key.Value == "PasswordAuthentication" && + secondEntry.Key.LocationRange.Start.Character == 0 && + secondEntry.Key.LocationRange.End.Character == 22 && + secondEntry.OptionValue.Value == "yes" && + secondEntry.OptionValue.LocationRange.Start.Character == 23 && + secondEntry.OptionValue.LocationRange.End.Character == 26) { + t.Errorf("Expected second entry to be PasswordAuthentication yes, but got: %v", secondEntry) + } +} From 82797de8e5fdd4c5b3b914a51c812ea4589fcc5b Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Tue, 10 Sep 2024 21:25:04 +0200 Subject: [PATCH 008/133] chore: Use both inclusive ranges for location ranges --- common/location.go | 4 ++-- handlers/aliases/ast/parser_test.go | 4 ++-- handlers/hosts/analyzer/handler_test.go | 4 ++-- handlers/hosts/lsp/text-document-hover.go | 2 +- handlers/sshd_config/ast/parser_test.go | 12 ++++++------ 5 files changed, 13 insertions(+), 13 deletions(-) diff --git a/common/location.go b/common/location.go index 5db293f..db050e7 100644 --- a/common/location.go +++ b/common/location.go @@ -57,7 +57,7 @@ func (l LocationRange) ToLSPRange() protocol.Range { }, End: protocol.Position{ Line: l.End.Line, - Character: l.End.Character, + Character: l.End.Character + 1, }, } } @@ -115,7 +115,7 @@ func CharacterRangeFromCtx( }, End: Location{ Line: line, - Character: end + 1, + Character: end, }, } } diff --git a/handlers/aliases/ast/parser_test.go b/handlers/aliases/ast/parser_test.go index 9ad9165..17351ea 100644 --- a/handlers/aliases/ast/parser_test.go +++ b/handlers/aliases/ast/parser_test.go @@ -105,11 +105,11 @@ luke: :include:/etc/other_aliases t.Fatalf("Expected path to be '/etc/other_aliases', got %v", includeValue.Path.Path) } - if !(includeValue.Location.Start.Character == 6 && includeValue.Location.End.Character == 33) { + if !(includeValue.Location.Start.Character == 6 && includeValue.Location.End.Character == 32) { t.Fatalf("Expected location to be 6-33, got %v-%v", includeValue.Location.Start.Character, includeValue.Location.End.Character) } - if !(includeValue.Path.Location.Start.Character == 15 && includeValue.Path.Location.End.Character == 33) { + if !(includeValue.Path.Location.Start.Character == 15 && includeValue.Path.Location.End.Character == 32) { t.Fatalf("Expected path location to be 15-33, got %v-%v", includeValue.Path.Location.Start.Character, includeValue.Path.Location.End.Character) } } diff --git a/handlers/hosts/analyzer/handler_test.go b/handlers/hosts/analyzer/handler_test.go index b7182a2..4705c95 100644 --- a/handlers/hosts/analyzer/handler_test.go +++ b/handlers/hosts/analyzer/handler_test.go @@ -51,7 +51,7 @@ func TestValidSimpleExampleWorks( t.Errorf("Expected start to be 0, but got %v", entry.Location.Start) } - if !(entry.Location.End.Character == 17) { + if !(entry.Location.End.Character == 16) { t.Errorf("Expected end to be 17, but got %v", entry.Location.End.Character) } @@ -63,7 +63,7 @@ func TestValidSimpleExampleWorks( t.Errorf("Expected IP address start to be 0, but got %v", entry.IPAddress.Location.Start.Character) } - if !(entry.IPAddress.Location.End.Character == 7) { + if !(entry.IPAddress.Location.End.Character == 6) { t.Errorf("Expected IP address end to be 7, but got %v", entry.IPAddress.Location.End.Character) } diff --git a/handlers/hosts/lsp/text-document-hover.go b/handlers/hosts/lsp/text-document-hover.go index 086daa5..53ceb61 100644 --- a/handlers/hosts/lsp/text-document-hover.go +++ b/handlers/hosts/lsp/text-document-hover.go @@ -49,7 +49,7 @@ func TextDocumentHover( hostname = entry.Hostname case handlers.HoverTargetAlias: for _, alias := range entry.Aliases { - if alias.Location.Start.Character <= character && character <= alias.Location.End.Character { + if character >= alias.Location.Start.Character && character <= alias.Location.End.Character { hostname = alias break } diff --git a/handlers/sshd_config/ast/parser_test.go b/handlers/sshd_config/ast/parser_test.go index 3b3626e..53a0458 100644 --- a/handlers/sshd_config/ast/parser_test.go +++ b/handlers/sshd_config/ast/parser_test.go @@ -31,13 +31,13 @@ PasswordAuthentication yes firstEntry.LocationRange.Start.Line == 0 && firstEntry.LocationRange.End.Line == 0 && firstEntry.LocationRange.Start.Character == 0 && - firstEntry.LocationRange.End.Character == 18 && + firstEntry.LocationRange.End.Character == 17 && firstEntry.Key.Value == "PermitRootLogin" && firstEntry.Key.LocationRange.Start.Character == 0 && - firstEntry.Key.LocationRange.End.Character == 15 && + firstEntry.Key.LocationRange.End.Character == 14 && firstEntry.OptionValue.Value == "no" && firstEntry.OptionValue.LocationRange.Start.Character == 16 && - firstEntry.OptionValue.LocationRange.End.Character == 18) { + firstEntry.OptionValue.LocationRange.End.Character == 17) { t.Errorf("Expected first entry to be PermitRootLogin no, but got: %v", firstEntry) } @@ -48,13 +48,13 @@ PasswordAuthentication yes secondEntry.LocationRange.Start.Line == 1 && secondEntry.LocationRange.End.Line == 1 && secondEntry.LocationRange.Start.Character == 0 && - secondEntry.LocationRange.End.Character == 26 && + secondEntry.LocationRange.End.Character == 25 && secondEntry.Key.Value == "PasswordAuthentication" && secondEntry.Key.LocationRange.Start.Character == 0 && - secondEntry.Key.LocationRange.End.Character == 22 && + secondEntry.Key.LocationRange.End.Character == 21 && secondEntry.OptionValue.Value == "yes" && secondEntry.OptionValue.LocationRange.Start.Character == 23 && - secondEntry.OptionValue.LocationRange.End.Character == 26) { + secondEntry.OptionValue.LocationRange.End.Character == 25) { t.Errorf("Expected second entry to be PasswordAuthentication yes, but got: %v", secondEntry) } } From 93203a7179c598cf5967a106f1034ec8a7c49a5a Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Tue, 10 Sep 2024 22:13:36 +0200 Subject: [PATCH 009/133] fix(sshd_config): Improve parser --- handlers/sshd_config/Config.g4 | 7 +- handlers/sshd_config/ast/listener.go | 43 ++- handlers/sshd_config/ast/parser.go | 6 +- handlers/sshd_config/ast/parser/Config.interp | 4 +- handlers/sshd_config/ast/parser/Config.tokens | 7 +- .../sshd_config/ast/parser/ConfigLexer.interp | 5 +- .../sshd_config/ast/parser/ConfigLexer.tokens | 7 +- .../sshd_config/ast/parser/config_lexer.go | 40 +-- .../sshd_config/ast/parser/config_parser.go | 111 +++--- handlers/sshd_config/ast/parser_test.go | 318 ++++++++++++++++++ 10 files changed, 440 insertions(+), 108 deletions(-) diff --git a/handlers/sshd_config/Config.g4 b/handlers/sshd_config/Config.g4 index 65c951a..e959976 100644 --- a/handlers/sshd_config/Config.g4 +++ b/handlers/sshd_config/Config.g4 @@ -13,22 +13,17 @@ key ; value - : STRING + : (STRING WHITESPACE)? STRING ; leadingComment : HASH WHITESPACE? (STRING WHITESPACE?)+ ; - HASH : '#' ; -MATCH - : ('M' | 'm') ('A' | 'a') ('T' | 't') ('C' | 'c') ('H' | 'h') - ; - WHITESPACE : [ \t]+ ; diff --git a/handlers/sshd_config/ast/listener.go b/handlers/sshd_config/ast/listener.go index d7d51db..7345a54 100644 --- a/handlers/sshd_config/ast/listener.go +++ b/handlers/sshd_config/ast/listener.go @@ -3,6 +3,8 @@ package ast import ( "config-lsp/common" "config-lsp/handlers/sshd_config/ast/parser" + "github.com/emirpasic/gods/maps/treemap" + gods "github.com/emirpasic/gods/utils" "strings" ) @@ -47,21 +49,7 @@ func (s *sshParserListener) EnterEntry(ctx *parser.EntryContext) { Value: ctx.GetText(), } - if s.sshContext.currentMatchBlock == nil { - s.Config.Options.Put( - location.Start.Line, - option, - ) - - s.sshContext.currentOption = option - } else { - s.sshContext.currentMatchBlock.Options.Put( - location.Start.Line, - option, - ) - - s.sshContext.currentOption = option - } + s.sshContext.currentOption = option } func (s *sshParserListener) EnterKey(ctx *parser.KeyContext) { @@ -91,17 +79,16 @@ func (s *sshParserListener) EnterValue(ctx *parser.ValueContext) { } func (s *sshParserListener) ExitValue(ctx *parser.ValueContext) { + location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext) + location.ChangeBothLines(s.sshContext.line) + + if s.sshContext.isKeyAMatchBlock { - location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext) - location.ChangeBothLines(s.sshContext.line) - - rawEntry, _ := s.Config.Options.Get(location.Start.Line) - entry := rawEntry.(*SSHOption) - - // Overwrite the current match block + // Add new match block matchBlock := &SSHMatchBlock{ LocationRange: location, - MatchEntry: entry, + MatchEntry: s.sshContext.currentOption, + Options: treemap.NewWith(gods.UInt32Comparator), } s.Config.Options.Put( location.Start.Line, @@ -110,6 +97,16 @@ func (s *sshParserListener) ExitValue(ctx *parser.ValueContext) { s.sshContext.currentMatchBlock = matchBlock s.sshContext.isKeyAMatchBlock = false + } else if s.sshContext.currentMatchBlock != nil { + s.sshContext.currentMatchBlock.Options.Put( + location.Start.Line, + s.sshContext.currentOption, + ) + } else { + s.Config.Options.Put( + location.Start.Line, + s.sshContext.currentOption, + ) } s.sshContext.currentOption = nil diff --git a/handlers/sshd_config/ast/parser.go b/handlers/sshd_config/ast/parser.go index fc510ee..7624284 100644 --- a/handlers/sshd_config/ast/parser.go +++ b/handlers/sshd_config/ast/parser.go @@ -35,12 +35,12 @@ func (c *SSHConfig) Parse(input string) []common.LSPError { for rawLineNumber, line := range lines { context.line = uint32(rawLineNumber) - if commentPattern.MatchString(line) { - c.CommentLines[context.line] = struct{}{} + if emptyPattern.MatchString(line) { continue } - if emptyPattern.MatchString(line) { + if commentPattern.MatchString(line) { + c.CommentLines[context.line] = struct{}{} continue } diff --git a/handlers/sshd_config/ast/parser/Config.interp b/handlers/sshd_config/ast/parser/Config.interp index 74f62e9..1a0d4d0 100644 --- a/handlers/sshd_config/ast/parser/Config.interp +++ b/handlers/sshd_config/ast/parser/Config.interp @@ -4,12 +4,10 @@ null null null null -null token symbolic names: null HASH -MATCH WHITESPACE STRING NEWLINE @@ -23,4 +21,4 @@ leadingComment atn: -[4, 1, 5, 55, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 1, 0, 1, 0, 3, 0, 13, 8, 0, 1, 0, 1, 0, 3, 0, 17, 8, 0, 3, 0, 19, 8, 0, 1, 0, 1, 0, 1, 1, 3, 1, 24, 8, 1, 1, 1, 3, 1, 27, 8, 1, 1, 1, 1, 1, 3, 1, 31, 8, 1, 1, 1, 3, 1, 34, 8, 1, 1, 1, 3, 1, 37, 8, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, 1, 4, 3, 4, 45, 8, 4, 1, 4, 1, 4, 3, 4, 49, 8, 4, 4, 4, 51, 8, 4, 11, 4, 12, 4, 52, 1, 4, 0, 0, 5, 0, 2, 4, 6, 8, 0, 0, 61, 0, 18, 1, 0, 0, 0, 2, 23, 1, 0, 0, 0, 4, 38, 1, 0, 0, 0, 6, 40, 1, 0, 0, 0, 8, 42, 1, 0, 0, 0, 10, 19, 3, 2, 1, 0, 11, 13, 5, 3, 0, 0, 12, 11, 1, 0, 0, 0, 12, 13, 1, 0, 0, 0, 13, 14, 1, 0, 0, 0, 14, 19, 3, 8, 4, 0, 15, 17, 5, 3, 0, 0, 16, 15, 1, 0, 0, 0, 16, 17, 1, 0, 0, 0, 17, 19, 1, 0, 0, 0, 18, 10, 1, 0, 0, 0, 18, 12, 1, 0, 0, 0, 18, 16, 1, 0, 0, 0, 19, 20, 1, 0, 0, 0, 20, 21, 5, 0, 0, 1, 21, 1, 1, 0, 0, 0, 22, 24, 5, 3, 0, 0, 23, 22, 1, 0, 0, 0, 23, 24, 1, 0, 0, 0, 24, 26, 1, 0, 0, 0, 25, 27, 3, 4, 2, 0, 26, 25, 1, 0, 0, 0, 26, 27, 1, 0, 0, 0, 27, 28, 1, 0, 0, 0, 28, 30, 5, 3, 0, 0, 29, 31, 3, 6, 3, 0, 30, 29, 1, 0, 0, 0, 30, 31, 1, 0, 0, 0, 31, 33, 1, 0, 0, 0, 32, 34, 5, 3, 0, 0, 33, 32, 1, 0, 0, 0, 33, 34, 1, 0, 0, 0, 34, 36, 1, 0, 0, 0, 35, 37, 3, 8, 4, 0, 36, 35, 1, 0, 0, 0, 36, 37, 1, 0, 0, 0, 37, 3, 1, 0, 0, 0, 38, 39, 5, 4, 0, 0, 39, 5, 1, 0, 0, 0, 40, 41, 5, 4, 0, 0, 41, 7, 1, 0, 0, 0, 42, 44, 5, 1, 0, 0, 43, 45, 5, 3, 0, 0, 44, 43, 1, 0, 0, 0, 44, 45, 1, 0, 0, 0, 45, 50, 1, 0, 0, 0, 46, 48, 5, 4, 0, 0, 47, 49, 5, 3, 0, 0, 48, 47, 1, 0, 0, 0, 48, 49, 1, 0, 0, 0, 49, 51, 1, 0, 0, 0, 50, 46, 1, 0, 0, 0, 51, 52, 1, 0, 0, 0, 52, 50, 1, 0, 0, 0, 52, 53, 1, 0, 0, 0, 53, 9, 1, 0, 0, 0, 11, 12, 16, 18, 23, 26, 30, 33, 36, 44, 48, 52] \ No newline at end of file +[4, 1, 4, 59, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 1, 0, 1, 0, 3, 0, 13, 8, 0, 1, 0, 1, 0, 3, 0, 17, 8, 0, 3, 0, 19, 8, 0, 1, 0, 1, 0, 1, 1, 3, 1, 24, 8, 1, 1, 1, 3, 1, 27, 8, 1, 1, 1, 1, 1, 3, 1, 31, 8, 1, 1, 1, 3, 1, 34, 8, 1, 1, 1, 3, 1, 37, 8, 1, 1, 2, 1, 2, 1, 3, 1, 3, 3, 3, 43, 8, 3, 1, 3, 1, 3, 1, 4, 1, 4, 3, 4, 49, 8, 4, 1, 4, 1, 4, 3, 4, 53, 8, 4, 4, 4, 55, 8, 4, 11, 4, 12, 4, 56, 1, 4, 0, 0, 5, 0, 2, 4, 6, 8, 0, 0, 66, 0, 18, 1, 0, 0, 0, 2, 23, 1, 0, 0, 0, 4, 38, 1, 0, 0, 0, 6, 42, 1, 0, 0, 0, 8, 46, 1, 0, 0, 0, 10, 19, 3, 2, 1, 0, 11, 13, 5, 2, 0, 0, 12, 11, 1, 0, 0, 0, 12, 13, 1, 0, 0, 0, 13, 14, 1, 0, 0, 0, 14, 19, 3, 8, 4, 0, 15, 17, 5, 2, 0, 0, 16, 15, 1, 0, 0, 0, 16, 17, 1, 0, 0, 0, 17, 19, 1, 0, 0, 0, 18, 10, 1, 0, 0, 0, 18, 12, 1, 0, 0, 0, 18, 16, 1, 0, 0, 0, 19, 20, 1, 0, 0, 0, 20, 21, 5, 0, 0, 1, 21, 1, 1, 0, 0, 0, 22, 24, 5, 2, 0, 0, 23, 22, 1, 0, 0, 0, 23, 24, 1, 0, 0, 0, 24, 26, 1, 0, 0, 0, 25, 27, 3, 4, 2, 0, 26, 25, 1, 0, 0, 0, 26, 27, 1, 0, 0, 0, 27, 28, 1, 0, 0, 0, 28, 30, 5, 2, 0, 0, 29, 31, 3, 6, 3, 0, 30, 29, 1, 0, 0, 0, 30, 31, 1, 0, 0, 0, 31, 33, 1, 0, 0, 0, 32, 34, 5, 2, 0, 0, 33, 32, 1, 0, 0, 0, 33, 34, 1, 0, 0, 0, 34, 36, 1, 0, 0, 0, 35, 37, 3, 8, 4, 0, 36, 35, 1, 0, 0, 0, 36, 37, 1, 0, 0, 0, 37, 3, 1, 0, 0, 0, 38, 39, 5, 3, 0, 0, 39, 5, 1, 0, 0, 0, 40, 41, 5, 3, 0, 0, 41, 43, 5, 2, 0, 0, 42, 40, 1, 0, 0, 0, 42, 43, 1, 0, 0, 0, 43, 44, 1, 0, 0, 0, 44, 45, 5, 3, 0, 0, 45, 7, 1, 0, 0, 0, 46, 48, 5, 1, 0, 0, 47, 49, 5, 2, 0, 0, 48, 47, 1, 0, 0, 0, 48, 49, 1, 0, 0, 0, 49, 54, 1, 0, 0, 0, 50, 52, 5, 3, 0, 0, 51, 53, 5, 2, 0, 0, 52, 51, 1, 0, 0, 0, 52, 53, 1, 0, 0, 0, 53, 55, 1, 0, 0, 0, 54, 50, 1, 0, 0, 0, 55, 56, 1, 0, 0, 0, 56, 54, 1, 0, 0, 0, 56, 57, 1, 0, 0, 0, 57, 9, 1, 0, 0, 0, 12, 12, 16, 18, 23, 26, 30, 33, 36, 42, 48, 52, 56] \ No newline at end of file diff --git a/handlers/sshd_config/ast/parser/Config.tokens b/handlers/sshd_config/ast/parser/Config.tokens index 30ff5e0..aacc14c 100644 --- a/handlers/sshd_config/ast/parser/Config.tokens +++ b/handlers/sshd_config/ast/parser/Config.tokens @@ -1,6 +1,5 @@ HASH=1 -MATCH=2 -WHITESPACE=3 -STRING=4 -NEWLINE=5 +WHITESPACE=2 +STRING=3 +NEWLINE=4 '#'=1 diff --git a/handlers/sshd_config/ast/parser/ConfigLexer.interp b/handlers/sshd_config/ast/parser/ConfigLexer.interp index 4ac663c..d61e14d 100644 --- a/handlers/sshd_config/ast/parser/ConfigLexer.interp +++ b/handlers/sshd_config/ast/parser/ConfigLexer.interp @@ -4,19 +4,16 @@ null null null null -null token symbolic names: null HASH -MATCH WHITESPACE STRING NEWLINE rule names: HASH -MATCH WHITESPACE STRING NEWLINE @@ -29,4 +26,4 @@ mode names: DEFAULT_MODE atn: -[4, 0, 5, 34, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 4, 2, 21, 8, 2, 11, 2, 12, 2, 22, 1, 3, 4, 3, 26, 8, 3, 11, 3, 12, 3, 27, 1, 4, 3, 4, 31, 8, 4, 1, 4, 1, 4, 0, 0, 5, 1, 1, 3, 2, 5, 3, 7, 4, 9, 5, 1, 0, 7, 2, 0, 77, 77, 109, 109, 2, 0, 65, 65, 97, 97, 2, 0, 84, 84, 116, 116, 2, 0, 67, 67, 99, 99, 2, 0, 72, 72, 104, 104, 2, 0, 9, 9, 32, 32, 4, 0, 9, 10, 13, 13, 32, 32, 35, 35, 36, 0, 1, 1, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, 5, 1, 0, 0, 0, 0, 7, 1, 0, 0, 0, 0, 9, 1, 0, 0, 0, 1, 11, 1, 0, 0, 0, 3, 13, 1, 0, 0, 0, 5, 20, 1, 0, 0, 0, 7, 25, 1, 0, 0, 0, 9, 30, 1, 0, 0, 0, 11, 12, 5, 35, 0, 0, 12, 2, 1, 0, 0, 0, 13, 14, 7, 0, 0, 0, 14, 15, 7, 1, 0, 0, 15, 16, 7, 2, 0, 0, 16, 17, 7, 3, 0, 0, 17, 18, 7, 4, 0, 0, 18, 4, 1, 0, 0, 0, 19, 21, 7, 5, 0, 0, 20, 19, 1, 0, 0, 0, 21, 22, 1, 0, 0, 0, 22, 20, 1, 0, 0, 0, 22, 23, 1, 0, 0, 0, 23, 6, 1, 0, 0, 0, 24, 26, 8, 6, 0, 0, 25, 24, 1, 0, 0, 0, 26, 27, 1, 0, 0, 0, 27, 25, 1, 0, 0, 0, 27, 28, 1, 0, 0, 0, 28, 8, 1, 0, 0, 0, 29, 31, 5, 13, 0, 0, 30, 29, 1, 0, 0, 0, 30, 31, 1, 0, 0, 0, 31, 32, 1, 0, 0, 0, 32, 33, 5, 10, 0, 0, 33, 10, 1, 0, 0, 0, 4, 0, 22, 27, 30, 0] \ No newline at end of file +[4, 0, 4, 26, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 1, 0, 1, 0, 1, 1, 4, 1, 13, 8, 1, 11, 1, 12, 1, 14, 1, 2, 4, 2, 18, 8, 2, 11, 2, 12, 2, 19, 1, 3, 3, 3, 23, 8, 3, 1, 3, 1, 3, 0, 0, 4, 1, 1, 3, 2, 5, 3, 7, 4, 1, 0, 2, 2, 0, 9, 9, 32, 32, 4, 0, 9, 10, 13, 13, 32, 32, 35, 35, 28, 0, 1, 1, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, 5, 1, 0, 0, 0, 0, 7, 1, 0, 0, 0, 1, 9, 1, 0, 0, 0, 3, 12, 1, 0, 0, 0, 5, 17, 1, 0, 0, 0, 7, 22, 1, 0, 0, 0, 9, 10, 5, 35, 0, 0, 10, 2, 1, 0, 0, 0, 11, 13, 7, 0, 0, 0, 12, 11, 1, 0, 0, 0, 13, 14, 1, 0, 0, 0, 14, 12, 1, 0, 0, 0, 14, 15, 1, 0, 0, 0, 15, 4, 1, 0, 0, 0, 16, 18, 8, 1, 0, 0, 17, 16, 1, 0, 0, 0, 18, 19, 1, 0, 0, 0, 19, 17, 1, 0, 0, 0, 19, 20, 1, 0, 0, 0, 20, 6, 1, 0, 0, 0, 21, 23, 5, 13, 0, 0, 22, 21, 1, 0, 0, 0, 22, 23, 1, 0, 0, 0, 23, 24, 1, 0, 0, 0, 24, 25, 5, 10, 0, 0, 25, 8, 1, 0, 0, 0, 4, 0, 14, 19, 22, 0] \ No newline at end of file diff --git a/handlers/sshd_config/ast/parser/ConfigLexer.tokens b/handlers/sshd_config/ast/parser/ConfigLexer.tokens index 30ff5e0..aacc14c 100644 --- a/handlers/sshd_config/ast/parser/ConfigLexer.tokens +++ b/handlers/sshd_config/ast/parser/ConfigLexer.tokens @@ -1,6 +1,5 @@ HASH=1 -MATCH=2 -WHITESPACE=3 -STRING=4 -NEWLINE=5 +WHITESPACE=2 +STRING=3 +NEWLINE=4 '#'=1 diff --git a/handlers/sshd_config/ast/parser/config_lexer.go b/handlers/sshd_config/ast/parser/config_lexer.go index cf0a348..ace491d 100644 --- a/handlers/sshd_config/ast/parser/config_lexer.go +++ b/handlers/sshd_config/ast/parser/config_lexer.go @@ -46,30 +46,25 @@ func configlexerLexerInit() { "", "'#'", } staticData.SymbolicNames = []string{ - "", "HASH", "MATCH", "WHITESPACE", "STRING", "NEWLINE", + "", "HASH", "WHITESPACE", "STRING", "NEWLINE", } staticData.RuleNames = []string{ - "HASH", "MATCH", "WHITESPACE", "STRING", "NEWLINE", + "HASH", "WHITESPACE", "STRING", "NEWLINE", } staticData.PredictionContextCache = antlr.NewPredictionContextCache() staticData.serializedATN = []int32{ - 4, 0, 5, 34, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, - 4, 7, 4, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 4, 2, 21, - 8, 2, 11, 2, 12, 2, 22, 1, 3, 4, 3, 26, 8, 3, 11, 3, 12, 3, 27, 1, 4, 3, - 4, 31, 8, 4, 1, 4, 1, 4, 0, 0, 5, 1, 1, 3, 2, 5, 3, 7, 4, 9, 5, 1, 0, 7, - 2, 0, 77, 77, 109, 109, 2, 0, 65, 65, 97, 97, 2, 0, 84, 84, 116, 116, 2, - 0, 67, 67, 99, 99, 2, 0, 72, 72, 104, 104, 2, 0, 9, 9, 32, 32, 4, 0, 9, - 10, 13, 13, 32, 32, 35, 35, 36, 0, 1, 1, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, - 5, 1, 0, 0, 0, 0, 7, 1, 0, 0, 0, 0, 9, 1, 0, 0, 0, 1, 11, 1, 0, 0, 0, 3, - 13, 1, 0, 0, 0, 5, 20, 1, 0, 0, 0, 7, 25, 1, 0, 0, 0, 9, 30, 1, 0, 0, 0, - 11, 12, 5, 35, 0, 0, 12, 2, 1, 0, 0, 0, 13, 14, 7, 0, 0, 0, 14, 15, 7, - 1, 0, 0, 15, 16, 7, 2, 0, 0, 16, 17, 7, 3, 0, 0, 17, 18, 7, 4, 0, 0, 18, - 4, 1, 0, 0, 0, 19, 21, 7, 5, 0, 0, 20, 19, 1, 0, 0, 0, 21, 22, 1, 0, 0, - 0, 22, 20, 1, 0, 0, 0, 22, 23, 1, 0, 0, 0, 23, 6, 1, 0, 0, 0, 24, 26, 8, - 6, 0, 0, 25, 24, 1, 0, 0, 0, 26, 27, 1, 0, 0, 0, 27, 25, 1, 0, 0, 0, 27, - 28, 1, 0, 0, 0, 28, 8, 1, 0, 0, 0, 29, 31, 5, 13, 0, 0, 30, 29, 1, 0, 0, - 0, 30, 31, 1, 0, 0, 0, 31, 32, 1, 0, 0, 0, 32, 33, 5, 10, 0, 0, 33, 10, - 1, 0, 0, 0, 4, 0, 22, 27, 30, 0, + 4, 0, 4, 26, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 1, + 0, 1, 0, 1, 1, 4, 1, 13, 8, 1, 11, 1, 12, 1, 14, 1, 2, 4, 2, 18, 8, 2, + 11, 2, 12, 2, 19, 1, 3, 3, 3, 23, 8, 3, 1, 3, 1, 3, 0, 0, 4, 1, 1, 3, 2, + 5, 3, 7, 4, 1, 0, 2, 2, 0, 9, 9, 32, 32, 4, 0, 9, 10, 13, 13, 32, 32, 35, + 35, 28, 0, 1, 1, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, 5, 1, 0, 0, 0, 0, 7, 1, + 0, 0, 0, 1, 9, 1, 0, 0, 0, 3, 12, 1, 0, 0, 0, 5, 17, 1, 0, 0, 0, 7, 22, + 1, 0, 0, 0, 9, 10, 5, 35, 0, 0, 10, 2, 1, 0, 0, 0, 11, 13, 7, 0, 0, 0, + 12, 11, 1, 0, 0, 0, 13, 14, 1, 0, 0, 0, 14, 12, 1, 0, 0, 0, 14, 15, 1, + 0, 0, 0, 15, 4, 1, 0, 0, 0, 16, 18, 8, 1, 0, 0, 17, 16, 1, 0, 0, 0, 18, + 19, 1, 0, 0, 0, 19, 17, 1, 0, 0, 0, 19, 20, 1, 0, 0, 0, 20, 6, 1, 0, 0, + 0, 21, 23, 5, 13, 0, 0, 22, 21, 1, 0, 0, 0, 22, 23, 1, 0, 0, 0, 23, 24, + 1, 0, 0, 0, 24, 25, 5, 10, 0, 0, 25, 8, 1, 0, 0, 0, 4, 0, 14, 19, 22, 0, } deserializer := antlr.NewATNDeserializer(nil) staticData.atn = deserializer.Deserialize(staticData.serializedATN) @@ -111,8 +106,7 @@ func NewConfigLexer(input antlr.CharStream) *ConfigLexer { // ConfigLexer tokens. const ( ConfigLexerHASH = 1 - ConfigLexerMATCH = 2 - ConfigLexerWHITESPACE = 3 - ConfigLexerSTRING = 4 - ConfigLexerNEWLINE = 5 + ConfigLexerWHITESPACE = 2 + ConfigLexerSTRING = 3 + ConfigLexerNEWLINE = 4 ) diff --git a/handlers/sshd_config/ast/parser/config_parser.go b/handlers/sshd_config/ast/parser/config_parser.go index a52548d..dbfca6f 100644 --- a/handlers/sshd_config/ast/parser/config_parser.go +++ b/handlers/sshd_config/ast/parser/config_parser.go @@ -36,37 +36,39 @@ func configParserInit() { "", "'#'", } staticData.SymbolicNames = []string{ - "", "HASH", "MATCH", "WHITESPACE", "STRING", "NEWLINE", + "", "HASH", "WHITESPACE", "STRING", "NEWLINE", } staticData.RuleNames = []string{ "lineStatement", "entry", "key", "value", "leadingComment", } staticData.PredictionContextCache = antlr.NewPredictionContextCache() staticData.serializedATN = []int32{ - 4, 1, 5, 55, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, + 4, 1, 4, 59, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 1, 0, 1, 0, 3, 0, 13, 8, 0, 1, 0, 1, 0, 3, 0, 17, 8, 0, 3, 0, 19, 8, 0, 1, 0, 1, 0, 1, 1, 3, 1, 24, 8, 1, 1, 1, 3, 1, 27, 8, 1, 1, 1, 1, 1, 3, 1, 31, 8, 1, 1, 1, 3, 1, 34, 8, 1, 1, 1, 3, 1, 37, 8, 1, 1, 2, 1, 2, 1, - 3, 1, 3, 1, 4, 1, 4, 3, 4, 45, 8, 4, 1, 4, 1, 4, 3, 4, 49, 8, 4, 4, 4, - 51, 8, 4, 11, 4, 12, 4, 52, 1, 4, 0, 0, 5, 0, 2, 4, 6, 8, 0, 0, 61, 0, - 18, 1, 0, 0, 0, 2, 23, 1, 0, 0, 0, 4, 38, 1, 0, 0, 0, 6, 40, 1, 0, 0, 0, - 8, 42, 1, 0, 0, 0, 10, 19, 3, 2, 1, 0, 11, 13, 5, 3, 0, 0, 12, 11, 1, 0, - 0, 0, 12, 13, 1, 0, 0, 0, 13, 14, 1, 0, 0, 0, 14, 19, 3, 8, 4, 0, 15, 17, - 5, 3, 0, 0, 16, 15, 1, 0, 0, 0, 16, 17, 1, 0, 0, 0, 17, 19, 1, 0, 0, 0, - 18, 10, 1, 0, 0, 0, 18, 12, 1, 0, 0, 0, 18, 16, 1, 0, 0, 0, 19, 20, 1, - 0, 0, 0, 20, 21, 5, 0, 0, 1, 21, 1, 1, 0, 0, 0, 22, 24, 5, 3, 0, 0, 23, - 22, 1, 0, 0, 0, 23, 24, 1, 0, 0, 0, 24, 26, 1, 0, 0, 0, 25, 27, 3, 4, 2, - 0, 26, 25, 1, 0, 0, 0, 26, 27, 1, 0, 0, 0, 27, 28, 1, 0, 0, 0, 28, 30, - 5, 3, 0, 0, 29, 31, 3, 6, 3, 0, 30, 29, 1, 0, 0, 0, 30, 31, 1, 0, 0, 0, - 31, 33, 1, 0, 0, 0, 32, 34, 5, 3, 0, 0, 33, 32, 1, 0, 0, 0, 33, 34, 1, - 0, 0, 0, 34, 36, 1, 0, 0, 0, 35, 37, 3, 8, 4, 0, 36, 35, 1, 0, 0, 0, 36, - 37, 1, 0, 0, 0, 37, 3, 1, 0, 0, 0, 38, 39, 5, 4, 0, 0, 39, 5, 1, 0, 0, - 0, 40, 41, 5, 4, 0, 0, 41, 7, 1, 0, 0, 0, 42, 44, 5, 1, 0, 0, 43, 45, 5, - 3, 0, 0, 44, 43, 1, 0, 0, 0, 44, 45, 1, 0, 0, 0, 45, 50, 1, 0, 0, 0, 46, - 48, 5, 4, 0, 0, 47, 49, 5, 3, 0, 0, 48, 47, 1, 0, 0, 0, 48, 49, 1, 0, 0, - 0, 49, 51, 1, 0, 0, 0, 50, 46, 1, 0, 0, 0, 51, 52, 1, 0, 0, 0, 52, 50, - 1, 0, 0, 0, 52, 53, 1, 0, 0, 0, 53, 9, 1, 0, 0, 0, 11, 12, 16, 18, 23, - 26, 30, 33, 36, 44, 48, 52, + 3, 1, 3, 3, 3, 43, 8, 3, 1, 3, 1, 3, 1, 4, 1, 4, 3, 4, 49, 8, 4, 1, 4, + 1, 4, 3, 4, 53, 8, 4, 4, 4, 55, 8, 4, 11, 4, 12, 4, 56, 1, 4, 0, 0, 5, + 0, 2, 4, 6, 8, 0, 0, 66, 0, 18, 1, 0, 0, 0, 2, 23, 1, 0, 0, 0, 4, 38, 1, + 0, 0, 0, 6, 42, 1, 0, 0, 0, 8, 46, 1, 0, 0, 0, 10, 19, 3, 2, 1, 0, 11, + 13, 5, 2, 0, 0, 12, 11, 1, 0, 0, 0, 12, 13, 1, 0, 0, 0, 13, 14, 1, 0, 0, + 0, 14, 19, 3, 8, 4, 0, 15, 17, 5, 2, 0, 0, 16, 15, 1, 0, 0, 0, 16, 17, + 1, 0, 0, 0, 17, 19, 1, 0, 0, 0, 18, 10, 1, 0, 0, 0, 18, 12, 1, 0, 0, 0, + 18, 16, 1, 0, 0, 0, 19, 20, 1, 0, 0, 0, 20, 21, 5, 0, 0, 1, 21, 1, 1, 0, + 0, 0, 22, 24, 5, 2, 0, 0, 23, 22, 1, 0, 0, 0, 23, 24, 1, 0, 0, 0, 24, 26, + 1, 0, 0, 0, 25, 27, 3, 4, 2, 0, 26, 25, 1, 0, 0, 0, 26, 27, 1, 0, 0, 0, + 27, 28, 1, 0, 0, 0, 28, 30, 5, 2, 0, 0, 29, 31, 3, 6, 3, 0, 30, 29, 1, + 0, 0, 0, 30, 31, 1, 0, 0, 0, 31, 33, 1, 0, 0, 0, 32, 34, 5, 2, 0, 0, 33, + 32, 1, 0, 0, 0, 33, 34, 1, 0, 0, 0, 34, 36, 1, 0, 0, 0, 35, 37, 3, 8, 4, + 0, 36, 35, 1, 0, 0, 0, 36, 37, 1, 0, 0, 0, 37, 3, 1, 0, 0, 0, 38, 39, 5, + 3, 0, 0, 39, 5, 1, 0, 0, 0, 40, 41, 5, 3, 0, 0, 41, 43, 5, 2, 0, 0, 42, + 40, 1, 0, 0, 0, 42, 43, 1, 0, 0, 0, 43, 44, 1, 0, 0, 0, 44, 45, 5, 3, 0, + 0, 45, 7, 1, 0, 0, 0, 46, 48, 5, 1, 0, 0, 47, 49, 5, 2, 0, 0, 48, 47, 1, + 0, 0, 0, 48, 49, 1, 0, 0, 0, 49, 54, 1, 0, 0, 0, 50, 52, 5, 3, 0, 0, 51, + 53, 5, 2, 0, 0, 52, 51, 1, 0, 0, 0, 52, 53, 1, 0, 0, 0, 53, 55, 1, 0, 0, + 0, 54, 50, 1, 0, 0, 0, 55, 56, 1, 0, 0, 0, 56, 54, 1, 0, 0, 0, 56, 57, + 1, 0, 0, 0, 57, 9, 1, 0, 0, 0, 12, 12, 16, 18, 23, 26, 30, 33, 36, 42, + 48, 52, 56, } deserializer := antlr.NewATNDeserializer(nil) staticData.atn = deserializer.Deserialize(staticData.serializedATN) @@ -106,10 +108,9 @@ func NewConfigParser(input antlr.TokenStream) *ConfigParser { const ( ConfigParserEOF = antlr.TokenEOF ConfigParserHASH = 1 - ConfigParserMATCH = 2 - ConfigParserWHITESPACE = 3 - ConfigParserSTRING = 4 - ConfigParserNEWLINE = 5 + ConfigParserWHITESPACE = 2 + ConfigParserSTRING = 3 + ConfigParserNEWLINE = 4 ) // ConfigParser rules. @@ -652,7 +653,9 @@ type IValueContext interface { GetParser() antlr.Parser // Getter signatures - STRING() antlr.TerminalNode + AllSTRING() []antlr.TerminalNode + STRING(i int) antlr.TerminalNode + WHITESPACE() antlr.TerminalNode // IsValueContext differentiates from other interfaces. IsValueContext() @@ -690,8 +693,16 @@ func NewValueContext(parser antlr.Parser, parent antlr.ParserRuleContext, invoki func (s *ValueContext) GetParser() antlr.Parser { return s.parser } -func (s *ValueContext) STRING() antlr.TerminalNode { - return s.GetToken(ConfigParserSTRING, 0) +func (s *ValueContext) AllSTRING() []antlr.TerminalNode { + return s.GetTokens(ConfigParserSTRING) +} + +func (s *ValueContext) STRING(i int) antlr.TerminalNode { + return s.GetToken(ConfigParserSTRING, i) +} + +func (s *ValueContext) WHITESPACE() antlr.TerminalNode { + return s.GetToken(ConfigParserWHITESPACE, 0) } func (s *ValueContext) GetRuleContext() antlr.RuleContext { @@ -718,8 +729,32 @@ func (p *ConfigParser) Value() (localctx IValueContext) { localctx = NewValueContext(p, p.GetParserRuleContext(), p.GetState()) p.EnterRule(localctx, 6, ConfigParserRULE_value) p.EnterOuterAlt(localctx, 1) + p.SetState(42) + p.GetErrorHandler().Sync(p) + + if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 8, p.GetParserRuleContext()) == 1 { + { + p.SetState(40) + p.Match(ConfigParserSTRING) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + { + p.SetState(41) + p.Match(ConfigParserWHITESPACE) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + + } else if p.HasError() { // JIM + goto errorExit + } { - p.SetState(40) + p.SetState(44) p.Match(ConfigParserSTRING) if p.HasError() { // Recognition error - abort rule @@ -837,14 +872,14 @@ func (p *ConfigParser) LeadingComment() (localctx ILeadingCommentContext) { p.EnterOuterAlt(localctx, 1) { - p.SetState(42) + p.SetState(46) p.Match(ConfigParserHASH) if p.HasError() { // Recognition error - abort rule goto errorExit } } - p.SetState(44) + p.SetState(48) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -853,7 +888,7 @@ func (p *ConfigParser) LeadingComment() (localctx ILeadingCommentContext) { if _la == ConfigParserWHITESPACE { { - p.SetState(43) + p.SetState(47) p.Match(ConfigParserWHITESPACE) if p.HasError() { // Recognition error - abort rule @@ -862,7 +897,7 @@ func (p *ConfigParser) LeadingComment() (localctx ILeadingCommentContext) { } } - p.SetState(50) + p.SetState(54) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -871,14 +906,14 @@ func (p *ConfigParser) LeadingComment() (localctx ILeadingCommentContext) { for ok := true; ok; ok = _la == ConfigParserSTRING { { - p.SetState(46) + p.SetState(50) p.Match(ConfigParserSTRING) if p.HasError() { // Recognition error - abort rule goto errorExit } } - p.SetState(48) + p.SetState(52) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -887,7 +922,7 @@ func (p *ConfigParser) LeadingComment() (localctx ILeadingCommentContext) { if _la == ConfigParserWHITESPACE { { - p.SetState(47) + p.SetState(51) p.Match(ConfigParserWHITESPACE) if p.HasError() { // Recognition error - abort rule @@ -897,7 +932,7 @@ func (p *ConfigParser) LeadingComment() (localctx ILeadingCommentContext) { } - p.SetState(52) + p.SetState(56) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit diff --git a/handlers/sshd_config/ast/parser_test.go b/handlers/sshd_config/ast/parser_test.go index 53a0458..6f5d0a3 100644 --- a/handlers/sshd_config/ast/parser_test.go +++ b/handlers/sshd_config/ast/parser_test.go @@ -58,3 +58,321 @@ PasswordAuthentication yes t.Errorf("Expected second entry to be PasswordAuthentication yes, but got: %v", secondEntry) } } + +func TestMatchSimpleBlock( + t *testing.T, +) { + input := utils.Dedent(` +PermitRootLogin no + +Match 192.168.0.1 + PasswordAuthentication yes +`) + p := NewSSHConfig() + errors := p.Parse(input) + + if len(errors) != 0 { + t.Fatalf("Expected no errors, got %v", errors) + } + + if !(p.Options.Size() == 2 && + len(utils.KeysOfMap(p.CommentLines)) == 0) { + t.Errorf("Expected 1 option and no comment lines, but got: %v, %v", p.Options, p.CommentLines) + } + + rawFirstEntry, _ := p.Options.Get(uint32(0)) + firstEntry := rawFirstEntry.(*SSHOption) + if !(firstEntry.Value == "PermitRootLogin no") { + t.Errorf("Expected first entry to be 'PermitRootLogin no', but got: %v", firstEntry.Value) + } + + rawSecondEntry, _ := p.Options.Get(uint32(2)) + secondEntry := rawSecondEntry.(*SSHMatchBlock) + if !(secondEntry.MatchEntry.Value == "Match 192.168.0.1") { + t.Errorf("Expected second entry to be 'Match 192.168.0.1', but got: %v", secondEntry.MatchEntry.Value) + } + + if !(secondEntry.Options.Size() == 1) { + t.Errorf("Expected 1 option in match block, but got: %v", secondEntry.Options) + } + + rawThirdEntry, _ := secondEntry.Options.Get(uint32(3)) + thirdEntry := rawThirdEntry.(*SSHOption) + if !(thirdEntry.Key.Value == "PasswordAuthentication" && thirdEntry.OptionValue.Value == "yes") { + t.Errorf("Expected third entry to be 'PasswordAuthentication yes', but got: %v", thirdEntry.Value) + } +} + +func TestMultipleMatchBlocks( + t *testing.T, +) { + input := utils.Dedent(` +PermitRootLogin no + +Match 192.168.0.1 + PasswordAuthentication yes + AllowUsers root user + +Match 192.168.0.2 + MaxAuthTries 3 +`) + p := NewSSHConfig() + errors := p.Parse(input) + + if len(errors) != 0 { + t.Fatalf("Expected no errors, got %v", errors) + } + + if !(p.Options.Size() == 3 && + len(utils.KeysOfMap(p.CommentLines)) == 0) { + t.Errorf("Expected 3 options and no comment lines, but got: %v, %v", p.Options, p.CommentLines) + } + + rawSecondEntry, _ := p.Options.Get(uint32(2)) + secondEntry := rawSecondEntry.(*SSHMatchBlock) + if !(secondEntry.Options.Size() == 2) { + t.Errorf("Expected 2 options in second match block, but got: %v", secondEntry.Options) + } + + rawThirdEntry, _ := secondEntry.Options.Get(uint32(3)) + thirdEntry := rawThirdEntry.(*SSHOption) + if !(thirdEntry.Key.Value == "PasswordAuthentication" && thirdEntry.OptionValue.Value == "yes") { + t.Errorf("Expected third entry to be 'PasswordAuthentication yes', but got: %v", thirdEntry.Value) + } + + rawFourthEntry, _ := secondEntry.Options.Get(uint32(4)) + fourthEntry := rawFourthEntry.(*SSHOption) + if !(fourthEntry.Key.Value == "AllowUsers" && fourthEntry.OptionValue.Value == "root user") { + t.Errorf("Expected fourth entry to be 'AllowUsers root user', but got: %v", fourthEntry.Value) + } + + rawFifthEntry, _ := p.Options.Get(uint32(6)) + fifthEntry := rawFifthEntry.(*SSHMatchBlock) + if !(fifthEntry.Options.Size() == 1) { + t.Errorf("Expected 1 option in fifth match block, but got: %v", fifthEntry.Options) + } + + rawSixthEntry, _ := fifthEntry.Options.Get(uint32(7)) + sixthEntry := rawSixthEntry.(*SSHOption) + if !(sixthEntry.Key.Value == "MaxAuthTries" && sixthEntry.OptionValue.Value == "3") { + t.Errorf("Expected sixth entry to be 'MaxAuthTries 3', but got: %v", sixthEntry.Value) + } +} + +func TestComplexExample( + t *testing.T, +) { + // From https://gist.github.com/kjellski/5940875 + input := utils.Dedent(` +# This is the sshd server system-wide configuration file. See +# sshd_config(5) for more information. + +# This sshd was compiled with PATH=/usr/bin:/bin:/usr/sbin:/sbin + +# The strategy used for options in the default sshd_config shipped with +# OpenSSH is to specify options with their default value where +# possible, but leave them commented. Uncommented options change a +# default value. + +#Port 22 +#AddressFamily any +#ListenAddress 0.0.0.0 +#ListenAddress :: + +# The default requires explicit activation of protocol 1 +#Protocol 2 + +# HostKey for protocol version 1 +#HostKey /etc/ssh/ssh_host_key +# HostKeys for protocol version 2 +#HostKey /etc/ssh/ssh_host_rsa_key +#HostKey /etc/ssh/ssh_host_dsa_key +#HostKey /etc/ssh/ssh_host_ecdsa_key + +# Lifetime and size of ephemeral version 1 server key +#KeyRegenerationInterval 1h +#ServerKeyBits 1024 + +# Logging +# obsoletes QuietMode and FascistLogging +#SyslogFacility AUTH +#LogLevel INFO + +# Authentication: + +#LoginGraceTime 2m +#BC# Root only allowed to login from LAN IP ranges listed at end +PermitRootLogin no +#PermitRootLogin yes +#StrictModes yes +#MaxAuthTries 6 +#MaxSessions 10 + +#RSAAuthentication yes +#PubkeyAuthentication yes +#AuthorizedKeysFile .ssh/authorized_keys + +# For this to work you will also need host keys in /etc/ssh/ssh_known_hosts +#RhostsRSAAuthentication no +# similar for protocol version 2 +#HostbasedAuthentication no +# Change to yes if you don't trust ~/.ssh/known_hosts for +# RhostsRSAAuthentication and HostbasedAuthentication +#IgnoreUserKnownHosts no +# Don't read the user's ~/.rhosts and ~/.shosts files +#IgnoreRhosts yes + +# To disable tunneled clear text passwords, change to no here! +#BC# Disable password authentication by default (except for LAN IP ranges listed later) +PasswordAuthentication no +PermitEmptyPasswords no +#BC# Have to allow root here because AllowUsers not allowed in Match block. It will not work though because of PermitRootLogin. +#BC# This is no longer true as of 6.1. AllowUsers is now allowed in a Match block. +AllowUsers kmk root + +# Change to no to disable s/key passwords +#BC# I occasionally use s/key one time passwords generated by a phone app +ChallengeResponseAuthentication yes + +# Kerberos options +#KerberosAuthentication no +#KerberosOrLocalPasswd yes +#KerberosTicketCleanup yes +#KerberosGetAFSToken no + +# GSSAPI options +#GSSAPIAuthentication no +#GSSAPICleanupCredentials yes + +# Set this to 'yes' to enable PAM authentication, account processing, +# and session processing. If this is enabled, PAM authentication will +# be allowed through the ChallengeResponseAuthentication and +# PasswordAuthentication. Depending on your PAM configuration, +# PAM authentication via ChallengeResponseAuthentication may bypass +# the setting of "PermitRootLogin without-password". +# If you just want the PAM account and session checks to run without +# PAM authentication, then enable this but set PasswordAuthentication +# and ChallengeResponseAuthentication to 'no'. +#BC# I would turn this off but I compiled ssh without PAM support so it errors if I set this. +#UsePAM no + +#AllowAgentForwarding yes +#AllowTcpForwarding yes +#GatewayPorts no +X11Forwarding yes +#X11DisplayOffset 10 +#X11UseLocalhost yes +#PrintMotd yes +#PrintLastLog yes +#TCPKeepAlive yes +#UseLogin no +#UsePrivilegeSeparation yes +#PermitUserEnvironment no +#Compression delayed +#ClientAliveInterval 0 +#ClientAliveCountMax 3 +#UseDNS yes +#PidFile /var/run/sshd.pid +#MaxStartups 10 +#PermitTunnel no +#ChrootDirectory none + +# no default banner path +#Banner none + +# override default of no subsystems +#Subsystem sftp /usr/lib/misc/sftp-server +Subsystem sftp internal-sftp + +# the following are HPN related configuration options +# tcp receive buffer polling. disable in non autotuning kernels +#TcpRcvBufPoll yes + +# allow the use of the none cipher +#NoneEnabled no + +# disable hpn performance boosts. +#HPNDisabled no + +# buffer size for hpn to non-hpn connections +#HPNBufferSize 2048 + + +# Example of overriding settings on a per-user basis +Match User anoncvs + X11Forwarding no + AllowTcpForwarding no + ForceCommand cvs server + +#BC# My internal networks +#BC# Root can log in from here but only with a key and kmk can log in here with a password. +Match Address 172.22.100.0/24,172.22.5.0/24,127.0.0.1 + PermitRootLogin without-password + PasswordAuthentication yes +`) + p := NewSSHConfig() + errors := p.Parse(input) + + if len(errors) != 0 { + t.Fatalf("Expected no errors, got %v", errors) + } + + if !(p.Options.Size() == 9 && + len(utils.KeysOfMap(p.CommentLines)) == 105) { + t.Errorf("Expected 9 options and 105 comment lines, but got: %v, %v", p.Options, p.CommentLines) + } + + rawFirstEntry, _ := p.Options.Get(uint32(38)) + firstEntry := rawFirstEntry.(*SSHOption) + if !(firstEntry.Key.Value == "PermitRootLogin" && firstEntry.OptionValue.Value == "no") { + t.Errorf("Expected first entry to be 'PermitRootLogin no', but got: %v", firstEntry.Value) + } + + rawSecondEntry, _ := p.Options.Get(uint32(60)) + secondEntry := rawSecondEntry.(*SSHOption) + if !(secondEntry.Key.Value == "PasswordAuthentication" && secondEntry.OptionValue.Value == "no") { + t.Errorf("Expected second entry to be 'PasswordAuthentication no', but got: %v", secondEntry.Value) + } + + rawThirdEntry, _ := p.Options.Get(uint32(118)) + thirdEntry := rawThirdEntry.(*SSHOption) + if !(thirdEntry.Key.Value == "Subsystem" && thirdEntry.OptionValue.Value == "sftp\tinternal-sftp") { + t.Errorf("Expected third entry to be 'Subsystem sftp internal-sftp', but got: %v", thirdEntry.Value) + } + + rawFourthEntry, _ := p.Options.Get(uint32(135)) + fourthEntry := rawFourthEntry.(*SSHMatchBlock) + if !(fourthEntry.MatchEntry.Value == "Match User anoncvs") { + t.Errorf("Expected fourth entry to be 'Match User anoncvs', but got: %v", fourthEntry.MatchEntry.Value) + } + + if !(fourthEntry.Options.Size() == 3) { + t.Errorf("Expected 3 options in fourth match block, but got: %v", fourthEntry.Options) + } + + rawFifthEntry, _ := fourthEntry.Options.Get(uint32(136)) + fifthEntry := rawFifthEntry.(*SSHOption) + if !(fifthEntry.Key.Value == "X11Forwarding" && fifthEntry.OptionValue.Value == "no") { + t.Errorf("Expected fifth entry to be 'X11Forwarding no', but got: %v", fifthEntry.Value) + } + + rawSixthEntry, _ := p.Options.Get(uint32(142)) + sixthEntry := rawSixthEntry.(*SSHMatchBlock) + if !(sixthEntry.MatchEntry.Value == "Match Address 172.22.100.0/24,172.22.5.0/24,127.0.0.1") { + t.Errorf("Expected sixth entry to be 'Match Address 172.22.100.0/24,172.22.5.0/24,127.0.0.1', but got: %v", sixthEntry.MatchEntry.Value) + } + + if !(sixthEntry.MatchEntry.Key.Value == "Match" && sixthEntry.MatchEntry.OptionValue.Value == "Address 172.22.100.0/24,172.22.5.0/24,127.0.0.1") { + t.Errorf("Expected sixth entry to be 'Match Address 172.22.100.0/24,172.22.5.0/24,127.0.0.1', but got: %v", sixthEntry.MatchEntry.Value) + } + + if !(sixthEntry.Options.Size() == 2) { + t.Errorf("Expected 2 options in sixth match block, but got: %v", sixthEntry.Options) + } + + rawSeventhEntry, _ := sixthEntry.Options.Get(uint32(143)) + seventhEntry := rawSeventhEntry.(*SSHOption) + if !(seventhEntry.Key.Value == "PermitRootLogin" && seventhEntry.OptionValue.Value == "without-password") { + t.Errorf("Expected seventh entry to be 'PermitRootLogin without-password', but got: %v", seventhEntry.Value) + } +} From e31e91f643b7931a9197e8f1f22084c7d7aa1b98 Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Tue, 10 Sep 2024 22:39:19 +0200 Subject: [PATCH 010/133] feat(sshd_config): Add fields --- handlers/sshd_config/fields/fields.go | 963 ++++++++++++++++++ handlers/sshd_config/fields/utils.go | 96 ++ .../fields/value-data-amount-value.go | 97 ++ .../sshd_config/fields/value-time-format.go | 111 ++ 4 files changed, 1267 insertions(+) create mode 100644 handlers/sshd_config/fields/fields.go create mode 100644 handlers/sshd_config/fields/utils.go create mode 100644 handlers/sshd_config/fields/value-data-amount-value.go create mode 100644 handlers/sshd_config/fields/value-time-format.go diff --git a/handlers/sshd_config/fields/fields.go b/handlers/sshd_config/fields/fields.go new file mode 100644 index 0000000..c75c8de --- /dev/null +++ b/handlers/sshd_config/fields/fields.go @@ -0,0 +1,963 @@ +package fields + +import ( + docvalues "config-lsp/doc-values" + "regexp" +) + +var ZERO = 0 +var MAX_PORT = 65535 +var MAX_FILE_MODE = 0777 + +var Options = map[string]docvalues.Value{ + "AcceptEnv": docvalues.DocumentationValue{ + Documentation: `Specifies what environment variables sent by the client will be copied into the session's environ(7). See SendEnv and SetEnv in ssh_config(5) for how to configure the client. The TERM environment variable is always accepted whenever the client requests a pseudo-terminal as it is required by the protocol. Variables are specified by name, which may contain the wildcard characters ‘*’ and ‘?’. Multiple environment variables may be separated by whitespace or spread across multiple AcceptEnv directives. Be warned that some environment variables could be used to bypass restricted user environments. For this reason, care should be taken in the use of this directive. The default is not to accept any environment variables.`, + Value: docvalues.StringValue{}, + }, + "AddressFamily": docvalues.DocumentationValue{ + Documentation: `Specifies which address family should be used by sshd(8). Valid arguments are any (the default), inet (use IPv4 only), or inet6 (use IPv6 only).`, + Value: docvalues.EnumValue{ + EnforceValues: true, + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("any"), + docvalues.CreateEnumString("inet"), + docvalues.CreateEnumString("inet6"), + }, + }, + }, + "AllowAgentForwarding": docvalues.DocumentationValue{ + Documentation: `Specifies whether ssh-agent(1) forwarding is permitted. The default is yes. Note that disabling agent forwarding does not improve security unless users are also denied shell access, as they can always install their own forwarders.`, + Value: booleanEnumValue, + }, + "AllowGroups": docvalues.DocumentationValue{ + Documentation: `This keyword can be followed by a list of group name patterns, separated by spaces. If specified, login is allowed only for users whose primary group or supplementary group list matches one of the patterns. Only group names are valid; a numerical group ID is not recognized. By default, login is allowed for all groups. The allow/deny groups directives are processed in the following order: DenyGroups, AllowGroups. + +See PATTERNS in ssh_config(5) for more information on patterns. This keyword may appear multiple times in sshd_config with each instance appending to the list.`, +Value: docvalues.GroupValue(" ", false), + }, + "AllowStreamLocalForwarding": docvalues.DocumentationValue{ + Documentation: `Specifies whether StreamLocal (Unix-domain socket) forwarding is permitted. The available options are yes (the default) or all to allow StreamLocal forwarding, no to prevent all StreamLocal forwarding, local to allow local (from the perspective of ssh(1)) forwarding only or remote to allow remote forwarding only. Note that disabling StreamLocal forwarding does not improve security unless users are also denied shell access, as they can always install their own forwarders.`, + Value: docvalues.EnumValue{ + EnforceValues: true, + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("yes"), + docvalues.CreateEnumString("all"), + docvalues.CreateEnumString("no"), + docvalues.CreateEnumString("local"), + docvalues.CreateEnumString("remote"), + }, + }, + }, + "AllowTcpForwarding": docvalues.DocumentationValue{ + Documentation: `Specifies whether TCP forwarding is permitted. The available options are yes (the default) or all to allow TCP forwarding, no to prevent all TCP forwarding, local to allow local (from the perspective of ssh(1)) forwarding only or remote to allow remote forwarding only. Note that disabling TCP forwarding does not improve security unless users are also denied shell access, as they can always install their own forwarders.`, + Value: docvalues.EnumValue{ + EnforceValues: true, + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("yes"), + docvalues.CreateEnumString("all"), + docvalues.CreateEnumString("no"), + docvalues.CreateEnumString("local"), + docvalues.CreateEnumString("remote"), + }, + }, + }, + "AllowUsers": docvalues.DocumentationValue{ + Documentation: `This keyword can be followed by a list of user name patterns, separated by spaces. If specified, login is allowed only for user names that match one of the patterns. Only user names are valid; a numerical user ID is not recognized. By default, login is allowed for all users. If the pattern takes the form USER@HOST then USER and HOST are separately checked, restricting logins to particular users from particular hosts. HOST criteria may additionally contain addresses to match in CIDR address/masklen format. The allow/deny users directives are processed in the following order: DenyUsers, AllowUsers. + See PATTERNS in ssh_config(5) for more information on patterns. This keyword may appear multiple times in sshd_config with each instance appending to the list.`, + Value: docvalues.UserValue(" ", false), + }, + "AuthenticationMethods": docvalues.DocumentationValue{ + Documentation: `Specifies the authentication methods that must be successfully completed for a user to be granted access. This option must be followed by one or more lists of comma-separated authentication method names, or by the single string any to indicate the default behaviour of accepting any single authentication method. If the default is overridden, then successful authentication requires completion of every method in at least one of these lists. + For example, "publickey,password publickey,keyboard-interactive" would require the user to complete public key authentication, followed by either password or keyboard interactive authentication. Only methods that are next in one or more lists are offered at each stage, so for this example it would not be possible to attempt password or keyboard-interactive authentication before public key. + For keyboard interactive authentication it is also possible to restrict authentication to a specific device by appending a colon followed by the device identifier bsdauth or pam. depending on the server configuration. For example, "keyboard-interactive:bsdauth" would restrict keyboard interactive authentication to the bsdauth device. + If the publickey method is listed more than once, sshd(8) verifies that keys that have been used successfully are not reused for subsequent authentications. For example, "publickey,publickey" requires successful authentication using two different public keys.PATTERNS + Note that each authentication method listed should also be explicitly enabled in the configuration. + The available authentication methods are: "gssapi-with-mic", "hostbased", "keyboard-interactive", "none" (used for access to password-less accounts when PermitEmptyPasswords is enabled), "password" and "publickey".`, + Value: docvalues.OrValue{ + Values: []docvalues.Value{ + docvalues.EnumValue{ + EnforceValues: true, + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("any"), + }, + }, + docvalues.ArrayValue{ + SubValue: docvalues.EnumValue{ + EnforceValues: true, + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("none"), + + docvalues.CreateEnumString("password"), + docvalues.CreateEnumString("publickey"), + docvalues.CreateEnumString("gssapi-with-mic"), + docvalues.CreateEnumString("keyboard-interactive"), + docvalues.CreateEnumString("hostbased"), + + docvalues.CreateEnumString("password:bsdauth"), + docvalues.CreateEnumString("publickey:bsdauth"), + docvalues.CreateEnumString("gssapi-with-mic:bsdauth"), + docvalues.CreateEnumString("keyboard-interactive:bsdauth"), + docvalues.CreateEnumString("hostbased:bsdauth"), + + docvalues.CreateEnumString("password:pam"), + docvalues.CreateEnumString("publickey:pam"), + docvalues.CreateEnumString("gssapi-with-mic:pam"), + docvalues.CreateEnumString("keyboard-interactive:pam"), + docvalues.CreateEnumString("hostbased:pam"), + }, + }, + }, + }, + }, + }, + "AuthorizedKeysCommand": docvalues.DocumentationValue{ + Documentation: `Specifies a program to be used to look up the user's public keys. The program must be owned by root, not writable by group or others and specified by an absolute path. Arguments to AuthorizedKeysCommand accept the tokens described in the “TOKENS” section. If no arguments are specified then the username of the target user is used. + The program should produce on standard output zero or more lines of authorized_keys output (see “AUTHORIZED_KEYS” in sshd(8)). AuthorizedKeysCommand is tried after the usual AuthorizedKeysFile files and will not be executed if a matching key is found there. By default, no AuthorizedKeysCommand is run.`, + Value: docvalues.StringValue{}, + }, + + "AuthorizedKeysCommandUser": docvalues.DocumentationValue{ + Documentation: `Specifies the user under whose account the AuthorizedKeysCommand is run. It is recommended to use a dedicated user that has no other role on the host than running authorized keys commands. If AuthorizedKeysCommand is specified but AuthorizedKeysCommandUser is not, then sshd(8) will refuse to start.`, + Value: docvalues.UserValue("", true), + }, + "AuthorizedKeysFile": docvalues.DocumentationValue{ + Documentation: `Specifies the file that contains the public keys used for user authentication. The format is described in the AUTHORIZED_KEYS FILE FORMAT section of sshd(8). Arguments to AuthorizedKeysFile accept the tokens described in the “TOKENS” section. After expansion, AuthorizedKeysFile is taken to be an absolute path or one relative to the user's home directory. Multiple files may be listed, separated by whitespace. Alternately this option may be set to none to skip checking for user keys in files. The default is ".ssh/authorized_keys .ssh/authorized_keys2".`, + Value: docvalues.ArrayValue{ + SubValue: docvalues.StringValue{}, + Separator: " ", + DuplicatesExtractor: &docvalues.DuplicatesAllowedExtractor, + }, + }, + "AuthorizedPrincipalsCommand": docvalues.DocumentationValue{ + Documentation: `Specifies a program to be used to generate the list of allowed certificate principals as per AuthorizedPrincipalsFile. The program must be owned by root, not writable by group or others and specified by an absolute path. Arguments to AuthorizedPrincipalsCommand accept the tokens described in the “TOKENS” section. If no arguments are specified then the username of the target user is used. + The program should produce on standard output zero or more lines of AuthorizedPrincipalsFile output. If either AuthorizedPrincipalsCommand or AuthorizedPrincipalsFile is specified, then certificates offered by the client for authentication must contain a principal that is listed. By default, no AuthorizedPrincipalsCommand is run.`, + Value: docvalues.StringValue{}, + }, + "AuthorizedPrincipalsCommandUser": docvalues.DocumentationValue{ + Documentation: `Specifies the user under whose account the AuthorizedPrincipalsCommand is run. It is recommended to use a dedicated user that has no other role on the host than running authorized principals commands. If AuthorizedPrincipalsCommand is specified but AuthorizedPrincipalsCommandUser is not, then sshd(8) will refuse to start.`, + Value: docvalues.UserValue("", true), + }, + "AuthorizedPrincipalsFile": docvalues.DocumentationValue{ + Documentation: `Specifies a file that lists principal names that are accepted for certificate authentication. When using certificates signed by a key listed in TrustedUserCAKeys, this file lists names, one of which must appear in the certificate for it to be accepted for authentication. Names are listed one per line preceded by key options (as described in “AUTHORIZED_KEYS FILE FORMAT” in sshd(8)). Empty lines and comments starting with ‘#’ are ignored. + Arguments to AuthorizedPrincipalsFile accept the tokens described in the “TOKENS” section. After expansion, AuthorizedPrincipalsFile is taken to be an absolute path or one relative to the user's home directory. The default is none, i.e. not to use a principals file – in this case, the username of the user must appear in a certificate's principals list for it to be accepted. + Note that AuthorizedPrincipalsFile is only used when authentication proceeds using a CA listed in TrustedUserCAKeys and is not consulted for certification authorities trusted via ~/.ssh/authorized_keys, though the principals= key option offers a similar facility (see sshd(8) for details).`, + Value: docvalues.PathValue{ + RequiredType: docvalues.PathTypeFile, + }, + }, + "Banner": docvalues.DocumentationValue{ + Documentation: `The contents of the specified file are sent to the remote user before authentication is allowed. If the argument is none then no banner is displayed. By default, no banner is displayed.`, + Value: docvalues.PathValue{ + RequiredType: docvalues.PathTypeFile, + }, + }, + "CASignatureAlgorithms": docvalues.DocumentationValue{ + Documentation: `Specifies which algorithms are allowed for signing of certificates by certificate authorities (CAs). The default is: + ssh-ed25519,ecdsa-sha2-nistp256, ecdsa-sha2-nistp384,ecdsa-sha2-nistp521, sk-ssh-ed25519@openssh.com, sk-ecdsa-sha2-nistp256@openssh.com, rsa-sha2-512,rsa-sha2-256 + If the specified list begins with a ‘+’ character, then the specified algorithms will be appended to the default set instead of replacing them. If the specified list begins with a ‘-’ character, then the specified algorithms (including wildcards) will be removed from the default set instead of replacing them. + Certificates signed using other algorithms will not be accepted for public key or host-based authentication.`, + Value: docvalues.PrefixWithMeaningValue{ + Prefixes: []docvalues.Prefix{ + { + Prefix: "+", + Meaning: "Appende to the default set", + }, + { + Prefix: "-", + Meaning: "Remove from the default set", + }, + }, + SubValue: docvalues.ArrayValue{ + Separator: ",", + DuplicatesExtractor: &docvalues.DuplicatesAllowedExtractor, + // TODO: Add + SubValue: docvalues.StringValue{}, + }, + }, + }, + "ChannelTimeout": docvalues.DocumentationValue{ + Documentation: `Specifies whether and how quickly sshd(8) should close inactive channels. Timeouts are specified as one or more “type=interval” pairs separated by whitespace, where the “type” must be the special keyword “global” or a channel type name from the list below, optionally containing wildcard characters. + The timeout value “interval” is specified in seconds or may use any of the units documented in the “TIME FORMATS” section. For example, “session=5m” would cause interactive sessions to terminate after five minutes of inactivity. Specifying a zero value disables the inactivity timeout. + The special timeout “global” applies to all active channels, taken together. Traffic on any active channel will reset the timeout, but when the timeout expires then all open channels will be closed. Note that this global timeout is not matched by wildcards and must be specified explicitly. + The available channel type names include: + + agent-connection Open connections to ssh-agent(1). + direct-tcpip, direct-streamlocal@openssh.com Open TCP or Unix socket (respectively) connections that have been established from a ssh(1) local forwarding, i.e. LocalForward or DynamicForward. + forwarded-tcpip, forwarded-streamlocal@openssh.com Open TCP or Unix socket (respectively) connections that have been established to a sshd(8) listening on behalf of a ssh(1) remote forwarding, i.e. RemoteForward. + session The interactive main session, including shell session, command execution, scp(1), sftp(1), etc. + tun-connection Open TunnelForward connections. + x11-connection Open X11 forwarding sessions. + + Note that in all the above cases, terminating an inactive session does not guarantee to remove all resources associated with the session, e.g. shell processes or X11 clients relating to the session may continue to execute. + Moreover, terminating an inactive channel or session does not necessarily close the SSH connection, nor does it prevent a client from requesting another channel of the same type. In particular, expiring an inactive forwarding session does not prevent another identical forwarding from being subsequently created. + The default is not to expire channels of any type for inactivity.`, + Value: docvalues.ArrayValue{ + Separator: " ", + DuplicatesExtractor: &channelTimeoutExtractor, + SubValue: docvalues.KeyValueAssignmentValue{ + ValueIsOptional: false, + Separator: "=", + Key: docvalues.EnumValue{ + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("global"), + docvalues.CreateEnumString("agent-connection"), + docvalues.CreateEnumString("direct-tcpip"), + docvalues.CreateEnumString("direct-streamlocal@openssh.com"), + docvalues.CreateEnumString("forwarded-tcpip"), + docvalues.CreateEnumString("forwarded-streamlocal@openssh.com"), + docvalues.CreateEnumString("session"), + docvalues.CreateEnumString("tun-connection"), + docvalues.CreateEnumString("x11-connection"), + }, + }, + Value: TimeFormatValue{}, + }, + }, + }, + "ChrootDirectory": docvalues.DocumentationValue{ + Documentation: `Specifies the pathname of a directory to chroot(2) to after authentication. At session startup sshd(8) checks that all components of the pathname are root-owned directories which are not writable by group or others. After the chroot, sshd(8) changes the working directory to the user's home directory. Arguments to ChrootDirectory accept the tokens described in the “TOKENS” section. + The ChrootDirectory must contain the necessary files and directories to support the user's session. For an interactive session this requires at least a shell, typically sh(1), and basic /dev nodes such as null(4), zero(4), stdin(4), stdout(4), stderr(4), and tty(4) devices. For file transfer sessions using SFTP no additional configuration of the environment is necessary if the in-process sftp-server is used, though sessions which use logging may require /dev/log inside the chroot directory on some operating systems (see sftp-server(8) for details). + For safety, it is very important that the directory hierarchy be prevented from modification by other processes on the system (especially those outside the jail). Misconfiguration can lead to unsafe environments which sshd(8) cannot detect. + The default is none, indicating not to chroot(2).`, + Value: docvalues.StringValue{}, + }, + "Ciphers": docvalues.DocumentationValue{ + Documentation: `Specifies the ciphers allowed. Multiple ciphers must be comma-separated. If the specified list begins with a ‘+’ character, then the specified ciphers will be appended to the default set instead of replacing them. If the specified list begins with a ‘-’ character, then the specified ciphers (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a ‘^’ character, then the specified ciphers will be placed at the head of the default set. + The supported ciphers are: + 3des-cbc aes128-cbc aes192-cbc aes256-cbc aes128-ctr aes192-ctr aes256-ctr aes128-gcm@openssh.com aes256-gcm@openssh.com chacha20-poly1305@openssh.com + The default is: + chacha20-poly1305@openssh.com, aes128-ctr,aes192-ctr,aes256-ctr, aes128-gcm@openssh.com,aes256-gcm@openssh.com + The list of available ciphers may also be obtained using "ssh -Q cipher".`, + Value: prefixPlusMinusCaret([]docvalues.EnumString{ + docvalues.CreateEnumString("3des-cbc"), + docvalues.CreateEnumString("aes128-cbc"), + docvalues.CreateEnumString("aes192-cbc"), + docvalues.CreateEnumString("aes256-cbc"), + docvalues.CreateEnumString("aes128-ctr"), + docvalues.CreateEnumString("aes192-ctr"), + docvalues.CreateEnumString("aes256-ctr"), + docvalues.CreateEnumString("aes128-gcm@openssh.com"), + docvalues.CreateEnumString("aes256-gcm@openssh.com"), + docvalues.CreateEnumString("chacha20-poly1305@openssh.com"), + }), + }, + "ClientAliveCountMax": docvalues.DocumentationValue{ + Documentation: `Sets the number of client alive messages which may be sent without sshd(8) receiving any messages back from the client. If this threshold is reached while client alive messages are being sent, sshd will disconnect the client, terminating the session. It is important to note that the use of client alive messages is very different from TCPKeepAlive. The client alive messages are sent through the encrypted channel and therefore will not be spoofable. The TCP keepalive option enabled by TCPKeepAlive is spoofable. The client alive mechanism is valuable when the client or server depend on knowing when a connection has become unresponsive. + The default value is 3. If ClientAliveInterval is set to 15, and ClientAliveCountMax is left at the default, unresponsive SSH clients will be disconnected after approximately 45 seconds. Setting a zero ClientAliveCountMax disables connection termination.`, + Value: docvalues.NumberValue{Min: &ZERO}, + }, + "ClientAliveInterval": docvalues.DocumentationValue{ + Documentation: `Sets a timeout interval in seconds after which if no data has been received from the client, sshd(8) will send a message through the encrypted channel to request a response from the client. The default is 0, indicating that these messages will not be sent to the client.`, + Value: docvalues.NumberValue{Min: &ZERO}, + }, + "Compression": docvalues.DocumentationValue{ + Documentation: `Specifies whether compression is enabled after the user has authenticated successfully. The argument must be yes, delayed (a legacy synonym for yes) or no. The default is yes.`, + Value: docvalues.EnumValue{ + EnforceValues: true, + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("yes"), + docvalues.CreateEnumString("delayed"), + docvalues.CreateEnumString("no"), + }, + }, + }, + "DenyGroups": docvalues.DocumentationValue{ + Documentation: `This keyword can be followed by a list of group name patterns, separated by spaces. Login is disallowed for users whose primary group or supplementary group list matches one of the patterns. Only group names are valid; a numerical group ID is not recognized. By default, login is allowed for all groups. The allow/deny groups directives are processed in the following order: DenyGroups, AllowGroups. + See PATTERNS in ssh_config(5) for more information on patterns. This keyword may appear multiple times in sshd_config with each instance appending to the list.`, + Value: docvalues.GroupValue(" ", false), + }, + "DenyUsers": docvalues.DocumentationValue{ + Documentation: `This keyword can be followed by a list of user name patterns, separated by spaces. Login is disallowed for user names that match one of the patterns. Only user names are valid; a numerical user ID is not recognized. By default, login is allowed for all users. If the pattern takes the form USER@HOST then USER and HOST are separately checked, restricting logins to particular users from particular hosts. HOST criteria may additionally contain addresses to match in CIDR address/masklen format. The allow/deny users directives are processed in the following order: DenyUsers, AllowUsers. + See PATTERNS in ssh_config(5) for more information on patterns. This keyword may appear multiple times in sshd_config with each instance appending to the list.`, + Value: docvalues.UserValue(" ", false), + }, + "DisableForwarding": docvalues.DocumentationValue{ + Documentation: `Disables all forwarding features, including X11, ssh-agent(1), TCP and StreamLocal. This option overrides all other forwarding-related options and may simplify restricted configurations.`, + Value: booleanEnumValue, + }, + "ExposeAuthInfo": docvalues.DocumentationValue{ + Documentation: `Writes a temporary file containing a list of authentication methods and public credentials (e.g. keys) used to authenticate the user. The location of the file is exposed to the user session through the SSH_USER_AUTH environment variable. The default is no.`, + Value: booleanEnumValue, + }, + "FingerprintHash": docvalues.DocumentationValue{ + Documentation: `Specifies the hash algorithm used when logging key fingerprints. Valid options are: md5 and sha256. The default is sha256.`, + Value: docvalues.EnumValue{ + EnforceValues: true, + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("md5"), + docvalues.CreateEnumString("sha256"), + }, + }, + }, + "ForceCommand": docvalues.DocumentationValue{ + Documentation: `Forces the execution of the command specified by ForceCommand, ignoring any command supplied by the client and ~/.ssh/rc if present. The command is invoked by using the user's login shell with the -c option. This applies to shell, command, or subsystem execution. It is most useful inside a Match block. The command originally supplied by the client is available in the SSH_ORIGINAL_COMMAND environment variable. Specifying a command of internal-sftp will force the use of an in- process SFTP server that requires no support files when used with ChrootDirectory. The default is none.`, + Value: docvalues.StringValue{}, + }, + "GatewayPorts": docvalues.DocumentationValue{ + Documentation: `Specifies whether remote hosts are allowed to connect to ports forwarded for the client. By default, sshd(8) binds remote port forwardings to the loopback address. This prevents other remote hosts from connecting to forwarded ports. GatewayPorts can be used to specify that sshd should allow remote port forwardings to bind to non-loopback addresses, thus allowing other hosts to connect. The argument may be no to force remote port forwardings to be available to the local host only, yes to force remote port forwardings to bind to the wildcard address, or clientspecified to allow the client to select the address to which the forwarding is bound. The default is no.`, + Value: booleanEnumValue, + }, + "GSSAPIAuthentication": docvalues.DocumentationValue{ + Documentation: `Specifies whether user authentication based on GSSAPI is allowed. The default is no.`, + Value: booleanEnumValue, + }, + "GSSAPICleanupCredentials": docvalues.DocumentationValue{ + Documentation: `Specifies whether to automatically destroy the user's credentials cache on logout. The default is yes.`, + Value: booleanEnumValue, + }, + "GSSAPIStrictAcceptorCheck": docvalues.DocumentationValue{ + Documentation: `Determines whether to be strict about the identity of the GSSAPI acceptor a client authenticates against. If set to yes then the client must authenticate against the host service on the current hostname. If set to no then the client may authenticate against any service key stored in the machine's default store. This facility is provided to assist with operation on multi homed machines. The default is yes.`, + Value: booleanEnumValue, + }, + "HostbasedAcceptedAlgorithms": docvalues.DocumentationValue{ + Documentation: `Specifies the signature algorithms that will be accepted for hostbased authentication as a list of comma-separated patterns. Alternately if the specified list begins with a ‘+’ character, then the specified signature algorithms will be appended to the default set instead of replacing them. If the specified list begins with a ‘-’ character, then the specified signature algorithms (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a ‘^’ character, then the specified signature algorithms will be placed at the head of the default set. The default for this option is: + ssh-ed25519-cert-v01@openssh.com, ecdsa-sha2-nistp256-cert-v01@openssh.com, ecdsa-sha2-nistp384-cert-v01@openssh.com, ecdsa-sha2-nistp521-cert-v01@openssh.com, sk-ssh-ed25519-cert-v01@openssh.com, sk-ecdsa-sha2-nistp256-cert-v01@openssh.com, rsa-sha2-512-cert-v01@openssh.com, rsa-sha2-256-cert-v01@openssh.com, ssh-ed25519, ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521, sk-ssh-ed25519@openssh.com, sk-ecdsa-sha2-nistp256@openssh.com, rsa-sha2-512,rsa-sha2-256 + The list of available signature algorithms may also be obtained using "ssh -Q HostbasedAcceptedAlgorithms". This was formerly named HostbasedAcceptedKeyTypes.`, + Value: docvalues.CustomValue{ + FetchValue: func(_ docvalues.CustomValueContext) docvalues.Value { + options, err := queryOpenSSHOptions("HostbasedAcceptedAlgorithms") + + if err != nil { + // Fallback + options, _ = queryOpenSSHOptions("HostbasedAcceptedKeyTypes") + } + + return prefixPlusMinusCaret(options) + }, + }, + }, + "HostbasedAuthentication": docvalues.DocumentationValue{ + Documentation: `Specifies whether rhosts or /etc/hosts.equiv authentication together with successful public key client host authentication is allowed (host-based authentication). The default is no.`, + Value: booleanEnumValue, + }, + "HostbasedUsesNameFromPacketOnly": docvalues.DocumentationValue{ + Documentation: `Specifies whether or not the server will attempt to perform a reverse name lookup when matching the name in the ~/.shosts, ~/.rhosts, and /etc/hosts.equiv files during HostbasedAuthentication. A setting of yes means that sshd(8) uses the name supplied by the client rather than attempting to resolve the name from the TCP connection itself. The default is no.`, + Value: booleanEnumValue, + }, + "HostCertificate": docvalues.DocumentationValue{ + Documentation: `Specifies a file containing a public host certificate. The certificate's public key must match a private host key already specified by HostKey. The default behaviour of sshd(8) is not to load any certificates.`, + Value: docvalues.PathValue{}, + }, + "HostKey": docvalues.DocumentationValue{ + Documentation: `Specifies a file containing a private host key used by SSH. The defaults are /etc/ssh/ssh_host_ecdsa_key, /etc/ssh/ssh_host_ed25519_key and /etc/ssh/ssh_host_rsa_key. + Note that sshd(8) will refuse to use a file if it is group/world-accessible and that the HostKeyAlgorithms option restricts which of the keys are actually used by sshd(8). + It is possible to have multiple host key files. It is also possible to specify public host key files instead. In this case operations on the private key will be delegated to an ssh-agent(1).`, + Value: docvalues.PathValue{}, + }, + "HostKeyAgent": docvalues.DocumentationValue{ + Documentation: `Identifies the UNIX-domain socket used to communicate with an agent that has access to the private host keys. If the string "SSH_AUTH_SOCK" is specified, the location of the socket will be read from the SSH_AUTH_SOCK environment variable.`, + Value: docvalues.OrValue{ + Values: []docvalues.Value{ + docvalues.EnumValue{ + EnforceValues: true, + Values: []docvalues.EnumString{ + docvalues.CreateEnumStringWithDoc("SSH_AUTH_SOCK", "The location of the socket will be read from the SSH_AUTH_SOCK environment variable."), + }, + }, + docvalues.StringValue{}, + }, + }, + }, + "HostKeyAlgorithms": docvalues.DocumentationValue{ + Documentation: `Specifies the host key signature algorithms that the server offers. The default for this option is: + ssh-ed25519-cert-v01@openssh.com, ecdsa-sha2-nistp256-cert-v01@openssh.com, ecdsa-sha2-nistp384-cert-v01@openssh.com, ecdsa-sha2-nistp521-cert-v01@openssh.com, sk-ssh-ed25519-cert-v01@openssh.com, sk-ecdsa-sha2-nistp256-cert-v01@openssh.com, rsa-sha2-512-cert-v01@openssh.com, rsa-sha2-256-cert-v01@openssh.com, ssh-ed25519, ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521, sk-ssh-ed25519@openssh.com, sk-ecdsa-sha2-nistp256@openssh.com, rsa-sha2-512,rsa-sha2-256 + The list of available signature algorithms may also be obtained using "ssh -Q HostKeyAlgorithms".`, + Value: docvalues.CustomValue{ + FetchValue: func(_ docvalues.CustomValueContext) docvalues.Value { + options, _ := queryOpenSSHOptions("HostKeyAlgorithms") + + return prefixPlusMinusCaret(options) + }, + }, + }, + "IgnoreRhosts": docvalues.DocumentationValue{ + Documentation: `Specifies whether to ignore per-user .rhosts and .shosts files during HostbasedAuthentication. The system-wide /etc/hosts.equiv and /etc/shosts.equiv are still used regardless of this setting. + Accepted values are yes (the default) to ignore all per- user files, shosts-only to allow the use of .shosts but to ignore .rhosts or no to allow both .shosts and rhosts.`, + Value: docvalues.EnumValue{ + EnforceValues: true, + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("yes"), + docvalues.CreateEnumString("shosts-only"), + docvalues.CreateEnumString("no"), + }, + }, + }, + "IgnoreUserKnownHosts": docvalues.DocumentationValue{ + Documentation: `Specifies whether sshd(8) should ignore the user's ~/.ssh/known_hosts during HostbasedAuthentication and use only the system-wide known hosts file /etc/ssh/ssh_known_hosts. The default is “no”.`, + Value: booleanEnumValue, + }, + "Include": docvalues.DocumentationValue{ + Documentation: `Include the specified configuration file(s). Multiple pathnames may be specified and each pathname may contain glob(7) wildcards that will be expanded and processed in lexical order. Files without absolute paths are assumed to be in /etc/ssh. An Include directive may appear inside a Match block to perform conditional inclusion.`, + Value: docvalues.ArrayValue{ + Separator: " ", + DuplicatesExtractor: &docvalues.SimpleDuplicatesExtractor, + SubValue: docvalues.PathValue{ + RequiredType: docvalues.PathTypeFile, + }, + }, + // TODO: Add extra check + }, + + "IPQoS": docvalues.DocumentationValue{ + Documentation: `Specifies the IPv4 type-of-service or DSCP class for the connection. Accepted values are af11, af12, af13, af21, af22, af23, af31, af32, af33, af41, af42, af43, cs0, cs1, cs2, cs3, cs4, cs5, cs6, cs7, ef, le, lowdelay, throughput, reliability, a numeric value, or none to use the operating system default. This option may take one or two arguments, separated by whitespace. If one argument is specified, it is used as the packet class unconditionally. If two values are specified, the first is automatically selected for interactive sessions and the second for non-interactive sessions. The default is af21 (Low-Latency Data) for interactive sessions and cs1 (Lower Effort) for non-interactive sessions.`, + Value: docvalues.OrValue{ + Values: []docvalues.Value{ + docvalues.NumberValue{}, + docvalues.EnumValue{ + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("none"), + }, + }, + docvalues.ArrayValue{ + Separator: " ", + SubValue: docvalues.EnumValue{ + EnforceValues: true, + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("af11"), + docvalues.CreateEnumString("af12"), + docvalues.CreateEnumString("af13"), + docvalues.CreateEnumString("af21"), + docvalues.CreateEnumString("af22"), + docvalues.CreateEnumString("af23"), + docvalues.CreateEnumString("af31"), + docvalues.CreateEnumString("af32"), + docvalues.CreateEnumString("af33"), + docvalues.CreateEnumString("af41"), + docvalues.CreateEnumString("af42"), + docvalues.CreateEnumString("af43"), + docvalues.CreateEnumString("cs0"), + docvalues.CreateEnumString("cs1"), + docvalues.CreateEnumString("cs2"), + docvalues.CreateEnumString("cs3"), + docvalues.CreateEnumString("cs4"), + docvalues.CreateEnumString("cs5"), + docvalues.CreateEnumString("cs6"), + docvalues.CreateEnumString("cs7"), + docvalues.CreateEnumString("ef"), + docvalues.CreateEnumString("le"), + docvalues.CreateEnumString("lowdelay"), + docvalues.CreateEnumString("throughput"), + docvalues.CreateEnumString("reliability"), + docvalues.CreateEnumString("none"), + }, + }, + }, + }, + }, + }, + "KbdInteractiveAuthentication": docvalues.DocumentationValue{ + Documentation: `Specifies whether to allow keyboard-interactive authentication. All authentication styles from login.conf(5) are supported. The default is yes. The argument to this keyword must be yes or no. ChallengeResponseAuthentication is a deprecated alias for this.`, + Value: booleanEnumValue, + }, + "KerberosAuthentication": docvalues.DocumentationValue{ + Documentation: `Specifies whether the password provided by the user for PasswordAuthentication will be validated through the Kerberos KDC. To use this option, the server needs a Kerberos servtab which allows the verification of the KDC's identity. The default is no.`, + Value: booleanEnumValue, + }, + "KerberosGetAFSToken": docvalues.DocumentationValue{ + Documentation: `If AFS is active and the user has a Kerberos 5 TGT, attempt to acquire an AFS token before accessing the user's home directory. The default is no.`, + Value: booleanEnumValue, + }, + "KerberosOrLocalPasswd": docvalues.DocumentationValue{ + Documentation: `If password authentication through Kerberos fails then the password will be validated via any additional local mechanism such as /etc/passwd. The default is yes.`, + Value: booleanEnumValue, + }, + "KerberosTicketCleanup": docvalues.DocumentationValue{ + Documentation: `Specifies whether to automatically destroy the user's ticket cache file on logout. The default is yes.`, + Value: booleanEnumValue, + }, + "KexAlgorithms": docvalues.DocumentationValue{ + Documentation: `Specifies the available KEX (Key Exchange) algorithms. Multiple algorithms must be comma-separated. Alternately if the specified list begins with a ‘+’ character, then the specified algorithms will be appended to the default set instead of replacing them. If the specified list begins with a ‘-’ character, then the specified algorithms (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a ‘^’ character, then the specified algorithms will be placed at the head of the default set. The supported algorithms are: + curve25519-sha256 curve25519-sha256@libssh.org diffie-hellman-group1-sha1 diffie-hellman-group14-sha1 diffie-hellman-group14-sha256 diffie-hellman-group16-sha512 diffie-hellman-group18-sha512 diffie-hellman-group-exchange-sha1 diffie-hellman-group-exchange-sha256 ecdh-sha2-nistp256 ecdh-sha2-nistp384 ecdh-sha2-nistp521 sntrup761x25519-sha512@openssh.com + The default is: + sntrup761x25519-sha512@openssh.com, curve25519-sha256,curve25519-sha256@libssh.org, ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521, diffie-hellman-group-exchange-sha256, diffie-hellman-group16-sha512,diffie-hellman-group18-sha512, diffie-hellman-group14-sha256 + The list of available key exchange algorithms may also be obtained using "ssh -Q KexAlgorithms".`, + Value: prefixPlusMinusCaret([]docvalues.EnumString{ + docvalues.CreateEnumString("curve25519-sha256"), + docvalues.CreateEnumString("curve25519-sha256@libssh.org"), + docvalues.CreateEnumString("diffie-hellman-group1-sha1"), + docvalues.CreateEnumString("diffie-hellman-group14-sha1"), + docvalues.CreateEnumString("diffie-hellman-group14-sha256"), + docvalues.CreateEnumString("diffie-hellman-group16-sha512"), + docvalues.CreateEnumString("diffie-hellman-group18-sha512"), + docvalues.CreateEnumString("diffie-hellman-group-exchange-sha1"), + docvalues.CreateEnumString("diffie-hellman-group-exchange-sha256"), + docvalues.CreateEnumString("ecdh-sha2-nistp256"), + docvalues.CreateEnumString("ecdh-sha2-nistp384"), + docvalues.CreateEnumString("ecdh-sha2-nistp521"), + docvalues.CreateEnumString("sntrup761x25519-sha512@openssh.com"), + }), + }, + "ListenAddress": docvalues.DocumentationValue{ + Documentation: `Specifies the local addresses sshd(8) should listen on. The following forms may be used: + ListenAddress hostname|address [rdomain domain] ListenAddress hostname:port [rdomain domain] ListenAddress IPv4_address:port [rdomain domain] ListenAddress [hostname|address]:port [rdomain domain] + The optional rdomain qualifier requests sshd(8) listen in an explicit routing domain. If port is not specified, sshd will listen on the address and all Port options specified. The default is to listen on all local addresses on the current default routing domain. Multiple ListenAddress options are permitted. For more information on routing domains, see rdomain(4).`, + Value: docvalues.KeyValueAssignmentValue{ + ValueIsOptional: true, + Key: docvalues.IPAddressValue{ + AllowIPv4: true, + AllowIPv6: true, + AllowRange: false, + DisallowedIPs: &docvalues.NonRoutableNetworks, + }, + Separator: ":", + Value: docvalues.NumberValue{Min: &ZERO, Max: &MAX_PORT}, + }, + }, + "LoginGraceTime": docvalues.DocumentationValue{ + Documentation: `The server disconnects after this time if the user has not successfully logged in. If the value is 0, there is no time limit. The default is 120 seconds.`, + Value: TimeFormatValue{}, + }, + "LogLevel": docvalues.DocumentationValue{ + Documentation: `Gives the verbosity level that is used when logging messages from sshd(8). The possible values are: QUIET, FATAL, ERROR, INFO, VERBOSE, DEBUG, DEBUG1, DEBUG2, and DEBUG3. The default is INFO. DEBUG and DEBUG1 are equivalent. DEBUG2 and DEBUG3 each specify higher levels of debugging output. Logging with a DEBUG level violates the privacy of users and is not recommended.`, + Value: docvalues.EnumValue{ + EnforceValues: true, + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("QUIET"), + docvalues.CreateEnumString("FATAL"), + docvalues.CreateEnumString("ERROR"), + docvalues.CreateEnumString("INFO"), + docvalues.CreateEnumString("VERBOSE"), + docvalues.CreateEnumString("DEBUG"), + docvalues.CreateEnumString("DEBUG1"), + docvalues.CreateEnumString("DEBUG2"), + docvalues.CreateEnumString("DEBUG3"), + }, + }, + }, + "LogVerbose": docvalues.DocumentationValue{ + Documentation: `Specify one or more overrides to LogLevel. An override consists of a pattern lists that matches the source file, function and line number to force detailed logging for. For example, an override pattern of: + kex.c:*:1000,*:kex_exchange_identification():*,packet.c:* + would enable detailed logging for line 1000 of kex.c, everything in the kex_exchange_identification() function, and all code in the packet.c file. This option is intended for debugging and no overrides are enabled by default.`, + Value: docvalues.StringValue{}, + }, + + "MACs": docvalues.DocumentationValue{ + Documentation: `Specifies the available MAC (message authentication code) algorithms. The MAC algorithm is used for data integrity protection. Multiple algorithms must be comma-separated. If the specified list begins with a ‘+’ character, then the specified algorithms will be appended to the default set instead of replacing them. If the specified list begins with a ‘-’ character, then the specified algorithms (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a ‘^’ character, then the specified algorithms will be placed at the head of the default set. + The algorithms that contain "-etm" calculate the MAC after encryption (encrypt-then-mac). These are considered safer and their use recommended. The supported MACs are: + hmac-md5 hmac-md5-96 hmac-sha1 hmac-sha1-96 hmac-sha2-256 hmac-sha2-512 umac-64@openssh.com umac-128@openssh.com hmac-md5-etm@openssh.com hmac-md5-96-etm@openssh.com hmac-sha1-etm@openssh.com hmac-sha1-96-etm@openssh.com hmac-sha2-256-etm@openssh.com hmac-sha2-512-etm@openssh.com umac-64-etm@openssh.com umac-128-etm@openssh.com + The default is: + umac-64-etm@openssh.com,umac-128-etm@openssh.com, hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com, hmac-sha1-etm@openssh.com, umac-64@openssh.com,umac-128@openssh.com, hmac-sha2-256,hmac-sha2-512,hmac-sha1 + The list of available MAC algorithms may also be obtained using "ssh -Q mac".`, + Value: prefixPlusMinusCaret([]docvalues.EnumString{ + docvalues.CreateEnumString("hmac-md5"), + docvalues.CreateEnumString("hmac-md5-96"), + docvalues.CreateEnumString("hmac-sha1"), + docvalues.CreateEnumString("hmac-sha1-96"), + docvalues.CreateEnumString("hmac-sha2-256"), + docvalues.CreateEnumString("hmac-sha2-256"), + docvalues.CreateEnumString("hmac-sha2-512"), + docvalues.CreateEnumString("umac-64@openssh.com"), + docvalues.CreateEnumString("umac-128@openssh.com"), + docvalues.CreateEnumString("hmac-md5-etm@openssh.com"), + docvalues.CreateEnumString("hmac-md5-96-etm@openssh.com"), + docvalues.CreateEnumString("hmac-sha1-etm@openssh.com"), + docvalues.CreateEnumString("hmac-sha1-96-etm@openssh.com"), + docvalues.CreateEnumString("hmac-sha2-256-etm@openssh.com"), + docvalues.CreateEnumString("hmac-sha2-512-etm@openssh.com"), + docvalues.CreateEnumString("umac-64-etm@openssh.com"), + docvalues.CreateEnumString("umac-128-etm@openssh.com"), + }), + }, + + // Match Introduces a conditional block. If all of the criteria on the Match line are satisfied, the keywords on the following lines override those set in the global section of the config file, until either another Match line or the end of the file. If a keyword appears in multiple Match blocks that are satisfied, only the first instance of the keyword is applied. + // The arguments to Match are one or more criteria-pattern pairs or the single token All which matches all criteria. The available criteria are User, Group, Host, LocalAddress, LocalPort, RDomain, and Address (with RDomain representing the rdomain(4) on which the connection was received). + // The match patterns may consist of single entries or comma-separated lists and may use the wildcard and negation operators described in the “PATTERNS” section of ssh_config(5). + // The patterns in an Address criteria may additionally contain addresses to match in CIDR address/masklen format, such as 192.0.2.0/24 or 2001:db8::/32. Note that the mask length provided must be consistent with the address - it is an error to specify a mask length that is too long for the address or one with bits set in this host portion of the address. For example, 192.0.2.0/33 and 192.0.2.0/8, respectively. + // Only a subset of keywords may be used on the lines following a Match keyword. Available keywords are AcceptEnv, AllowAgentForwarding, AllowGroups, AllowStreamLocalForwarding, AllowTcpForwarding, AllowUsers, AuthenticationMethods, AuthorizedKeysCommand, AuthorizedKeysCommandUser, AuthorizedKeysFile, AuthorizedPrincipalsCommand, AuthorizedPrincipalsCommandUser, AuthorizedPrincipalsFile, Banner, CASignatureAlgorithms, ChannelTimeout, ChrootDirectory, ClientAliveCountMax, ClientAliveInterval, DenyGroups, DenyUsers, DisableForwarding, ExposeAuthInfo, ForceCommand, GatewayPorts, GSSAPIAuthentication, HostbasedAcceptedAlgorithms, HostbasedAuthentication, HostbasedUsesNameFromPacketOnly, IgnoreRhosts, Include, IPQoS, KbdInteractiveAuthentication, KerberosAuthentication, LogLevel, MaxAuthTries, MaxSessions, PasswordAuthentication, PermitEmptyPasswords, PermitListen, PermitOpen, PermitRootLogin, PermitTTY, PermitTunnel, PermitUserRC, PubkeyAcceptedAlgorithms, PubkeyAuthentication, PubkeyAuthOptions, RekeyLimit, RevokedKeys, RDomain, SetEnv, StreamLocalBindMask, StreamLocalBindUnlink, TrustedUserCAKeys, UnusedConnectionTimeout, X11DisplayOffset, X11Forwarding and X11UseLocalhost.`, + "MaxAuthTries": docvalues.DocumentationValue{ + Documentation: `Specifies the maximum number of authentication attempts permitted per connection. Once the number of failures reaches half this value, additional failures are logged. The default is 6.`, + Value: docvalues.NumberValue{Min: &ZERO}, + }, + "MaxSessions": docvalues.DocumentationValue{ + Documentation: `Specifies the maximum number of open shell, login or subsystem (e.g. sftp) sessions permitted per network connection. Multiple sessions may be established by clients that support connection multiplexing. Setting MaxSessions to 1 will effectively disable session multiplexing, whereas setting it to 0 will prevent all shell, login and subsystem sessions while still permitting forwarding. The default is 10.`, + Value: docvalues.NumberValue{Min: &ZERO}, + }, + "MaxStartups": docvalues.DocumentationValue{ + Documentation: `Specifies the maximum number of concurrent unauthenticated connections to the SSH daemon. Additional connections will be dropped until authentication succeeds or the LoginGraceTime expires for a connection. The default is 10:30:100. + Alternatively, random early drop can be enabled by specifying the three colon separated values start:rate:full (e.g. "10:30:60"). sshd(8) will refuse connection attempts with a probability of rate/100 (30%) if there are currently start (10) unauthenticated connections. The probability increases linearly and all connection attempts are refused if the number of unauthenticated connections reaches full (60).`, + // TODO: Add custom value `SeapartorValue` that takes an array of values and separators + Value: docvalues.RegexValue{ + Regex: *regexp.MustCompile(`^(\d+):(\d+):(\d+)$`), + }, + }, + "ModuliFile": docvalues.DocumentationValue{ + Documentation: `Specifies the moduli(5) file that contains the Diffie- Hellman groups used for the “diffie-hellman-group-exchange-sha1” and “diffie-hellman-group-exchange-sha256” key exchange methods. The default is /etc/moduli.`, + Value: docvalues.PathValue{ + RequiredType: docvalues.PathTypeFile, + }, + }, + "PasswordAuthentication": docvalues.DocumentationValue{ + Documentation: `Specifies whether password authentication is allowed. The default is yes.`, + Value: booleanEnumValue, + }, + "PermitEmptyPasswords": docvalues.DocumentationValue{ + Documentation: `When password authentication is allowed, it specifies whether the server allows login to accounts with empty password strings. The default is no.`, + Value: booleanEnumValue, + }, + "PermitListen": docvalues.DocumentationValue{ + Documentation: `Specifies the addresses/ports on which a remote TCP port forwarding may listen. The listen specification must be one of the following forms: + PermitListen port PermitListen host:port + Multiple permissions may be specified by separating them with whitespace. An argument of any can be used to remove all restrictions and permit any listen requests. An argument of none can be used to prohibit all listen requests. The host name may contain wildcards as described in the PATTERNS section in ssh_config(5). The wildcard ‘*’ can also be used in place of a port number to allow all ports. By default all port forwarding listen requests are permitted. Note that the GatewayPorts option may further restrict which addresses may be listened on. Note also that ssh(1) will request a listen host of “localhost” if no listen host was specifically requested, and this name is treated differently to explicit localhost addresses of “127.0.0.1” and “::1”.`, + Value: docvalues.ArrayValue{ + Separator: " ", + DuplicatesExtractor: &docvalues.SimpleDuplicatesExtractor, + SubValue: docvalues.KeyValueAssignmentValue{ + ValueIsOptional: true, + Key: docvalues.IPAddressValue{ + AllowIPv4: true, + AllowIPv6: true, + AllowRange: false, + DisallowedIPs: &docvalues.NonRoutableNetworks, + }, + Separator: ":", + Value: docvalues.OrValue{ + Values: []docvalues.Value{ + docvalues.EnumValue{ + Values: []docvalues.EnumString{ + { + InsertText: "*", + DescriptionText: "\\*", + Documentation: "Allow all ports", + }, + }, + EnforceValues: true, + }, + docvalues.NumberValue{Min: &ZERO, Max: &MAX_PORT}, + }, + }, + }, + }, + }, + "PermitOpen": docvalues.DocumentationValue{ + Documentation: `Specifies the destinations to which TCP port forwarding is permitted. The forwarding specification must be one of the following forms: + PermitOpen host:port PermitOpen IPv4_addr:port PermitOpen [IPv6_addr]:port + Multiple forwards may be specified by separating them with whitespace. An argument of any can be used to remove all restrictions and permit any forwarding requests. An argument of none can be used to prohibit all forwarding requests. The wildcard ‘*’ can be used for host or port to allow all hosts or ports respectively. Otherwise, no pattern matching or address lookups are performed on supplied names. By default all port forwarding requests are permitted.`, + Value: docvalues.ArrayValue{ + Separator: " ", + DuplicatesExtractor: &docvalues.SimpleDuplicatesExtractor, + SubValue: docvalues.KeyValueAssignmentValue{ + ValueIsOptional: true, + Key: docvalues.OrValue{ + Values: []docvalues.Value{ + docvalues.EnumValue{ + Values: []docvalues.EnumString{ + { + InsertText: "*", + DescriptionText: "\\*", + Documentation: "Allow all hosts", + }, + }, + }, + docvalues.IPAddressValue{ + AllowIPv4: true, + AllowIPv6: true, + AllowRange: false, + DisallowedIPs: &docvalues.NonRoutableNetworks, + }, + }, + }, + Separator: ":", + Value: docvalues.OrValue{ + Values: []docvalues.Value{ + docvalues.EnumValue{ + Values: []docvalues.EnumString{ + { + InsertText: "*", + DescriptionText: "\\*", + Documentation: "Allow all ports", + }, + }, + EnforceValues: true, + }, + docvalues.NumberValue{Min: &ZERO, Max: &MAX_PORT}, + }, + }, + }, + }, + }, + "PermitRootLogin": docvalues.DocumentationValue{ + Documentation: `Specifies whether root can log in using ssh(1). The argument must be yes, prohibit-password, forced-commands-only, or no. The default is prohibit-password. + If this option is set to prohibit-password (or its deprecated alias, without-password), password and keyboard-interactive authentication are disabled for root. + If this option is set to forced-commands-only, root login with public key authentication will be allowed, but only if the command option has been specified (which may be useful for taking remote backups even if root login is normally not allowed). All other authentication methods are disabled for root. + If this option is set to no, root is not allowed to log in.`, + Value: docvalues.EnumValue{ + EnforceValues: true, + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("yes"), + docvalues.CreateEnumString("prohibit-password"), + docvalues.CreateEnumString("forced-commands-only"), + docvalues.CreateEnumString("no"), + }, + }, + }, + "PermitTTY": docvalues.DocumentationValue{ + Documentation: `Specifies whether pty(4) allocation is permitted. The default is yes.`, + Value: booleanEnumValue, + }, + "PermitTunnel": docvalues.DocumentationValue{ + Documentation: `Specifies whether tun(4) device forwarding is allowed. The argument must be yes, point-to-point (layer 3), ethernet (layer 2), or no. Specifying yes permits both point-to-point and ethernet. The default is no. + Independent of this setting, the permissions of the selected tun(4) device must allow access to the user.`, + Value: docvalues.EnumValue{ + EnforceValues: true, + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("yes"), + docvalues.CreateEnumString("point-to-point"), + docvalues.CreateEnumString("ethernet"), + docvalues.CreateEnumString("no"), + }, + }, + }, + "PermitUserEnvironment": docvalues.DocumentationValue{ + Documentation: `Specifies whether ~/.ssh/environment and environment= options in ~/.ssh/authorized_keys are processed by sshd(8). Valid options are yes, no or a pattern-list specifying which environment variable names to accept (for example "LANG,LC_*"). The default is no. Enabling environment processing may enable users to bypass access restrictions in some configurations using mechanisms such as LD_PRELOAD.`, + Value: docvalues.OrValue{ + Values: []docvalues.Value{ + docvalues.EnumValue{ + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("yes"), + docvalues.CreateEnumString("no"), + }, + }, + docvalues.ArrayValue{ + SubValue: docvalues.StringValue{}, + Separator: ",", + DuplicatesExtractor: &docvalues.DuplicatesAllowedExtractor, + }, + }, + }, + }, + "PermitUserRC": docvalues.DocumentationValue{ + Documentation: `Specifies whether any ~/.ssh/rc file is executed. The default is yes.`, + Value: booleanEnumValue, + }, + "PerSourceMaxStartups": docvalues.DocumentationValue{ + Documentation: `Specifies the number of unauthenticated connections allowed from a given source address, or “none” if there is no limit. This limit is applied in addition to MaxStartups, whichever is lower. The default is none.`, + Value: docvalues.OrValue{ + Values: []docvalues.Value{ + docvalues.EnumValue{ + EnforceValues: true, + Values: []docvalues.EnumString{ + { + InsertText: "none", + DescriptionText: "none", + Documentation: "No limit", + }, + }, + }, + docvalues.NumberValue{Min: &ZERO}, + }, + }, + }, + "PerSourceNetBlockSize": docvalues.DocumentationValue{ + Documentation: `Specifies the number of bits of source address that are grouped together for the purposes of applying PerSourceMaxStartups limits. Values for IPv4 and optionally IPv6 may be specified, separated by a colon. The default is 32:128, which means each address is considered individually.`, + Value: docvalues.KeyValueAssignmentValue{ + Separator: ":", + ValueIsOptional: false, + Key: docvalues.NumberValue{Min: &ZERO}, + Value: docvalues.NumberValue{Min: &ZERO}, + }, + }, + "PidFile": docvalues.DocumentationValue{ + Documentation: `Specifies the file that contains the process ID of the SSH daemon, or none to not write one. The default is /var/run/sshd.pid.`, + Value: docvalues.StringValue{}, + }, + + "Port": docvalues.DocumentationValue{ + Documentation: `Specifies the port number that sshd(8) listens on. The default is 22. Multiple options of this type are permitted. See also ListenAddress.`, + Value: docvalues.NumberValue{Min: &ZERO, Max: &MAX_PORT}, + }, + "PrintLastLog": docvalues.DocumentationValue{ + Documentation: `Specifies whether sshd(8) should print the date and time of the last user login when a user logs in interactively. The default is yes.`, + Value: booleanEnumValue, + }, + "PrintMotd": docvalues.DocumentationValue{ + Documentation: `Specifies whether sshd(8) should print /etc/motd when a user logs in interactively. (On some systems it is also printed by the shell, /etc/profile, or equivalent.) The default is yes.`, + Value: booleanEnumValue, + }, + "PubkeyAcceptedAlgorithms": docvalues.DocumentationValue{ + Documentation: `Specifies the signature algorithms that will be accepted for public key authentication as a list of comma- separated patterns. Alternately if the specified list begins with a ‘+’ character, then the specified algorithms will be appended to the default set instead of replacing them. If the specified list begins with a ‘-’ character, then the specified algorithms (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a ‘^’ character, then the specified algorithms will be placed at the head of the default set. The default for this option is: + ssh-ed25519-cert-v01@openssh.com, ecdsa-sha2-nistp256-cert-v01@openssh.com, ecdsa-sha2-nistp384-cert-v01@openssh.com, ecdsa-sha2-nistp521-cert-v01@openssh.com, sk-ssh-ed25519-cert-v01@openssh.com, sk-ecdsa-sha2-nistp256-cert-v01@openssh.com, rsa-sha2-512-cert-v01@openssh.com, rsa-sha2-256-cert-v01@openssh.com, ssh-ed25519, ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521, sk-ssh-ed25519@openssh.com, sk-ecdsa-sha2-nistp256@openssh.com, rsa-sha2-512,rsa-sha2-256 + The list of available signature algorithms may also be obtained using "ssh -Q PubkeyAcceptedAlgorithms".`, + Value: docvalues.CustomValue{ + FetchValue: func(_ docvalues.CustomValueContext) docvalues.Value { + options, _ := queryOpenSSHOptions("PubkeyAcceptedAlgorithms") + + return prefixPlusMinusCaret(options) + }, + }, + }, + "PubkeyAuthOptions": docvalues.DocumentationValue{ + Documentation: `Sets one or more public key authentication options. The supported keywords are: none (the default; indicating no additional options are enabled), touch-required and verify-required. + The touch-required option causes public key authentication using a FIDO authenticator algorithm (i.e. ecdsa-sk or ed25519-sk) to always require the signature to attest that a physically present user explicitly confirmed the authentication (usually by touching the authenticator). By default, sshd(8) requires user presence unless overridden with an authorized_keys option. The touch-required flag disables this override. + The verify-required option requires a FIDO key signature attest that the user was verified, e.g. via a PIN. + Neither the touch-required or verify-required options have any effect for other, non-FIDO, public key types.`, + Value: docvalues.ArrayValue{ + Separator: ",", + SubValue: docvalues.EnumValue{ + EnforceValues: true, + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("none"), + docvalues.CreateEnumString("touch-required"), + docvalues.CreateEnumString("verify-required"), + }, + }, + }, + }, + "PubkeyAuthentication": docvalues.DocumentationValue{ + Documentation: `Specifies whether public key authentication is allowed. The default is yes.`, + Value: booleanEnumValue, + }, + "RekeyLimit": docvalues.DocumentationValue{ + Documentation: `Specifies the maximum amount of data that may be transmitted or received before the session key is renegotiated, optionally followed by a maximum amount of time that may pass before the session key is renegotiated. The first argument is specified in bytes and may have a suffix of ‘K’, ‘M’, or ‘G’ to indicate Kilobytes, Megabytes, or Gigabytes, respectively. The default is between ‘1G’ and ‘4G’, depending on the cipher. The optional second value is specified in seconds and may use any of the units documented in the “TIME FORMATS” section. The default value for RekeyLimit is default none, which means that rekeying is performed after the cipher's default amount of data has been sent or received and no time based rekeying is done.`, + Value: docvalues.KeyValueAssignmentValue{ + Separator: " ", + ValueIsOptional: true, + Key: DataAmountValue{}, + Value: TimeFormatValue{}, + }, + }, + "RequiredRSASize": docvalues.DocumentationValue{ + Documentation: `Specifies the minimum RSA key size (in bits) that sshd(8) will accept. User and host-based authentication keys smaller than this limit will be refused. The default is 1024 bits. Note that this limit may only be raised from the default.`, + Value: docvalues.NumberValue{Min: &ZERO}, + }, + "RevokedKeys": docvalues.DocumentationValue{ + Documentation: `Specifies revoked public keys file, or none to not use one. Keys listed in this file will be refused for public key authentication. Note that if this file is not readable, then public key authentication will be refused for all users. Keys may be specified as a text file, listing one public key per line, or as an OpenSSH Key Revocation List (KRL) as generated by ssh-keygen(1). For more information on KRLs, see the KEY REVOCATION LISTS section in ssh-keygen(1).`, + Value: docvalues.StringValue{}, + }, + "RDomain": docvalues.DocumentationValue{ + Documentation: `Specifies an explicit routing domain that is applied after authentication has completed. The user session, as well as any forwarded or listening IP sockets, will be bound to this rdomain(4). If the routing domain is set to %D, then the domain in which the incoming connection was received will be applied.`, + Value: docvalues.OrValue{ + Values: []docvalues.Value{ + docvalues.EnumValue{ + Values: []docvalues.EnumString{ + { + InsertText: "%D", + DescriptionText: "%D", + Documentation: "The domain in which the incoming connection was received", + }, + }, + }, + docvalues.StringValue{}, + }, + }, + }, + "SecurityKeyProvider": docvalues.DocumentationValue{ + Documentation: `Specifies a path to a library that will be used when loading FIDO authenticator-hosted keys, overriding the default of using the built-in USB HID support.`, + Value: docvalues.PathValue{ + RequiredType: docvalues.PathTypeFile, + }, + }, + + "SetEnv": docvalues.DocumentationValue{ + Documentation: `Specifies one or more environment variables to set in child sessions started by sshd(8) as “NAME=VALUE”. The environment value may be quoted (e.g. if it contains whitespace characters). Environment variables set by SetEnv override the default environment and any variables specified by the user via AcceptEnv or PermitUserEnvironment.`, + Value: docvalues.ArrayValue{ + Separator: " ", + DuplicatesExtractor: &setEnvExtractor, + SubValue: docvalues.KeyValueAssignmentValue{ + ValueIsOptional: false, + Separator: "=", + Key: docvalues.StringValue{}, + Value: docvalues.StringValue{}, + }, + }, + }, + "StreamLocalBindMask": docvalues.DocumentationValue{ + Documentation: `Sets the octal file creation mode mask (umask) used when creating a Unix-domain socket file for local or remote port forwarding. This option is only used for port forwarding to a Unix-domain socket file. + The default value is 0177, which creates a Unix-domain socket file that is readable and writable only by the owner. Note that not all operating systems honor the file mode on Unix-domain socket files.`, + Value: docvalues.NumberValue{Min: &ZERO, Max: &MAX_FILE_MODE}, + }, + "StreamLocalBindUnlink": docvalues.DocumentationValue{ + Documentation: `Specifies whether to remove an existing Unix-domain socket file for local or remote port forwarding before creating a new one. If the socket file already exists and StreamLocalBindUnlink is not enabled, sshd will be unable to forward the port to the Unix-domain socket file. This option is only used for port forwarding to a Unix-domain socket file. + The argument must be yes or no. The default is no.`, + Value: booleanEnumValue, + }, + "StrictModes": docvalues.DocumentationValue{ + Documentation: `Specifies whether sshd(8) should check file modes and ownership of the user's files and home directory before accepting login. This is normally desirable because novices sometimes accidentally leave their directory or files world-writable. The default is yes. Note that this does not apply to ChrootDirectory, whose permissions and ownership are checked unconditionally.`, + Value: booleanEnumValue, + }, + "Subsystem": docvalues.DocumentationValue{ + Documentation: `Configures an external subsystem (e.g. file transfer daemon). Arguments should be a subsystem name and a command (with optional arguments) to execute upon subsystem request. + The command sftp-server implements the SFTP file transfer subsystem. + Alternately the name internal-sftp implements an in- process SFTP server. This may simplify configurations using ChrootDirectory to force a different filesystem root on clients. It accepts the same command line arguments as sftp-server and even though it is in- process, settings such as LogLevel or SyslogFacility do not apply to it and must be set explicitly via command line arguments. + By default no subsystems are defined.`, + Value: docvalues.StringValue{}, + }, + "SyslogFacility": docvalues.DocumentationValue{ + Documentation: `Gives the facility code that is used when logging messages from sshd(8). The possible values are: DAEMON, USER, AUTH, LOCAL0, LOCAL1, LOCAL2, LOCAL3, LOCAL4, LOCAL5, LOCAL6, LOCAL7. The default is AUTH.`, + Value: docvalues.EnumValue{ + EnforceValues: true, + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("DAEMON"), + docvalues.CreateEnumString("USER"), + docvalues.CreateEnumString("AUTH"), + docvalues.CreateEnumString("LOCAL0"), + docvalues.CreateEnumString("LOCAL1"), + docvalues.CreateEnumString("LOCAL2"), + docvalues.CreateEnumString("LOCAL3"), + docvalues.CreateEnumString("LOCAL4"), + docvalues.CreateEnumString("LOCAL5"), + docvalues.CreateEnumString("LOCAL6"), + docvalues.CreateEnumString("LOCAL7"), + }, + }, + }, + "TCPKeepAlive": docvalues.DocumentationValue{ + Documentation: `Specifies whether the system should send TCP keepalive messages to the other side. If they are sent, death of the connection or crash of one of the machines will be properly noticed. However, this means that connections will die if the route is down temporarily, and some people find it annoying. On the other hand, if TCP keepalives are not sent, sessions may hang indefinitely on the server, leaving "ghost" users and consuming server resources. + The default is yes (to send TCP keepalive messages), and the server will notice if the network goes down or the client host crashes. This avoids infinitely hanging sessions. + To disable TCP keepalive messages, the value should be set to no.`, + Value: booleanEnumValue, + }, + "TrustedUserCAKeys": docvalues.DocumentationValue{ + Documentation: `Specifies a file containing public keys of certificate authorities that are trusted to sign user certificates for authentication, or none to not use one. Keys are listed one per line; empty lines and comments starting with ‘#’ are allowed. If a certificate is presented for authentication and has its signing CA key listed in this file, then it may be used for authentication for any user listed in the certificate's principals list. Note that certificates that lack a list of principals will not be permitted for authentication using TrustedUserCAKeys. For more details on certificates, see the CERTIFICATES section in ssh-keygen(1).`, + Value: docvalues.StringValue{}, + }, + "UnusedConnectionTimeout": docvalues.DocumentationValue{ + Documentation: `Specifies whether and how quickly sshd(8) should close client connections with no open channels. Open channels include active shell, command execution or subsystem sessions, connected network, socket, agent or X11 forwardings. Forwarding listeners, such as those from the ssh(1) -R flag, are not considered as open channels and do not prevent the timeout. The timeout value is specified in seconds or may use any of the units documented in the “TIME FORMATS” section. + Note that this timeout starts when the client connection completes user authentication but before the client has an opportunity to open any channels. Caution should be used when using short timeout values, as they may not provide sufficient time for the client to request and open its channels before terminating the connection. + The default none is to never expire connections for having no open channels. This option may be useful in conjunction with ChannelTimeout.`, + Value: TimeFormatValue{}, + }, + "UseDNS": docvalues.DocumentationValue{ + Documentation: `Specifies whether sshd(8) should look up the remote host name, and to check that the resolved host name for the remote IP address maps back to the very same IP address. + If this option is set to no (the default) then only addresses and not host names may be used in ~/.ssh/authorized_keys from and sshd_config Match Host directives.`, + Value: booleanEnumValue, + }, + + "UsePAM": docvalues.DocumentationValue{ + Documentation: `Enables the Pluggable Authentication Module interface. If set to yes this will enable PAM authentication using KbdInteractiveAuthentication and PasswordAuthentication in addition to PAM account and session module processing for all authentication types. + Because PAM keyboard-interactive authentication usually serves an equivalent role to password authentication, you should disable either PasswordAuthentication or KbdInteractiveAuthentication. + If UsePAM is enabled, you will not be able to run sshd(8) as a non-root user. The default is no.`, + Value: booleanEnumValue, + }, + "VersionAddendum": docvalues.DocumentationValue{ + Documentation: `Optionally specifies additional text to append to the SSH protocol banner sent by the server upon connection. The default is none.`, + Value: docvalues.OrValue{ + Values: []docvalues.Value{ + docvalues.EnumValue{ + EnforceValues: true, + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("none"), + }, + }, + docvalues.StringValue{}, + }, + }, + }, + "X11DisplayOffset": docvalues.DocumentationValue{ + Documentation: `Specifies the first display number available for sshd(8)'s X11 forwarding. This prevents sshd from interfering with real X11 servers. The default is 10.`, + Value: docvalues.NumberValue{Min: &ZERO}, + }, + "X11Forwarding": docvalues.DocumentationValue{ + Documentation: `Specifies whether X11 forwarding is permitted. The argument must be yes or no. The default is no. + When X11 forwarding is enabled, there may be additional exposure to the server and to client displays if the sshd(8) proxy display is configured to listen on the wildcard address (see X11UseLocalhost), though this is not the default. Additionally, the authentication spoofing and authentication data verification and substitution occur on the client side. The security risk of using X11 forwarding is that the client's X11 display server may be exposed to attack when the SSH client requests forwarding (see the warnings for ForwardX11 in ssh_config(5)). A system administrator may have a stance in which they want to protect clients that may expose themselves to attack by unwittingly requesting X11 forwarding, which can warrant a no setting. + Note that disabling X11 forwarding does not prevent users from forwarding X11 traffic, as users can always install their own forwarders.`, + Value: booleanEnumValue, + }, + "X11UseLocalhost": docvalues.DocumentationValue{ + Documentation: `Specifies whether sshd(8) should bind the X11 forwarding server to the loopback address or to the wildcard address. By default, sshd binds the forwarding server to the loopback address and sets the hostname part of the DISPLAY environment variable to localhost. This prevents remote hosts from connecting to the proxy display. However, some older X11 clients may not function with this configuration. X11UseLocalhost may be set to no to specify that the forwarding server should be bound to the wildcard address. The argument must be yes or no. The default is yes.`, + Value: booleanEnumValue, + }, + "XAuthLocation": docvalues.DocumentationValue{ + Documentation: `Specifies the full pathname of the xauth(1) program, or none to not use one. The default is /usr/X11R6/bin/xauth.`, + Value: docvalues.StringValue{}, + }, +} diff --git a/handlers/sshd_config/fields/utils.go b/handlers/sshd_config/fields/utils.go new file mode 100644 index 0000000..78ebcc7 --- /dev/null +++ b/handlers/sshd_config/fields/utils.go @@ -0,0 +1,96 @@ +package fields + +import ( + docvalues "config-lsp/doc-values" + "config-lsp/utils" + "os/exec" + "strings" +) + +var booleanEnumValue = docvalues.EnumValue{ + EnforceValues: true, + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("yes"), + docvalues.CreateEnumString("no"), + }, +} + +var plusMinuxCaretPrefixes = []docvalues.Prefix{ + { + Prefix: "+", + Meaning: "Append to the default set", + }, + { + Prefix: "-", + Meaning: "Remove from the default set", + }, + { + Prefix: "^", + Meaning: "Place at the head of the default set", + }, +} + +var channelTimeoutExtractor = docvalues.ExtractKeyDuplicatesExtractor("=") +var setEnvExtractor = docvalues.ExtractKeyDuplicatesExtractor("=") + +func prefixPlusMinusCaret(values []docvalues.EnumString) docvalues.PrefixWithMeaningValue { + return docvalues.PrefixWithMeaningValue{ + Prefixes: []docvalues.Prefix{ + { + Prefix: "+", + Meaning: "Append to the default set", + }, + { + Prefix: "-", + Meaning: "Remove from the default set", + }, + { + Prefix: "^", + Meaning: "Place at the head of the default set", + }, + }, + SubValue: docvalues.ArrayValue{ + Separator: ",", + DuplicatesExtractor: &docvalues.SimpleDuplicatesExtractor, + SubValue: docvalues.EnumValue{ + Values: values, + }, + }, + } +} + +var _cachedQueries map[string][]docvalues.EnumString = make(map[string][]docvalues.EnumString) + +func queryValues(query string) ([]string, error) { + cmd := exec.Command("ssh", "-Q", query) + + output, err := cmd.Output() + + if err != nil { + return []string{}, err + } + + return strings.Split(string(output), "\n"), nil +} + +func queryOpenSSHOptions( + query string, +) ([]docvalues.EnumString, error) { + var availableQueries []docvalues.EnumString + key := query + + if _cachedQueries[key] != nil && len(_cachedQueries[key]) > 0 { + return _cachedQueries[key], nil + } else { + availableRawQueries, err := queryValues(query) + availableQueries = utils.Map(availableRawQueries, docvalues.CreateEnumString) + + if err != nil { + return []docvalues.EnumString{}, err + } + + _cachedQueries[key] = availableQueries + } + + return availableQueries, nil +} diff --git a/handlers/sshd_config/fields/value-data-amount-value.go b/handlers/sshd_config/fields/value-data-amount-value.go new file mode 100644 index 0000000..01a6b68 --- /dev/null +++ b/handlers/sshd_config/fields/value-data-amount-value.go @@ -0,0 +1,97 @@ +package fields + +import ( + docvalues "config-lsp/doc-values" + "fmt" + "regexp" + "strconv" + + protocol "github.com/tliron/glsp/protocol_3_16" +) + +var dataAmountCheckPattern = regexp.MustCompile(`(?i)^(\d+)([KMG])$`) + +type InvalidDataAmountError struct{} + +func (e InvalidDataAmountError) Error() string { + return "Data amount is invalid. It must be in the form of: [K|M|G]" +} + +type DataAmountValue struct{} + +func (v DataAmountValue) GetTypeDescription() []string { + return []string{"Data amount"} +} + +func (v DataAmountValue) CheckIsValid(value string) []*docvalues.InvalidValue { + if !dataAmountCheckPattern.MatchString(value) { + return []*docvalues.InvalidValue{ + { + Err: InvalidDataAmountError{}, + Start: 0, + End: uint32(len(value)), + }, + } + } + + return nil +} + +func calculateLineToKilobyte(value string, unit string) string { + val, err := strconv.Atoi(value) + + if err != nil { + return "" + } + + switch unit { + case "K": + return strconv.Itoa(val) + case "M": + return strconv.Itoa(val * 1000) + case "G": + return strconv.Itoa(val * 1000 * 1000) + default: + return "" + } +} + +func (v DataAmountValue) FetchCompletions(line string, cursor uint32) []protocol.CompletionItem { + completions := make([]protocol.CompletionItem, 0) + + if line != "" && !dataAmountCheckPattern.MatchString(line) { + kind := protocol.CompletionItemKindValue + + completions = append( + completions, + protocol.CompletionItem{ + Label: line + "K", + Kind: &kind, + Documentation: line + " kilobytes", + }, + protocol.CompletionItem{ + Label: line + "M", + Kind: &kind, + Documentation: fmt.Sprintf("%s megabytes (%s kilobytes)", line, calculateLineToKilobyte(line, "M")), + }, + protocol.CompletionItem{ + Label: line + "G", + Kind: &kind, + Documentation: fmt.Sprintf("%s gigabytes (%s kilobytes)", line, calculateLineToKilobyte(line, "G")), + }, + ) + } + + if line == "" || isJustDigitsPattern.MatchString(line) { + completions = append( + completions, + docvalues.GenerateBase10Completions(line)..., + ) + } + + return completions +} + +func (v DataAmountValue) FetchHoverInfo(line string, cursor uint32) []string { + return []string{} +} diff --git a/handlers/sshd_config/fields/value-time-format.go b/handlers/sshd_config/fields/value-time-format.go new file mode 100644 index 0000000..607ac3d --- /dev/null +++ b/handlers/sshd_config/fields/value-time-format.go @@ -0,0 +1,111 @@ +package fields + +import ( + docvalues "config-lsp/doc-values" + "config-lsp/utils" + "fmt" + "regexp" + "strconv" + + protocol "github.com/tliron/glsp/protocol_3_16" +) + +var timeFormatCompletionsPattern = regexp.MustCompile(`(?i)^(\d+)([smhdw])$`) +var timeFormatCheckPattern = regexp.MustCompile(`(?i)^(\d+)([smhdw]?)$`) + +type InvalidTimeFormatError struct{} + +func (e InvalidTimeFormatError) Error() string { + return "Time format is invalid. It must be in the form of: [s|m|h|d|w]" +} + +type TimeFormatValue struct{} + +func (v TimeFormatValue) GetTypeDescription() []string { + return []string{"Time value"} +} + +func (v TimeFormatValue) CheckIsValid(value string) []*docvalues.InvalidValue { + if !timeFormatCheckPattern.MatchString(value) { + return []*docvalues.InvalidValue{ + { + Err: InvalidTimeFormatError{}, + Start: 0, + End: uint32(len(value)), + }, + } + } + + return nil +} + +func calculateInSeconds(value int, unit string) int { + switch unit { + case "s": + return value + case "m": + return value * 60 + case "h": + return value * 60 * 60 + case "d": + return value * 60 * 60 * 24 + case "w": + return value * 60 * 60 * 24 * 7 + default: + return 0 + } +} + +func (v TimeFormatValue) FetchCompletions(line string, cursor uint32) []protocol.CompletionItem { + completions := make([]protocol.CompletionItem, 0) + + if line != "" && !timeFormatCompletionsPattern.MatchString(line) { + completions = append( + completions, + utils.Map( + []string{"s", "m", "h", "d", "w"}, + func(unit string) protocol.CompletionItem { + kind := protocol.CompletionItemKindValue + + unitName := map[string]string{ + "s": "seconds", + "m": "minutes", + "h": "hours", + "d": "days", + "w": "weeks", + }[unit] + + var detail string + value, err := strconv.Atoi(line) + + if err == nil { + if unit == "s" { + detail = fmt.Sprintf("%d seconds", value) + } else { + detail = fmt.Sprintf("%d %s (%d seconds)", value, unitName, calculateInSeconds(value, unit)) + } + } + + return protocol.CompletionItem{ + Label: line + unit, + Kind: &kind, + Detail: &detail, + } + }, + )..., + ) + } + + if line == "" || isJustDigitsPattern.MatchString(line) { + completions = append( + completions, + docvalues.GenerateBase10Completions(line)..., + ) + } + + return completions +} + +func (v TimeFormatValue) FetchHoverInfo(line string, cursor uint32) []string { + return []string{} +} From c89752332123c5d46fb48ca1c7affd1da6e2679a Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Tue, 10 Sep 2024 22:40:18 +0200 Subject: [PATCH 011/133] fix(sshd_config): Add missing regex --- handlers/sshd_config/fields/utils.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/handlers/sshd_config/fields/utils.go b/handlers/sshd_config/fields/utils.go index 78ebcc7..eb092d0 100644 --- a/handlers/sshd_config/fields/utils.go +++ b/handlers/sshd_config/fields/utils.go @@ -4,9 +4,12 @@ import ( docvalues "config-lsp/doc-values" "config-lsp/utils" "os/exec" + "regexp" "strings" ) +var isJustDigitsPattern = regexp.MustCompile(`^\d+$`) + var booleanEnumValue = docvalues.EnumValue{ EnforceValues: true, Values: []docvalues.EnumString{ From 7ec24834f38642d1706a24fac2703b55c5b457df Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Tue, 10 Sep 2024 23:11:05 +0200 Subject: [PATCH 012/133] feat(sshd_config): Add lsp handler --- handlers/sshd_config/analyzer/analyzer.go | 12 +++++ .../lsp/text-document-code-action.go | 14 ++++++ .../lsp/text-document-completion.go | 10 +++++ .../lsp/text-document-did-change.go | 42 +++++++++++++++++ .../lsp/text-document-did-close.go | 13 ++++++ .../sshd_config/lsp/text-document-did-open.go | 45 +++++++++++++++++++ .../sshd_config/lsp/text-document-hover.go | 13 ++++++ .../lsp/text-document-signature-help.go | 10 +++++ .../lsp/workspace-execute-command.go | 10 +++++ handlers/sshd_config/shared.go | 14 ++++++ root-handler/text-document-code-action.go | 3 +- root-handler/text-document-completion.go | 3 +- root-handler/text-document-hover.go | 3 +- root-handler/text-document-signature-help.go | 3 +- root-handler/workspace-execute-command.go | 1 + 15 files changed, 192 insertions(+), 4 deletions(-) create mode 100644 handlers/sshd_config/analyzer/analyzer.go create mode 100644 handlers/sshd_config/lsp/text-document-code-action.go create mode 100644 handlers/sshd_config/lsp/text-document-completion.go create mode 100644 handlers/sshd_config/lsp/text-document-did-change.go create mode 100644 handlers/sshd_config/lsp/text-document-did-close.go create mode 100644 handlers/sshd_config/lsp/text-document-did-open.go create mode 100644 handlers/sshd_config/lsp/text-document-hover.go create mode 100644 handlers/sshd_config/lsp/text-document-signature-help.go create mode 100644 handlers/sshd_config/lsp/workspace-execute-command.go create mode 100644 handlers/sshd_config/shared.go diff --git a/handlers/sshd_config/analyzer/analyzer.go b/handlers/sshd_config/analyzer/analyzer.go new file mode 100644 index 0000000..4635a05 --- /dev/null +++ b/handlers/sshd_config/analyzer/analyzer.go @@ -0,0 +1,12 @@ +package analyzer + +import ( + "config-lsp/handlers/sshd_config" + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func Analyze( + d *sshdconfig.SSHDocument, +) []protocol.Diagnostic { + return nil +} diff --git a/handlers/sshd_config/lsp/text-document-code-action.go b/handlers/sshd_config/lsp/text-document-code-action.go new file mode 100644 index 0000000..37950bd --- /dev/null +++ b/handlers/sshd_config/lsp/text-document-code-action.go @@ -0,0 +1,14 @@ +package lsp + +import ( + "github.com/tliron/glsp" + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func TextDocumentCodeAction(context *glsp.Context, params *protocol.CodeActionParams) ([]protocol.CodeAction, error) { + // document := hosts.DocumentParserMap[params.TextDocument.URI] + // + // actions := make([]protocol.CodeAction, 0, 1) + + return nil, nil +} diff --git a/handlers/sshd_config/lsp/text-document-completion.go b/handlers/sshd_config/lsp/text-document-completion.go new file mode 100644 index 0000000..5c5b64a --- /dev/null +++ b/handlers/sshd_config/lsp/text-document-completion.go @@ -0,0 +1,10 @@ +package lsp + +import ( + "github.com/tliron/glsp" + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func TextDocumentCompletion(context *glsp.Context, params *protocol.CompletionParams) (any, error) { + return nil, nil +} diff --git a/handlers/sshd_config/lsp/text-document-did-change.go b/handlers/sshd_config/lsp/text-document-did-change.go new file mode 100644 index 0000000..bed7156 --- /dev/null +++ b/handlers/sshd_config/lsp/text-document-did-change.go @@ -0,0 +1,42 @@ +package lsp + +import ( + "config-lsp/common" + "config-lsp/handlers/sshd_config/analyzer" + "config-lsp/handlers/sshd_config" + "config-lsp/utils" + + "github.com/tliron/glsp" + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func TextDocumentDidChange( + context *glsp.Context, + params *protocol.DidChangeTextDocumentParams, +) error { + content := params.ContentChanges[0].(protocol.TextDocumentContentChangeEventWhole).Text + common.ClearDiagnostics(context, params.TextDocument.URI) + + document := sshdconfig.DocumentParserMap[params.TextDocument.URI] + document.Config.Clear() + + diagnostics := make([]protocol.Diagnostic, 0) + errors := document.Config.Parse(content) + + if len(errors) > 0 { + diagnostics = append(diagnostics, utils.Map( + errors, + func(err common.LSPError) protocol.Diagnostic { + return err.ToDiagnostic() + }, + )...) + } + + diagnostics = append(diagnostics, analyzer.Analyze(document)...) + + if len(diagnostics) > 0 { + common.SendDiagnostics(context, params.TextDocument.URI, diagnostics) + } + + return nil +} diff --git a/handlers/sshd_config/lsp/text-document-did-close.go b/handlers/sshd_config/lsp/text-document-did-close.go new file mode 100644 index 0000000..52834b0 --- /dev/null +++ b/handlers/sshd_config/lsp/text-document-did-close.go @@ -0,0 +1,13 @@ +package lsp + +import ( + "config-lsp/handlers/sshd_config" + "github.com/tliron/glsp" + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func TextDocumentDidClose(context *glsp.Context, params *protocol.DidCloseTextDocumentParams) error { + delete(sshdconfig.DocumentParserMap, params.TextDocument.URI) + + return nil +} diff --git a/handlers/sshd_config/lsp/text-document-did-open.go b/handlers/sshd_config/lsp/text-document-did-open.go new file mode 100644 index 0000000..7906931 --- /dev/null +++ b/handlers/sshd_config/lsp/text-document-did-open.go @@ -0,0 +1,45 @@ +package lsp + +import ( + "config-lsp/common" + "config-lsp/handlers/sshd_config" + "config-lsp/handlers/sshd_config/analyzer" + "config-lsp/handlers/sshd_config/ast" + "config-lsp/utils" + + "github.com/tliron/glsp" + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func TextDocumentDidOpen( + context *glsp.Context, + params *protocol.DidOpenTextDocumentParams, +) error { + common.ClearDiagnostics(context, params.TextDocument.URI) + + parser := ast.NewSSHConfig() + document := sshdconfig.SSHDocument{ + Config: parser, + } + sshdconfig.DocumentParserMap[params.TextDocument.URI] = &document + + errors := parser.Parse(params.TextDocument.Text) + + diagnostics := utils.Map( + errors, + func(err common.LSPError) protocol.Diagnostic { + return err.ToDiagnostic() + }, + ) + + diagnostics = append( + diagnostics, + analyzer.Analyze(&document)..., + ) + + if len(diagnostics) > 0 { + common.SendDiagnostics(context, params.TextDocument.URI, diagnostics) + } + + return nil +} diff --git a/handlers/sshd_config/lsp/text-document-hover.go b/handlers/sshd_config/lsp/text-document-hover.go new file mode 100644 index 0000000..61d19cd --- /dev/null +++ b/handlers/sshd_config/lsp/text-document-hover.go @@ -0,0 +1,13 @@ +package lsp + +import ( + "github.com/tliron/glsp" + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func TextDocumentHover( + context *glsp.Context, + params *protocol.HoverParams, +) (*protocol.Hover, error) { + return nil, nil +} diff --git a/handlers/sshd_config/lsp/text-document-signature-help.go b/handlers/sshd_config/lsp/text-document-signature-help.go new file mode 100644 index 0000000..eff0052 --- /dev/null +++ b/handlers/sshd_config/lsp/text-document-signature-help.go @@ -0,0 +1,10 @@ +package lsp + +import ( + "github.com/tliron/glsp" + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func TextDocumentSignatureHelp(context *glsp.Context, params *protocol.SignatureHelpParams) (*protocol.SignatureHelp, error) { + return nil, nil +} diff --git a/handlers/sshd_config/lsp/workspace-execute-command.go b/handlers/sshd_config/lsp/workspace-execute-command.go new file mode 100644 index 0000000..f2f39d0 --- /dev/null +++ b/handlers/sshd_config/lsp/workspace-execute-command.go @@ -0,0 +1,10 @@ +package lsp + +import ( + "github.com/tliron/glsp" + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func WorkspaceExecuteCommand(context *glsp.Context, params *protocol.ExecuteCommandParams) (*protocol.ApplyWorkspaceEditParams, error) { + return nil, nil +} diff --git a/handlers/sshd_config/shared.go b/handlers/sshd_config/shared.go new file mode 100644 index 0000000..e5503b7 --- /dev/null +++ b/handlers/sshd_config/shared.go @@ -0,0 +1,14 @@ +package sshdconfig + +import ( + "config-lsp/handlers/sshd_config/ast" + + protocol "github.com/tliron/glsp/protocol_3_16" +) + +type SSHDocument struct { + Config *ast.SSHConfig +} + +var DocumentParserMap = map[protocol.DocumentUri]*SSHDocument{} + diff --git a/root-handler/text-document-code-action.go b/root-handler/text-document-code-action.go index f1da029..a9d3d33 100644 --- a/root-handler/text-document-code-action.go +++ b/root-handler/text-document-code-action.go @@ -3,6 +3,7 @@ package roothandler import ( aliases "config-lsp/handlers/aliases/lsp" hosts "config-lsp/handlers/hosts/lsp" + sshdconfig "config-lsp/handlers/sshd_config/lsp" wireguard "config-lsp/handlers/wireguard/lsp" "github.com/tliron/glsp" @@ -28,7 +29,7 @@ func TextDocumentCodeAction(context *glsp.Context, params *protocol.CodeActionPa case LanguageHosts: return hosts.TextDocumentCodeAction(context, params) case LanguageSSHDConfig: - return nil, nil + return sshdconfig.TextDocumentCodeAction(context, params) case LanguageWireguard: return wireguard.TextDocumentCodeAction(context, params) case LanguageAliases: diff --git a/root-handler/text-document-completion.go b/root-handler/text-document-completion.go index 160bcb2..6b5a2f2 100644 --- a/root-handler/text-document-completion.go +++ b/root-handler/text-document-completion.go @@ -4,6 +4,7 @@ import ( aliases "config-lsp/handlers/aliases/lsp" fstab "config-lsp/handlers/fstab/lsp" hosts "config-lsp/handlers/hosts/lsp" + sshdconfig "config-lsp/handlers/sshd_config/lsp" wireguard "config-lsp/handlers/wireguard/lsp" "github.com/tliron/glsp" @@ -27,7 +28,7 @@ func TextDocumentCompletion(context *glsp.Context, params *protocol.CompletionPa case LanguageFstab: return fstab.TextDocumentCompletion(context, params) case LanguageSSHDConfig: - return nil, nil + return sshdconfig.TextDocumentCompletion(context, params) case LanguageWireguard: return wireguard.TextDocumentCompletion(context, params) case LanguageHosts: diff --git a/root-handler/text-document-hover.go b/root-handler/text-document-hover.go index dfc15c6..da9a971 100644 --- a/root-handler/text-document-hover.go +++ b/root-handler/text-document-hover.go @@ -4,6 +4,7 @@ import ( aliases "config-lsp/handlers/aliases/lsp" fstab "config-lsp/handlers/fstab/lsp" hosts "config-lsp/handlers/hosts/lsp" + sshdconfig "config-lsp/handlers/sshd_config/lsp" wireguard "config-lsp/handlers/wireguard/lsp" "github.com/tliron/glsp" @@ -27,7 +28,7 @@ func TextDocumentHover(context *glsp.Context, params *protocol.HoverParams) (*pr case LanguageHosts: return hosts.TextDocumentHover(context, params) case LanguageSSHDConfig: - return nil, nil + return sshdconfig.TextDocumentHover(context, params) case LanguageFstab: return fstab.TextDocumentHover(context, params) case LanguageWireguard: diff --git a/root-handler/text-document-signature-help.go b/root-handler/text-document-signature-help.go index a3a7396..3fb742e 100644 --- a/root-handler/text-document-signature-help.go +++ b/root-handler/text-document-signature-help.go @@ -2,6 +2,7 @@ package roothandler import ( aliases "config-lsp/handlers/aliases/lsp" + sshdconfig "config-lsp/handlers/sshd_config/lsp" "github.com/tliron/glsp" protocol "github.com/tliron/glsp/protocol_3_16" @@ -24,7 +25,7 @@ func TextDocumentSignatureHelp(context *glsp.Context, params *protocol.Signature case LanguageHosts: return nil, nil case LanguageSSHDConfig: - return nil, nil + return sshdconfig.TextDocumentSignatureHelp(context, params) case LanguageFstab: return nil, nil case LanguageWireguard: diff --git a/root-handler/workspace-execute-command.go b/root-handler/workspace-execute-command.go index e159353..dd7f906 100644 --- a/root-handler/workspace-execute-command.go +++ b/root-handler/workspace-execute-command.go @@ -3,6 +3,7 @@ package roothandler import ( hosts "config-lsp/handlers/hosts/lsp" wireguard "config-lsp/handlers/wireguard/lsp" + "strings" "github.com/tliron/glsp" From 75f93cfb44a11e4496bb969ec46fbcd1cc4715fd Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Tue, 10 Sep 2024 23:11:30 +0200 Subject: [PATCH 013/133] fix(aliases): Fix textDocument/didClose --- handlers/aliases/lsp/text-document-did-close.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/handlers/aliases/lsp/text-document-did-close.go b/handlers/aliases/lsp/text-document-did-close.go index 3283aad..7eb4a5f 100644 --- a/handlers/aliases/lsp/text-document-did-close.go +++ b/handlers/aliases/lsp/text-document-did-close.go @@ -1,13 +1,13 @@ package lsp import ( - "config-lsp/handlers/hosts" + "config-lsp/handlers/aliases" "github.com/tliron/glsp" protocol "github.com/tliron/glsp/protocol_3_16" ) func TextDocumentDidClose(context *glsp.Context, params *protocol.DidCloseTextDocumentParams) error { - delete(hosts.DocumentParserMap, params.TextDocument.URI) + delete(aliases.DocumentParserMap, params.TextDocument.URI) return nil } From 02b4a53480a0a14521f553ef4e17fd7b7c2ae6d6 Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Wed, 11 Sep 2024 19:55:27 +0200 Subject: [PATCH 014/133] feat(aliases): Add code action to send test mails --- handlers/aliases/commands/aliases-command.go | 45 ++++++++++++++ .../aliases/commands/aliases-commands_test.go | 11 ++++ handlers/aliases/handlers/code-actions.go | 51 ++++++++++++++++ .../aliases/handlers/fetch-code-actions.go | 59 +++++++++++++++++++ .../aliases/lsp/text-document-code-action.go | 10 ++-- .../aliases/lsp/workspace-execute-command.go | 24 ++++---- 6 files changed, 186 insertions(+), 14 deletions(-) create mode 100644 handlers/aliases/commands/aliases-command.go create mode 100644 handlers/aliases/commands/aliases-commands_test.go create mode 100644 handlers/aliases/handlers/code-actions.go create mode 100644 handlers/aliases/handlers/fetch-code-actions.go diff --git a/handlers/aliases/commands/aliases-command.go b/handlers/aliases/commands/aliases-command.go new file mode 100644 index 0000000..7ad9475 --- /dev/null +++ b/handlers/aliases/commands/aliases-command.go @@ -0,0 +1,45 @@ +package commands + +import ( + "os/exec" + "strings" +) + +func IsNewAliasesCommandAvailable() bool { + _, err := exec.LookPath("newaliases") + + return err == nil +} + +func IsSendmailCommandAvailable() bool { + _, err := exec.LookPath("sendmail") + + return err == nil +} + +func IsPostfixCommandAvailable() bool { + _, err := exec.LookPath("postfix") + + return err == nil +} + +func CanSendTestMails() bool { + return IsSendmailCommandAvailable() && IsPostfixCommandAvailable() +} + +func UpdateAliasesDatabase() error { + cmd := exec.Command("newaliases") + + err := cmd.Run() + + return err +} + +func SendTestMail(address string, content string) error { + cmd := exec.Command("sendmail", address) + cmd.Stdin = strings.NewReader(content) + + err := cmd.Run() + + return err +} diff --git a/handlers/aliases/commands/aliases-commands_test.go b/handlers/aliases/commands/aliases-commands_test.go new file mode 100644 index 0000000..fee1097 --- /dev/null +++ b/handlers/aliases/commands/aliases-commands_test.go @@ -0,0 +1,11 @@ +package commands + +import "testing" + +func TestAreAliasesCommandsAvailable( + t *testing.T, +) { + if !IsNewAliasesCommandAvailable() { + t.Skip("Aliases tools not available") + } +} diff --git a/handlers/aliases/handlers/code-actions.go b/handlers/aliases/handlers/code-actions.go new file mode 100644 index 0000000..a8eedd4 --- /dev/null +++ b/handlers/aliases/handlers/code-actions.go @@ -0,0 +1,51 @@ +package handlers + +import ( + "config-lsp/handlers/aliases" + "config-lsp/handlers/aliases/commands" + "fmt" + "time" + + protocol "github.com/tliron/glsp/protocol_3_16" +) + +type CodeActionName string + +const ( + CodeActionSendTestMail CodeActionName = "sendTestMail" +) + +type CodeAction interface { + RunCommand(*aliases.AliasesDocument) (*protocol.ApplyWorkspaceEditParams, error) +} + +type CodeActionArgs interface{} + +type CodeActionSendTestMailArgs struct { + URI protocol.DocumentUri + User string +} + +func CodeActionSendTestMailArgsFromArguments(arguments map[string]interface{}) CodeActionSendTestMailArgs { + return CodeActionSendTestMailArgs{ + URI: arguments["URI"].(protocol.DocumentUri), + User: arguments["User"].(string), + } +} + +func (args CodeActionSendTestMailArgs) RunCommand(d *aliases.AliasesDocument) (*protocol.ApplyWorkspaceEditParams, error) { + content := fmt.Sprintf( + `Subject: Test mail from %s + +This is a test mail from config-lsp. +It is intended for the user %s. +`, + time.Now().Format(time.RFC1123), + args.User, + ) + + address := fmt.Sprintf("%s@localhost.localdomain", args.User) + commands.SendTestMail(address, content) + + return &protocol.ApplyWorkspaceEditParams{}, nil +} diff --git a/handlers/aliases/handlers/fetch-code-actions.go b/handlers/aliases/handlers/fetch-code-actions.go new file mode 100644 index 0000000..5a76437 --- /dev/null +++ b/handlers/aliases/handlers/fetch-code-actions.go @@ -0,0 +1,59 @@ +package handlers + +import ( + "config-lsp/handlers/aliases" + "config-lsp/handlers/aliases/ast" + "config-lsp/handlers/aliases/commands" + "fmt" + + protocol "github.com/tliron/glsp/protocol_3_16" +) + +type disabledExplanation struct { + Reason string +} + +func FetchCodeActions( + d *aliases.AliasesDocument, + params *protocol.CodeActionParams, +) []protocol.CodeAction { + line := params.Range.Start.Line + + rawEntry, found := d.Parser.Aliases.Get(line) + + if !found { + return nil + } + + entry := rawEntry.(*ast.AliasEntry) + + if entry.Key != nil { + address := fmt.Sprintf("%s@localhost.localdomain", entry.Key.Value) + + commandID := "aliases." + CodeActionSendTestMail + command := protocol.Command{ + Title: fmt.Sprintf("Send a test mail to %s", address), + Command: string(commandID), + Arguments: []any{ + CodeActionSendTestMailArgs{ + URI: params.TextDocument.URI, + User: entry.Key.Value, + }, + }, + } + codeAction := &protocol.CodeAction{ + Title: fmt.Sprintf("Send a test mail to %s", address), + Command: &command, + } + + if !commands.CanSendTestMails() { + codeAction.Disabled.Reason = "postfix is required to send test mails" + } + + return []protocol.CodeAction{ + *codeAction, + } + } + + return nil +} diff --git a/handlers/aliases/lsp/text-document-code-action.go b/handlers/aliases/lsp/text-document-code-action.go index 37950bd..ba73911 100644 --- a/handlers/aliases/lsp/text-document-code-action.go +++ b/handlers/aliases/lsp/text-document-code-action.go @@ -1,14 +1,16 @@ package lsp import ( + "config-lsp/handlers/aliases" + "config-lsp/handlers/aliases/handlers" + "github.com/tliron/glsp" protocol "github.com/tliron/glsp/protocol_3_16" ) func TextDocumentCodeAction(context *glsp.Context, params *protocol.CodeActionParams) ([]protocol.CodeAction, error) { - // document := hosts.DocumentParserMap[params.TextDocument.URI] - // - // actions := make([]protocol.CodeAction, 0, 1) + d := aliases.DocumentParserMap[params.TextDocument.URI] + actions := handlers.FetchCodeActions(d, params) - return nil, nil + return actions, nil } diff --git a/handlers/aliases/lsp/workspace-execute-command.go b/handlers/aliases/lsp/workspace-execute-command.go index 41f5298..8cad016 100644 --- a/handlers/aliases/lsp/workspace-execute-command.go +++ b/handlers/aliases/lsp/workspace-execute-command.go @@ -1,21 +1,25 @@ package lsp import ( + "config-lsp/handlers/aliases" + "config-lsp/handlers/aliases/handlers" + "strings" + "github.com/tliron/glsp" protocol "github.com/tliron/glsp/protocol_3_16" ) func WorkspaceExecuteCommand(context *glsp.Context, params *protocol.ExecuteCommandParams) (*protocol.ApplyWorkspaceEditParams, error) { - // _, command, _ := strings.Cut(params.Command, ".") - // - // switch command { - // case string(handlers.CodeActionInlineAliases): - // args := handlers.CodeActionInlineAliasesArgsFromArguments(params.Arguments[0].(map[string]any)) - // - // document := hosts.DocumentParserMap[args.URI] - // - // return args.RunCommand(*document.Parser) - // } + _, command, _ := strings.Cut(params.Command, ".") + + switch command { + case string(handlers.CodeActionSendTestMail): + args := handlers.CodeActionSendTestMailArgsFromArguments(params.Arguments[0].(map[string]any)) + + d := aliases.DocumentParserMap[args.URI] + + return args.RunCommand(d) + } return nil, nil } From 6383fbba176e9e47448eb3288e9c04426ee15f65 Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Wed, 11 Sep 2024 22:21:30 +0200 Subject: [PATCH 015/133] feat(sshd_config): Improvements; Add basic root completions --- handlers/sshd_config/Config.g4 | 2 +- handlers/sshd_config/ast/listener.go | 3 +- handlers/sshd_config/ast/parser.go | 2 +- handlers/sshd_config/ast/parser/Config.interp | 2 +- .../sshd_config/ast/parser/config_parser.go | 119 +++++++------- handlers/sshd_config/ast/parser_test.go | 56 +++++++ handlers/sshd_config/ast/sshd_config.go | 38 +++++ handlers/sshd_config/fields/fields.go | 150 +++++++++--------- handlers/sshd_config/handlers/completions.go | 35 ++++ .../lsp/text-document-completion.go | 23 +++ .../lsp/text-document-did-change.go | 2 +- handlers/sshd_config/shared.go | 3 +- 12 files changed, 296 insertions(+), 139 deletions(-) create mode 100644 handlers/sshd_config/handlers/completions.go diff --git a/handlers/sshd_config/Config.g4 b/handlers/sshd_config/Config.g4 index e959976..0621992 100644 --- a/handlers/sshd_config/Config.g4 +++ b/handlers/sshd_config/Config.g4 @@ -5,7 +5,7 @@ lineStatement ; entry - : WHITESPACE? key? WHITESPACE value? WHITESPACE? leadingComment? + : WHITESPACE? key? WHITESPACE? value? WHITESPACE? leadingComment? ; key diff --git a/handlers/sshd_config/ast/listener.go b/handlers/sshd_config/ast/listener.go index 7345a54..48666bf 100644 --- a/handlers/sshd_config/ast/listener.go +++ b/handlers/sshd_config/ast/listener.go @@ -78,11 +78,10 @@ func (s *sshParserListener) EnterValue(ctx *parser.ValueContext) { } } -func (s *sshParserListener) ExitValue(ctx *parser.ValueContext) { +func (s *sshParserListener) ExitEntry(ctx *parser.EntryContext) { location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext) location.ChangeBothLines(s.sshContext.line) - if s.sshContext.isKeyAMatchBlock { // Add new match block matchBlock := &SSHMatchBlock{ diff --git a/handlers/sshd_config/ast/parser.go b/handlers/sshd_config/ast/parser.go index 7624284..466f61e 100644 --- a/handlers/sshd_config/ast/parser.go +++ b/handlers/sshd_config/ast/parser.go @@ -21,7 +21,7 @@ func NewSSHConfig() *SSHConfig { func (c *SSHConfig) Clear() { c.Options = treemap.NewWith(gods.UInt32Comparator) - c.CommentLines = make(map[uint32]struct{}) + c.CommentLines = map[uint32]struct{}{} } var commentPattern = regexp.MustCompile(`^\s*#.*$`) diff --git a/handlers/sshd_config/ast/parser/Config.interp b/handlers/sshd_config/ast/parser/Config.interp index 1a0d4d0..4739ffb 100644 --- a/handlers/sshd_config/ast/parser/Config.interp +++ b/handlers/sshd_config/ast/parser/Config.interp @@ -21,4 +21,4 @@ leadingComment atn: -[4, 1, 4, 59, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 1, 0, 1, 0, 3, 0, 13, 8, 0, 1, 0, 1, 0, 3, 0, 17, 8, 0, 3, 0, 19, 8, 0, 1, 0, 1, 0, 1, 1, 3, 1, 24, 8, 1, 1, 1, 3, 1, 27, 8, 1, 1, 1, 1, 1, 3, 1, 31, 8, 1, 1, 1, 3, 1, 34, 8, 1, 1, 1, 3, 1, 37, 8, 1, 1, 2, 1, 2, 1, 3, 1, 3, 3, 3, 43, 8, 3, 1, 3, 1, 3, 1, 4, 1, 4, 3, 4, 49, 8, 4, 1, 4, 1, 4, 3, 4, 53, 8, 4, 4, 4, 55, 8, 4, 11, 4, 12, 4, 56, 1, 4, 0, 0, 5, 0, 2, 4, 6, 8, 0, 0, 66, 0, 18, 1, 0, 0, 0, 2, 23, 1, 0, 0, 0, 4, 38, 1, 0, 0, 0, 6, 42, 1, 0, 0, 0, 8, 46, 1, 0, 0, 0, 10, 19, 3, 2, 1, 0, 11, 13, 5, 2, 0, 0, 12, 11, 1, 0, 0, 0, 12, 13, 1, 0, 0, 0, 13, 14, 1, 0, 0, 0, 14, 19, 3, 8, 4, 0, 15, 17, 5, 2, 0, 0, 16, 15, 1, 0, 0, 0, 16, 17, 1, 0, 0, 0, 17, 19, 1, 0, 0, 0, 18, 10, 1, 0, 0, 0, 18, 12, 1, 0, 0, 0, 18, 16, 1, 0, 0, 0, 19, 20, 1, 0, 0, 0, 20, 21, 5, 0, 0, 1, 21, 1, 1, 0, 0, 0, 22, 24, 5, 2, 0, 0, 23, 22, 1, 0, 0, 0, 23, 24, 1, 0, 0, 0, 24, 26, 1, 0, 0, 0, 25, 27, 3, 4, 2, 0, 26, 25, 1, 0, 0, 0, 26, 27, 1, 0, 0, 0, 27, 28, 1, 0, 0, 0, 28, 30, 5, 2, 0, 0, 29, 31, 3, 6, 3, 0, 30, 29, 1, 0, 0, 0, 30, 31, 1, 0, 0, 0, 31, 33, 1, 0, 0, 0, 32, 34, 5, 2, 0, 0, 33, 32, 1, 0, 0, 0, 33, 34, 1, 0, 0, 0, 34, 36, 1, 0, 0, 0, 35, 37, 3, 8, 4, 0, 36, 35, 1, 0, 0, 0, 36, 37, 1, 0, 0, 0, 37, 3, 1, 0, 0, 0, 38, 39, 5, 3, 0, 0, 39, 5, 1, 0, 0, 0, 40, 41, 5, 3, 0, 0, 41, 43, 5, 2, 0, 0, 42, 40, 1, 0, 0, 0, 42, 43, 1, 0, 0, 0, 43, 44, 1, 0, 0, 0, 44, 45, 5, 3, 0, 0, 45, 7, 1, 0, 0, 0, 46, 48, 5, 1, 0, 0, 47, 49, 5, 2, 0, 0, 48, 47, 1, 0, 0, 0, 48, 49, 1, 0, 0, 0, 49, 54, 1, 0, 0, 0, 50, 52, 5, 3, 0, 0, 51, 53, 5, 2, 0, 0, 52, 51, 1, 0, 0, 0, 52, 53, 1, 0, 0, 0, 53, 55, 1, 0, 0, 0, 54, 50, 1, 0, 0, 0, 55, 56, 1, 0, 0, 0, 56, 54, 1, 0, 0, 0, 56, 57, 1, 0, 0, 0, 57, 9, 1, 0, 0, 0, 12, 12, 16, 18, 23, 26, 30, 33, 36, 42, 48, 52, 56] \ No newline at end of file +[4, 1, 4, 61, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 1, 0, 1, 0, 3, 0, 13, 8, 0, 1, 0, 1, 0, 3, 0, 17, 8, 0, 3, 0, 19, 8, 0, 1, 0, 1, 0, 1, 1, 3, 1, 24, 8, 1, 1, 1, 3, 1, 27, 8, 1, 1, 1, 3, 1, 30, 8, 1, 1, 1, 3, 1, 33, 8, 1, 1, 1, 3, 1, 36, 8, 1, 1, 1, 3, 1, 39, 8, 1, 1, 2, 1, 2, 1, 3, 1, 3, 3, 3, 45, 8, 3, 1, 3, 1, 3, 1, 4, 1, 4, 3, 4, 51, 8, 4, 1, 4, 1, 4, 3, 4, 55, 8, 4, 4, 4, 57, 8, 4, 11, 4, 12, 4, 58, 1, 4, 0, 0, 5, 0, 2, 4, 6, 8, 0, 0, 69, 0, 18, 1, 0, 0, 0, 2, 23, 1, 0, 0, 0, 4, 40, 1, 0, 0, 0, 6, 44, 1, 0, 0, 0, 8, 48, 1, 0, 0, 0, 10, 19, 3, 2, 1, 0, 11, 13, 5, 2, 0, 0, 12, 11, 1, 0, 0, 0, 12, 13, 1, 0, 0, 0, 13, 14, 1, 0, 0, 0, 14, 19, 3, 8, 4, 0, 15, 17, 5, 2, 0, 0, 16, 15, 1, 0, 0, 0, 16, 17, 1, 0, 0, 0, 17, 19, 1, 0, 0, 0, 18, 10, 1, 0, 0, 0, 18, 12, 1, 0, 0, 0, 18, 16, 1, 0, 0, 0, 19, 20, 1, 0, 0, 0, 20, 21, 5, 0, 0, 1, 21, 1, 1, 0, 0, 0, 22, 24, 5, 2, 0, 0, 23, 22, 1, 0, 0, 0, 23, 24, 1, 0, 0, 0, 24, 26, 1, 0, 0, 0, 25, 27, 3, 4, 2, 0, 26, 25, 1, 0, 0, 0, 26, 27, 1, 0, 0, 0, 27, 29, 1, 0, 0, 0, 28, 30, 5, 2, 0, 0, 29, 28, 1, 0, 0, 0, 29, 30, 1, 0, 0, 0, 30, 32, 1, 0, 0, 0, 31, 33, 3, 6, 3, 0, 32, 31, 1, 0, 0, 0, 32, 33, 1, 0, 0, 0, 33, 35, 1, 0, 0, 0, 34, 36, 5, 2, 0, 0, 35, 34, 1, 0, 0, 0, 35, 36, 1, 0, 0, 0, 36, 38, 1, 0, 0, 0, 37, 39, 3, 8, 4, 0, 38, 37, 1, 0, 0, 0, 38, 39, 1, 0, 0, 0, 39, 3, 1, 0, 0, 0, 40, 41, 5, 3, 0, 0, 41, 5, 1, 0, 0, 0, 42, 43, 5, 3, 0, 0, 43, 45, 5, 2, 0, 0, 44, 42, 1, 0, 0, 0, 44, 45, 1, 0, 0, 0, 45, 46, 1, 0, 0, 0, 46, 47, 5, 3, 0, 0, 47, 7, 1, 0, 0, 0, 48, 50, 5, 1, 0, 0, 49, 51, 5, 2, 0, 0, 50, 49, 1, 0, 0, 0, 50, 51, 1, 0, 0, 0, 51, 56, 1, 0, 0, 0, 52, 54, 5, 3, 0, 0, 53, 55, 5, 2, 0, 0, 54, 53, 1, 0, 0, 0, 54, 55, 1, 0, 0, 0, 55, 57, 1, 0, 0, 0, 56, 52, 1, 0, 0, 0, 57, 58, 1, 0, 0, 0, 58, 56, 1, 0, 0, 0, 58, 59, 1, 0, 0, 0, 59, 9, 1, 0, 0, 0, 13, 12, 16, 18, 23, 26, 29, 32, 35, 38, 44, 50, 54, 58] \ No newline at end of file diff --git a/handlers/sshd_config/ast/parser/config_parser.go b/handlers/sshd_config/ast/parser/config_parser.go index dbfca6f..bd05590 100644 --- a/handlers/sshd_config/ast/parser/config_parser.go +++ b/handlers/sshd_config/ast/parser/config_parser.go @@ -43,32 +43,33 @@ func configParserInit() { } staticData.PredictionContextCache = antlr.NewPredictionContextCache() staticData.serializedATN = []int32{ - 4, 1, 4, 59, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, + 4, 1, 4, 61, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 1, 0, 1, 0, 3, 0, 13, 8, 0, 1, 0, 1, 0, 3, 0, 17, 8, 0, 3, 0, 19, 8, 0, - 1, 0, 1, 0, 1, 1, 3, 1, 24, 8, 1, 1, 1, 3, 1, 27, 8, 1, 1, 1, 1, 1, 3, - 1, 31, 8, 1, 1, 1, 3, 1, 34, 8, 1, 1, 1, 3, 1, 37, 8, 1, 1, 2, 1, 2, 1, - 3, 1, 3, 3, 3, 43, 8, 3, 1, 3, 1, 3, 1, 4, 1, 4, 3, 4, 49, 8, 4, 1, 4, - 1, 4, 3, 4, 53, 8, 4, 4, 4, 55, 8, 4, 11, 4, 12, 4, 56, 1, 4, 0, 0, 5, - 0, 2, 4, 6, 8, 0, 0, 66, 0, 18, 1, 0, 0, 0, 2, 23, 1, 0, 0, 0, 4, 38, 1, - 0, 0, 0, 6, 42, 1, 0, 0, 0, 8, 46, 1, 0, 0, 0, 10, 19, 3, 2, 1, 0, 11, - 13, 5, 2, 0, 0, 12, 11, 1, 0, 0, 0, 12, 13, 1, 0, 0, 0, 13, 14, 1, 0, 0, - 0, 14, 19, 3, 8, 4, 0, 15, 17, 5, 2, 0, 0, 16, 15, 1, 0, 0, 0, 16, 17, - 1, 0, 0, 0, 17, 19, 1, 0, 0, 0, 18, 10, 1, 0, 0, 0, 18, 12, 1, 0, 0, 0, - 18, 16, 1, 0, 0, 0, 19, 20, 1, 0, 0, 0, 20, 21, 5, 0, 0, 1, 21, 1, 1, 0, - 0, 0, 22, 24, 5, 2, 0, 0, 23, 22, 1, 0, 0, 0, 23, 24, 1, 0, 0, 0, 24, 26, - 1, 0, 0, 0, 25, 27, 3, 4, 2, 0, 26, 25, 1, 0, 0, 0, 26, 27, 1, 0, 0, 0, - 27, 28, 1, 0, 0, 0, 28, 30, 5, 2, 0, 0, 29, 31, 3, 6, 3, 0, 30, 29, 1, - 0, 0, 0, 30, 31, 1, 0, 0, 0, 31, 33, 1, 0, 0, 0, 32, 34, 5, 2, 0, 0, 33, - 32, 1, 0, 0, 0, 33, 34, 1, 0, 0, 0, 34, 36, 1, 0, 0, 0, 35, 37, 3, 8, 4, - 0, 36, 35, 1, 0, 0, 0, 36, 37, 1, 0, 0, 0, 37, 3, 1, 0, 0, 0, 38, 39, 5, - 3, 0, 0, 39, 5, 1, 0, 0, 0, 40, 41, 5, 3, 0, 0, 41, 43, 5, 2, 0, 0, 42, - 40, 1, 0, 0, 0, 42, 43, 1, 0, 0, 0, 43, 44, 1, 0, 0, 0, 44, 45, 5, 3, 0, - 0, 45, 7, 1, 0, 0, 0, 46, 48, 5, 1, 0, 0, 47, 49, 5, 2, 0, 0, 48, 47, 1, - 0, 0, 0, 48, 49, 1, 0, 0, 0, 49, 54, 1, 0, 0, 0, 50, 52, 5, 3, 0, 0, 51, - 53, 5, 2, 0, 0, 52, 51, 1, 0, 0, 0, 52, 53, 1, 0, 0, 0, 53, 55, 1, 0, 0, - 0, 54, 50, 1, 0, 0, 0, 55, 56, 1, 0, 0, 0, 56, 54, 1, 0, 0, 0, 56, 57, - 1, 0, 0, 0, 57, 9, 1, 0, 0, 0, 12, 12, 16, 18, 23, 26, 30, 33, 36, 42, - 48, 52, 56, + 1, 0, 1, 0, 1, 1, 3, 1, 24, 8, 1, 1, 1, 3, 1, 27, 8, 1, 1, 1, 3, 1, 30, + 8, 1, 1, 1, 3, 1, 33, 8, 1, 1, 1, 3, 1, 36, 8, 1, 1, 1, 3, 1, 39, 8, 1, + 1, 2, 1, 2, 1, 3, 1, 3, 3, 3, 45, 8, 3, 1, 3, 1, 3, 1, 4, 1, 4, 3, 4, 51, + 8, 4, 1, 4, 1, 4, 3, 4, 55, 8, 4, 4, 4, 57, 8, 4, 11, 4, 12, 4, 58, 1, + 4, 0, 0, 5, 0, 2, 4, 6, 8, 0, 0, 69, 0, 18, 1, 0, 0, 0, 2, 23, 1, 0, 0, + 0, 4, 40, 1, 0, 0, 0, 6, 44, 1, 0, 0, 0, 8, 48, 1, 0, 0, 0, 10, 19, 3, + 2, 1, 0, 11, 13, 5, 2, 0, 0, 12, 11, 1, 0, 0, 0, 12, 13, 1, 0, 0, 0, 13, + 14, 1, 0, 0, 0, 14, 19, 3, 8, 4, 0, 15, 17, 5, 2, 0, 0, 16, 15, 1, 0, 0, + 0, 16, 17, 1, 0, 0, 0, 17, 19, 1, 0, 0, 0, 18, 10, 1, 0, 0, 0, 18, 12, + 1, 0, 0, 0, 18, 16, 1, 0, 0, 0, 19, 20, 1, 0, 0, 0, 20, 21, 5, 0, 0, 1, + 21, 1, 1, 0, 0, 0, 22, 24, 5, 2, 0, 0, 23, 22, 1, 0, 0, 0, 23, 24, 1, 0, + 0, 0, 24, 26, 1, 0, 0, 0, 25, 27, 3, 4, 2, 0, 26, 25, 1, 0, 0, 0, 26, 27, + 1, 0, 0, 0, 27, 29, 1, 0, 0, 0, 28, 30, 5, 2, 0, 0, 29, 28, 1, 0, 0, 0, + 29, 30, 1, 0, 0, 0, 30, 32, 1, 0, 0, 0, 31, 33, 3, 6, 3, 0, 32, 31, 1, + 0, 0, 0, 32, 33, 1, 0, 0, 0, 33, 35, 1, 0, 0, 0, 34, 36, 5, 2, 0, 0, 35, + 34, 1, 0, 0, 0, 35, 36, 1, 0, 0, 0, 36, 38, 1, 0, 0, 0, 37, 39, 3, 8, 4, + 0, 38, 37, 1, 0, 0, 0, 38, 39, 1, 0, 0, 0, 39, 3, 1, 0, 0, 0, 40, 41, 5, + 3, 0, 0, 41, 5, 1, 0, 0, 0, 42, 43, 5, 3, 0, 0, 43, 45, 5, 2, 0, 0, 44, + 42, 1, 0, 0, 0, 44, 45, 1, 0, 0, 0, 45, 46, 1, 0, 0, 0, 46, 47, 5, 3, 0, + 0, 47, 7, 1, 0, 0, 0, 48, 50, 5, 1, 0, 0, 49, 51, 5, 2, 0, 0, 50, 49, 1, + 0, 0, 0, 50, 51, 1, 0, 0, 0, 51, 56, 1, 0, 0, 0, 52, 54, 5, 3, 0, 0, 53, + 55, 5, 2, 0, 0, 54, 53, 1, 0, 0, 0, 54, 55, 1, 0, 0, 0, 55, 57, 1, 0, 0, + 0, 56, 52, 1, 0, 0, 0, 57, 58, 1, 0, 0, 0, 58, 56, 1, 0, 0, 0, 58, 59, + 1, 0, 0, 0, 59, 9, 1, 0, 0, 0, 13, 12, 16, 18, 23, 26, 29, 32, 35, 38, + 44, 50, 54, 58, } deserializer := antlr.NewATNDeserializer(nil) staticData.atn = deserializer.Deserialize(staticData.serializedATN) @@ -469,27 +470,33 @@ func (p *ConfigParser) Entry() (localctx IEntryContext) { } p.SetState(26) p.GetErrorHandler().Sync(p) - if p.HasError() { - goto errorExit - } - _la = p.GetTokenStream().LA(1) - if _la == ConfigParserSTRING { + if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 4, p.GetParserRuleContext()) == 1 { { p.SetState(25) p.Key() } + } else if p.HasError() { // JIM + goto errorExit } - { - p.SetState(28) - p.Match(ConfigParserWHITESPACE) - if p.HasError() { - // Recognition error - abort rule - goto errorExit + p.SetState(29) + p.GetErrorHandler().Sync(p) + + if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 5, p.GetParserRuleContext()) == 1 { + { + p.SetState(28) + p.Match(ConfigParserWHITESPACE) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } } + + } else if p.HasError() { // JIM + goto errorExit } - p.SetState(30) + p.SetState(32) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -498,12 +505,12 @@ func (p *ConfigParser) Entry() (localctx IEntryContext) { if _la == ConfigParserSTRING { { - p.SetState(29) + p.SetState(31) p.Value() } } - p.SetState(33) + p.SetState(35) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -512,7 +519,7 @@ func (p *ConfigParser) Entry() (localctx IEntryContext) { if _la == ConfigParserWHITESPACE { { - p.SetState(32) + p.SetState(34) p.Match(ConfigParserWHITESPACE) if p.HasError() { // Recognition error - abort rule @@ -521,7 +528,7 @@ func (p *ConfigParser) Entry() (localctx IEntryContext) { } } - p.SetState(36) + p.SetState(38) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -530,7 +537,7 @@ func (p *ConfigParser) Entry() (localctx IEntryContext) { if _la == ConfigParserHASH { { - p.SetState(35) + p.SetState(37) p.LeadingComment() } @@ -624,7 +631,7 @@ func (p *ConfigParser) Key() (localctx IKeyContext) { p.EnterRule(localctx, 4, ConfigParserRULE_key) p.EnterOuterAlt(localctx, 1) { - p.SetState(38) + p.SetState(40) p.Match(ConfigParserSTRING) if p.HasError() { // Recognition error - abort rule @@ -729,12 +736,12 @@ func (p *ConfigParser) Value() (localctx IValueContext) { localctx = NewValueContext(p, p.GetParserRuleContext(), p.GetState()) p.EnterRule(localctx, 6, ConfigParserRULE_value) p.EnterOuterAlt(localctx, 1) - p.SetState(42) + p.SetState(44) p.GetErrorHandler().Sync(p) - if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 8, p.GetParserRuleContext()) == 1 { + if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 9, p.GetParserRuleContext()) == 1 { { - p.SetState(40) + p.SetState(42) p.Match(ConfigParserSTRING) if p.HasError() { // Recognition error - abort rule @@ -742,7 +749,7 @@ func (p *ConfigParser) Value() (localctx IValueContext) { } } { - p.SetState(41) + p.SetState(43) p.Match(ConfigParserWHITESPACE) if p.HasError() { // Recognition error - abort rule @@ -754,7 +761,7 @@ func (p *ConfigParser) Value() (localctx IValueContext) { goto errorExit } { - p.SetState(44) + p.SetState(46) p.Match(ConfigParserSTRING) if p.HasError() { // Recognition error - abort rule @@ -872,14 +879,14 @@ func (p *ConfigParser) LeadingComment() (localctx ILeadingCommentContext) { p.EnterOuterAlt(localctx, 1) { - p.SetState(46) + p.SetState(48) p.Match(ConfigParserHASH) if p.HasError() { // Recognition error - abort rule goto errorExit } } - p.SetState(48) + p.SetState(50) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -888,7 +895,7 @@ func (p *ConfigParser) LeadingComment() (localctx ILeadingCommentContext) { if _la == ConfigParserWHITESPACE { { - p.SetState(47) + p.SetState(49) p.Match(ConfigParserWHITESPACE) if p.HasError() { // Recognition error - abort rule @@ -897,7 +904,7 @@ func (p *ConfigParser) LeadingComment() (localctx ILeadingCommentContext) { } } - p.SetState(54) + p.SetState(56) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -906,14 +913,14 @@ func (p *ConfigParser) LeadingComment() (localctx ILeadingCommentContext) { for ok := true; ok; ok = _la == ConfigParserSTRING { { - p.SetState(50) + p.SetState(52) p.Match(ConfigParserSTRING) if p.HasError() { // Recognition error - abort rule goto errorExit } } - p.SetState(52) + p.SetState(54) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -922,7 +929,7 @@ func (p *ConfigParser) LeadingComment() (localctx ILeadingCommentContext) { if _la == ConfigParserWHITESPACE { { - p.SetState(51) + p.SetState(53) p.Match(ConfigParserWHITESPACE) if p.HasError() { // Recognition error - abort rule @@ -932,7 +939,7 @@ func (p *ConfigParser) LeadingComment() (localctx ILeadingCommentContext) { } - p.SetState(56) + p.SetState(58) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit diff --git a/handlers/sshd_config/ast/parser_test.go b/handlers/sshd_config/ast/parser_test.go index 6f5d0a3..9ea5e09 100644 --- a/handlers/sshd_config/ast/parser_test.go +++ b/handlers/sshd_config/ast/parser_test.go @@ -157,6 +157,62 @@ Match 192.168.0.2 if !(sixthEntry.Key.Value == "MaxAuthTries" && sixthEntry.OptionValue.Value == "3") { t.Errorf("Expected sixth entry to be 'MaxAuthTries 3', but got: %v", sixthEntry.Value) } + + firstOption, firstMatchBlock := p.FindOption(uint32(4)) + + if !(firstOption.Key.Value == "PasswordAuthentication" && firstOption.OptionValue.Value == "yes" && firstMatchBlock.MatchEntry.Value == "Match 192.168.0.1") { + t.Errorf("Expected first option to be 'PasswordAuthentication yes' and first match block to be 'Match 192.168.0.1', but got: %v, %v", firstOption, firstMatchBlock) + } +} + +func TestSimpleExampleWithComments( + t *testing.T, +) { + input := utils.Dedent(` +# Test +PermitRootLogin no +Port 22 +# Second test +AddressFamily any +Sample +`) + p := NewSSHConfig() + errors := p.Parse(input) + + if len(errors) != 0 { + t.Fatalf("Expected no errors, got %v", errors) + } + + if !(p.Options.Size() == 4 && + len(utils.KeysOfMap(p.CommentLines)) == 2) { + t.Errorf("Expected 3 options and 2 comment lines, but got: %v, %v", p.Options, p.CommentLines) + } + + rawFirstEntry, _ := p.Options.Get(uint32(1)) + firstEntry := rawFirstEntry.(*SSHOption) + if !(firstEntry.Value == "PermitRootLogin no") { + t.Errorf("Expected first entry to be 'PermitRootLogin no', but got: %v", firstEntry.Value) + } + + if len(p.CommentLines) != 2 { + t.Errorf("Expected 2 comment lines, but got: %v", p.CommentLines) + } + + if !utils.KeyExists(p.CommentLines, uint32(0)) { + t.Errorf("Expected comment line 0 to not exist, but it does") + } + + if !(utils.KeyExists(p.CommentLines, uint32(3))) { + t.Errorf("Expected comment line 2 to exist, but it does not") + } + + rawSecondEntry, _ := p.Options.Get(uint32(5)) + secondEntry := rawSecondEntry.(*SSHOption) + + if !(secondEntry.Value == "Sample") { + t.Errorf("Expected second entry to be 'Sample', but got: %v", secondEntry.Value) + } + } func TestComplexExample( diff --git a/handlers/sshd_config/ast/sshd_config.go b/handlers/sshd_config/ast/sshd_config.go index 6364bb9..c75565c 100644 --- a/handlers/sshd_config/ast/sshd_config.go +++ b/handlers/sshd_config/ast/sshd_config.go @@ -57,3 +57,41 @@ type SSHConfig struct { // [uint32]{} -> line number -> {} CommentLines map[uint32]struct{} } + +func (c SSHConfig) FindMatchBlock(line uint32) *SSHMatchBlock { + for currentLine := line; currentLine > 0; currentLine-- { + rawEntry, found := c.Options.Get(currentLine) + + if !found { + continue + } + + switch entry := rawEntry.(type) { + case *SSHMatchBlock: + return entry + } + } + + return nil +} + +func (c SSHConfig) FindOption(line uint32) (*SSHOption, *SSHMatchBlock) { + matchBlock := c.FindMatchBlock(line) + + if matchBlock != nil { + rawEntry, found := matchBlock.Options.Get(line) + + if found { + return rawEntry.(*SSHOption), matchBlock + } + } + + rawEntry, found := c.Options.Get(line) + + if found { + return rawEntry.(*SSHOption), nil + } + + return nil, nil + +} diff --git a/handlers/sshd_config/fields/fields.go b/handlers/sshd_config/fields/fields.go index c75c8de..dc8b9d5 100644 --- a/handlers/sshd_config/fields/fields.go +++ b/handlers/sshd_config/fields/fields.go @@ -12,7 +12,7 @@ var MAX_FILE_MODE = 0777 var Options = map[string]docvalues.Value{ "AcceptEnv": docvalues.DocumentationValue{ Documentation: `Specifies what environment variables sent by the client will be copied into the session's environ(7). See SendEnv and SetEnv in ssh_config(5) for how to configure the client. The TERM environment variable is always accepted whenever the client requests a pseudo-terminal as it is required by the protocol. Variables are specified by name, which may contain the wildcard characters ‘*’ and ‘?’. Multiple environment variables may be separated by whitespace or spread across multiple AcceptEnv directives. Be warned that some environment variables could be used to bypass restricted user environments. For this reason, care should be taken in the use of this directive. The default is not to accept any environment variables.`, - Value: docvalues.StringValue{}, + Value: docvalues.StringValue{}, }, "AddressFamily": docvalues.DocumentationValue{ Documentation: `Specifies which address family should be used by sshd(8). Valid arguments are any (the default), inet (use IPv4 only), or inet6 (use IPv6 only).`, @@ -27,13 +27,13 @@ var Options = map[string]docvalues.Value{ }, "AllowAgentForwarding": docvalues.DocumentationValue{ Documentation: `Specifies whether ssh-agent(1) forwarding is permitted. The default is yes. Note that disabling agent forwarding does not improve security unless users are also denied shell access, as they can always install their own forwarders.`, - Value: booleanEnumValue, + Value: booleanEnumValue, }, "AllowGroups": docvalues.DocumentationValue{ Documentation: `This keyword can be followed by a list of group name patterns, separated by spaces. If specified, login is allowed only for users whose primary group or supplementary group list matches one of the patterns. Only group names are valid; a numerical group ID is not recognized. By default, login is allowed for all groups. The allow/deny groups directives are processed in the following order: DenyGroups, AllowGroups. See PATTERNS in ssh_config(5) for more information on patterns. This keyword may appear multiple times in sshd_config with each instance appending to the list.`, -Value: docvalues.GroupValue(" ", false), + Value: docvalues.GroupValue(" ", false), }, "AllowStreamLocalForwarding": docvalues.DocumentationValue{ Documentation: `Specifies whether StreamLocal (Unix-domain socket) forwarding is permitted. The available options are yes (the default) or all to allow StreamLocal forwarding, no to prevent all StreamLocal forwarding, local to allow local (from the perspective of ssh(1)) forwarding only or remote to allow remote forwarding only. Note that disabling StreamLocal forwarding does not improve security unless users are also denied shell access, as they can always install their own forwarders.`, @@ -64,7 +64,7 @@ Value: docvalues.GroupValue(" ", false), "AllowUsers": docvalues.DocumentationValue{ Documentation: `This keyword can be followed by a list of user name patterns, separated by spaces. If specified, login is allowed only for user names that match one of the patterns. Only user names are valid; a numerical user ID is not recognized. By default, login is allowed for all users. If the pattern takes the form USER@HOST then USER and HOST are separately checked, restricting logins to particular users from particular hosts. HOST criteria may additionally contain addresses to match in CIDR address/masklen format. The allow/deny users directives are processed in the following order: DenyUsers, AllowUsers. See PATTERNS in ssh_config(5) for more information on patterns. This keyword may appear multiple times in sshd_config with each instance appending to the list.`, - Value: docvalues.UserValue(" ", false), + Value: docvalues.UserValue(" ", false), }, "AuthenticationMethods": docvalues.DocumentationValue{ Documentation: `Specifies the authentication methods that must be successfully completed for a user to be granted access. This option must be followed by one or more lists of comma-separated authentication method names, or by the single string any to indicate the default behaviour of accepting any single authentication method. If the default is overridden, then successful authentication requires completion of every method in at least one of these lists. @@ -73,7 +73,7 @@ Value: docvalues.GroupValue(" ", false), If the publickey method is listed more than once, sshd(8) verifies that keys that have been used successfully are not reused for subsequent authentications. For example, "publickey,publickey" requires successful authentication using two different public keys.PATTERNS Note that each authentication method listed should also be explicitly enabled in the configuration. The available authentication methods are: "gssapi-with-mic", "hostbased", "keyboard-interactive", "none" (used for access to password-less accounts when PermitEmptyPasswords is enabled), "password" and "publickey".`, - Value: docvalues.OrValue{ + Value: docvalues.OrValue{ Values: []docvalues.Value{ docvalues.EnumValue{ EnforceValues: true, @@ -113,12 +113,12 @@ Value: docvalues.GroupValue(" ", false), "AuthorizedKeysCommand": docvalues.DocumentationValue{ Documentation: `Specifies a program to be used to look up the user's public keys. The program must be owned by root, not writable by group or others and specified by an absolute path. Arguments to AuthorizedKeysCommand accept the tokens described in the “TOKENS” section. If no arguments are specified then the username of the target user is used. The program should produce on standard output zero or more lines of authorized_keys output (see “AUTHORIZED_KEYS” in sshd(8)). AuthorizedKeysCommand is tried after the usual AuthorizedKeysFile files and will not be executed if a matching key is found there. By default, no AuthorizedKeysCommand is run.`, - Value: docvalues.StringValue{}, + Value: docvalues.StringValue{}, }, "AuthorizedKeysCommandUser": docvalues.DocumentationValue{ Documentation: `Specifies the user under whose account the AuthorizedKeysCommand is run. It is recommended to use a dedicated user that has no other role on the host than running authorized keys commands. If AuthorizedKeysCommand is specified but AuthorizedKeysCommandUser is not, then sshd(8) will refuse to start.`, - Value: docvalues.UserValue("", true), + Value: docvalues.UserValue("", true), }, "AuthorizedKeysFile": docvalues.DocumentationValue{ Documentation: `Specifies the file that contains the public keys used for user authentication. The format is described in the AUTHORIZED_KEYS FILE FORMAT section of sshd(8). Arguments to AuthorizedKeysFile accept the tokens described in the “TOKENS” section. After expansion, AuthorizedKeysFile is taken to be an absolute path or one relative to the user's home directory. Multiple files may be listed, separated by whitespace. Alternately this option may be set to none to skip checking for user keys in files. The default is ".ssh/authorized_keys .ssh/authorized_keys2".`, @@ -131,17 +131,17 @@ Value: docvalues.GroupValue(" ", false), "AuthorizedPrincipalsCommand": docvalues.DocumentationValue{ Documentation: `Specifies a program to be used to generate the list of allowed certificate principals as per AuthorizedPrincipalsFile. The program must be owned by root, not writable by group or others and specified by an absolute path. Arguments to AuthorizedPrincipalsCommand accept the tokens described in the “TOKENS” section. If no arguments are specified then the username of the target user is used. The program should produce on standard output zero or more lines of AuthorizedPrincipalsFile output. If either AuthorizedPrincipalsCommand or AuthorizedPrincipalsFile is specified, then certificates offered by the client for authentication must contain a principal that is listed. By default, no AuthorizedPrincipalsCommand is run.`, - Value: docvalues.StringValue{}, + Value: docvalues.StringValue{}, }, "AuthorizedPrincipalsCommandUser": docvalues.DocumentationValue{ Documentation: `Specifies the user under whose account the AuthorizedPrincipalsCommand is run. It is recommended to use a dedicated user that has no other role on the host than running authorized principals commands. If AuthorizedPrincipalsCommand is specified but AuthorizedPrincipalsCommandUser is not, then sshd(8) will refuse to start.`, - Value: docvalues.UserValue("", true), + Value: docvalues.UserValue("", true), }, "AuthorizedPrincipalsFile": docvalues.DocumentationValue{ Documentation: `Specifies a file that lists principal names that are accepted for certificate authentication. When using certificates signed by a key listed in TrustedUserCAKeys, this file lists names, one of which must appear in the certificate for it to be accepted for authentication. Names are listed one per line preceded by key options (as described in “AUTHORIZED_KEYS FILE FORMAT” in sshd(8)). Empty lines and comments starting with ‘#’ are ignored. Arguments to AuthorizedPrincipalsFile accept the tokens described in the “TOKENS” section. After expansion, AuthorizedPrincipalsFile is taken to be an absolute path or one relative to the user's home directory. The default is none, i.e. not to use a principals file – in this case, the username of the user must appear in a certificate's principals list for it to be accepted. Note that AuthorizedPrincipalsFile is only used when authentication proceeds using a CA listed in TrustedUserCAKeys and is not consulted for certification authorities trusted via ~/.ssh/authorized_keys, though the principals= key option offers a similar facility (see sshd(8) for details).`, - Value: docvalues.PathValue{ + Value: docvalues.PathValue{ RequiredType: docvalues.PathTypeFile, }, }, @@ -156,7 +156,7 @@ Value: docvalues.GroupValue(" ", false), ssh-ed25519,ecdsa-sha2-nistp256, ecdsa-sha2-nistp384,ecdsa-sha2-nistp521, sk-ssh-ed25519@openssh.com, sk-ecdsa-sha2-nistp256@openssh.com, rsa-sha2-512,rsa-sha2-256 If the specified list begins with a ‘+’ character, then the specified algorithms will be appended to the default set instead of replacing them. If the specified list begins with a ‘-’ character, then the specified algorithms (including wildcards) will be removed from the default set instead of replacing them. Certificates signed using other algorithms will not be accepted for public key or host-based authentication.`, - Value: docvalues.PrefixWithMeaningValue{ + Value: docvalues.PrefixWithMeaningValue{ Prefixes: []docvalues.Prefix{ { Prefix: "+", @@ -191,7 +191,7 @@ Value: docvalues.GroupValue(" ", false), Note that in all the above cases, terminating an inactive session does not guarantee to remove all resources associated with the session, e.g. shell processes or X11 clients relating to the session may continue to execute. Moreover, terminating an inactive channel or session does not necessarily close the SSH connection, nor does it prevent a client from requesting another channel of the same type. In particular, expiring an inactive forwarding session does not prevent another identical forwarding from being subsequently created. The default is not to expire channels of any type for inactivity.`, - Value: docvalues.ArrayValue{ + Value: docvalues.ArrayValue{ Separator: " ", DuplicatesExtractor: &channelTimeoutExtractor, SubValue: docvalues.KeyValueAssignmentValue{ @@ -219,7 +219,7 @@ Value: docvalues.GroupValue(" ", false), The ChrootDirectory must contain the necessary files and directories to support the user's session. For an interactive session this requires at least a shell, typically sh(1), and basic /dev nodes such as null(4), zero(4), stdin(4), stdout(4), stderr(4), and tty(4) devices. For file transfer sessions using SFTP no additional configuration of the environment is necessary if the in-process sftp-server is used, though sessions which use logging may require /dev/log inside the chroot directory on some operating systems (see sftp-server(8) for details). For safety, it is very important that the directory hierarchy be prevented from modification by other processes on the system (especially those outside the jail). Misconfiguration can lead to unsafe environments which sshd(8) cannot detect. The default is none, indicating not to chroot(2).`, - Value: docvalues.StringValue{}, + Value: docvalues.StringValue{}, }, "Ciphers": docvalues.DocumentationValue{ Documentation: `Specifies the ciphers allowed. Multiple ciphers must be comma-separated. If the specified list begins with a ‘+’ character, then the specified ciphers will be appended to the default set instead of replacing them. If the specified list begins with a ‘-’ character, then the specified ciphers (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a ‘^’ character, then the specified ciphers will be placed at the head of the default set. @@ -228,7 +228,7 @@ Value: docvalues.GroupValue(" ", false), The default is: chacha20-poly1305@openssh.com, aes128-ctr,aes192-ctr,aes256-ctr, aes128-gcm@openssh.com,aes256-gcm@openssh.com The list of available ciphers may also be obtained using "ssh -Q cipher".`, - Value: prefixPlusMinusCaret([]docvalues.EnumString{ + Value: prefixPlusMinusCaret([]docvalues.EnumString{ docvalues.CreateEnumString("3des-cbc"), docvalues.CreateEnumString("aes128-cbc"), docvalues.CreateEnumString("aes192-cbc"), @@ -244,11 +244,11 @@ Value: docvalues.GroupValue(" ", false), "ClientAliveCountMax": docvalues.DocumentationValue{ Documentation: `Sets the number of client alive messages which may be sent without sshd(8) receiving any messages back from the client. If this threshold is reached while client alive messages are being sent, sshd will disconnect the client, terminating the session. It is important to note that the use of client alive messages is very different from TCPKeepAlive. The client alive messages are sent through the encrypted channel and therefore will not be spoofable. The TCP keepalive option enabled by TCPKeepAlive is spoofable. The client alive mechanism is valuable when the client or server depend on knowing when a connection has become unresponsive. The default value is 3. If ClientAliveInterval is set to 15, and ClientAliveCountMax is left at the default, unresponsive SSH clients will be disconnected after approximately 45 seconds. Setting a zero ClientAliveCountMax disables connection termination.`, - Value: docvalues.NumberValue{Min: &ZERO}, + Value: docvalues.NumberValue{Min: &ZERO}, }, "ClientAliveInterval": docvalues.DocumentationValue{ Documentation: `Sets a timeout interval in seconds after which if no data has been received from the client, sshd(8) will send a message through the encrypted channel to request a response from the client. The default is 0, indicating that these messages will not be sent to the client.`, - Value: docvalues.NumberValue{Min: &ZERO}, + Value: docvalues.NumberValue{Min: &ZERO}, }, "Compression": docvalues.DocumentationValue{ Documentation: `Specifies whether compression is enabled after the user has authenticated successfully. The argument must be yes, delayed (a legacy synonym for yes) or no. The default is yes.`, @@ -264,20 +264,20 @@ Value: docvalues.GroupValue(" ", false), "DenyGroups": docvalues.DocumentationValue{ Documentation: `This keyword can be followed by a list of group name patterns, separated by spaces. Login is disallowed for users whose primary group or supplementary group list matches one of the patterns. Only group names are valid; a numerical group ID is not recognized. By default, login is allowed for all groups. The allow/deny groups directives are processed in the following order: DenyGroups, AllowGroups. See PATTERNS in ssh_config(5) for more information on patterns. This keyword may appear multiple times in sshd_config with each instance appending to the list.`, - Value: docvalues.GroupValue(" ", false), + Value: docvalues.GroupValue(" ", false), }, "DenyUsers": docvalues.DocumentationValue{ Documentation: `This keyword can be followed by a list of user name patterns, separated by spaces. Login is disallowed for user names that match one of the patterns. Only user names are valid; a numerical user ID is not recognized. By default, login is allowed for all users. If the pattern takes the form USER@HOST then USER and HOST are separately checked, restricting logins to particular users from particular hosts. HOST criteria may additionally contain addresses to match in CIDR address/masklen format. The allow/deny users directives are processed in the following order: DenyUsers, AllowUsers. See PATTERNS in ssh_config(5) for more information on patterns. This keyword may appear multiple times in sshd_config with each instance appending to the list.`, - Value: docvalues.UserValue(" ", false), + Value: docvalues.UserValue(" ", false), }, "DisableForwarding": docvalues.DocumentationValue{ Documentation: `Disables all forwarding features, including X11, ssh-agent(1), TCP and StreamLocal. This option overrides all other forwarding-related options and may simplify restricted configurations.`, - Value: booleanEnumValue, + Value: booleanEnumValue, }, "ExposeAuthInfo": docvalues.DocumentationValue{ Documentation: `Writes a temporary file containing a list of authentication methods and public credentials (e.g. keys) used to authenticate the user. The location of the file is exposed to the user session through the SSH_USER_AUTH environment variable. The default is no.`, - Value: booleanEnumValue, + Value: booleanEnumValue, }, "FingerprintHash": docvalues.DocumentationValue{ Documentation: `Specifies the hash algorithm used when logging key fingerprints. Valid options are: md5 and sha256. The default is sha256.`, @@ -291,29 +291,29 @@ Value: docvalues.GroupValue(" ", false), }, "ForceCommand": docvalues.DocumentationValue{ Documentation: `Forces the execution of the command specified by ForceCommand, ignoring any command supplied by the client and ~/.ssh/rc if present. The command is invoked by using the user's login shell with the -c option. This applies to shell, command, or subsystem execution. It is most useful inside a Match block. The command originally supplied by the client is available in the SSH_ORIGINAL_COMMAND environment variable. Specifying a command of internal-sftp will force the use of an in- process SFTP server that requires no support files when used with ChrootDirectory. The default is none.`, - Value: docvalues.StringValue{}, + Value: docvalues.StringValue{}, }, "GatewayPorts": docvalues.DocumentationValue{ Documentation: `Specifies whether remote hosts are allowed to connect to ports forwarded for the client. By default, sshd(8) binds remote port forwardings to the loopback address. This prevents other remote hosts from connecting to forwarded ports. GatewayPorts can be used to specify that sshd should allow remote port forwardings to bind to non-loopback addresses, thus allowing other hosts to connect. The argument may be no to force remote port forwardings to be available to the local host only, yes to force remote port forwardings to bind to the wildcard address, or clientspecified to allow the client to select the address to which the forwarding is bound. The default is no.`, - Value: booleanEnumValue, + Value: booleanEnumValue, }, "GSSAPIAuthentication": docvalues.DocumentationValue{ Documentation: `Specifies whether user authentication based on GSSAPI is allowed. The default is no.`, - Value: booleanEnumValue, + Value: booleanEnumValue, }, "GSSAPICleanupCredentials": docvalues.DocumentationValue{ Documentation: `Specifies whether to automatically destroy the user's credentials cache on logout. The default is yes.`, - Value: booleanEnumValue, + Value: booleanEnumValue, }, "GSSAPIStrictAcceptorCheck": docvalues.DocumentationValue{ Documentation: `Determines whether to be strict about the identity of the GSSAPI acceptor a client authenticates against. If set to yes then the client must authenticate against the host service on the current hostname. If set to no then the client may authenticate against any service key stored in the machine's default store. This facility is provided to assist with operation on multi homed machines. The default is yes.`, - Value: booleanEnumValue, + Value: booleanEnumValue, }, "HostbasedAcceptedAlgorithms": docvalues.DocumentationValue{ Documentation: `Specifies the signature algorithms that will be accepted for hostbased authentication as a list of comma-separated patterns. Alternately if the specified list begins with a ‘+’ character, then the specified signature algorithms will be appended to the default set instead of replacing them. If the specified list begins with a ‘-’ character, then the specified signature algorithms (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a ‘^’ character, then the specified signature algorithms will be placed at the head of the default set. The default for this option is: ssh-ed25519-cert-v01@openssh.com, ecdsa-sha2-nistp256-cert-v01@openssh.com, ecdsa-sha2-nistp384-cert-v01@openssh.com, ecdsa-sha2-nistp521-cert-v01@openssh.com, sk-ssh-ed25519-cert-v01@openssh.com, sk-ecdsa-sha2-nistp256-cert-v01@openssh.com, rsa-sha2-512-cert-v01@openssh.com, rsa-sha2-256-cert-v01@openssh.com, ssh-ed25519, ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521, sk-ssh-ed25519@openssh.com, sk-ecdsa-sha2-nistp256@openssh.com, rsa-sha2-512,rsa-sha2-256 The list of available signature algorithms may also be obtained using "ssh -Q HostbasedAcceptedAlgorithms". This was formerly named HostbasedAcceptedKeyTypes.`, - Value: docvalues.CustomValue{ + Value: docvalues.CustomValue{ FetchValue: func(_ docvalues.CustomValueContext) docvalues.Value { options, err := queryOpenSSHOptions("HostbasedAcceptedAlgorithms") @@ -328,21 +328,21 @@ Value: docvalues.GroupValue(" ", false), }, "HostbasedAuthentication": docvalues.DocumentationValue{ Documentation: `Specifies whether rhosts or /etc/hosts.equiv authentication together with successful public key client host authentication is allowed (host-based authentication). The default is no.`, - Value: booleanEnumValue, + Value: booleanEnumValue, }, "HostbasedUsesNameFromPacketOnly": docvalues.DocumentationValue{ Documentation: `Specifies whether or not the server will attempt to perform a reverse name lookup when matching the name in the ~/.shosts, ~/.rhosts, and /etc/hosts.equiv files during HostbasedAuthentication. A setting of yes means that sshd(8) uses the name supplied by the client rather than attempting to resolve the name from the TCP connection itself. The default is no.`, - Value: booleanEnumValue, + Value: booleanEnumValue, }, "HostCertificate": docvalues.DocumentationValue{ Documentation: `Specifies a file containing a public host certificate. The certificate's public key must match a private host key already specified by HostKey. The default behaviour of sshd(8) is not to load any certificates.`, - Value: docvalues.PathValue{}, + Value: docvalues.PathValue{}, }, "HostKey": docvalues.DocumentationValue{ Documentation: `Specifies a file containing a private host key used by SSH. The defaults are /etc/ssh/ssh_host_ecdsa_key, /etc/ssh/ssh_host_ed25519_key and /etc/ssh/ssh_host_rsa_key. Note that sshd(8) will refuse to use a file if it is group/world-accessible and that the HostKeyAlgorithms option restricts which of the keys are actually used by sshd(8). It is possible to have multiple host key files. It is also possible to specify public host key files instead. In this case operations on the private key will be delegated to an ssh-agent(1).`, - Value: docvalues.PathValue{}, + Value: docvalues.PathValue{}, }, "HostKeyAgent": docvalues.DocumentationValue{ Documentation: `Identifies the UNIX-domain socket used to communicate with an agent that has access to the private host keys. If the string "SSH_AUTH_SOCK" is specified, the location of the socket will be read from the SSH_AUTH_SOCK environment variable.`, @@ -362,7 +362,7 @@ Value: docvalues.GroupValue(" ", false), Documentation: `Specifies the host key signature algorithms that the server offers. The default for this option is: ssh-ed25519-cert-v01@openssh.com, ecdsa-sha2-nistp256-cert-v01@openssh.com, ecdsa-sha2-nistp384-cert-v01@openssh.com, ecdsa-sha2-nistp521-cert-v01@openssh.com, sk-ssh-ed25519-cert-v01@openssh.com, sk-ecdsa-sha2-nistp256-cert-v01@openssh.com, rsa-sha2-512-cert-v01@openssh.com, rsa-sha2-256-cert-v01@openssh.com, ssh-ed25519, ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521, sk-ssh-ed25519@openssh.com, sk-ecdsa-sha2-nistp256@openssh.com, rsa-sha2-512,rsa-sha2-256 The list of available signature algorithms may also be obtained using "ssh -Q HostKeyAlgorithms".`, - Value: docvalues.CustomValue{ + Value: docvalues.CustomValue{ FetchValue: func(_ docvalues.CustomValueContext) docvalues.Value { options, _ := queryOpenSSHOptions("HostKeyAlgorithms") @@ -373,7 +373,7 @@ Value: docvalues.GroupValue(" ", false), "IgnoreRhosts": docvalues.DocumentationValue{ Documentation: `Specifies whether to ignore per-user .rhosts and .shosts files during HostbasedAuthentication. The system-wide /etc/hosts.equiv and /etc/shosts.equiv are still used regardless of this setting. Accepted values are yes (the default) to ignore all per- user files, shosts-only to allow the use of .shosts but to ignore .rhosts or no to allow both .shosts and rhosts.`, - Value: docvalues.EnumValue{ + Value: docvalues.EnumValue{ EnforceValues: true, Values: []docvalues.EnumString{ docvalues.CreateEnumString("yes"), @@ -384,7 +384,7 @@ Value: docvalues.GroupValue(" ", false), }, "IgnoreUserKnownHosts": docvalues.DocumentationValue{ Documentation: `Specifies whether sshd(8) should ignore the user's ~/.ssh/known_hosts during HostbasedAuthentication and use only the system-wide known hosts file /etc/ssh/ssh_known_hosts. The default is “no”.`, - Value: booleanEnumValue, + Value: booleanEnumValue, }, "Include": docvalues.DocumentationValue{ Documentation: `Include the specified configuration file(s). Multiple pathnames may be specified and each pathname may contain glob(7) wildcards that will be expanded and processed in lexical order. Files without absolute paths are assumed to be in /etc/ssh. An Include directive may appear inside a Match block to perform conditional inclusion.`, @@ -447,23 +447,23 @@ Value: docvalues.GroupValue(" ", false), }, "KbdInteractiveAuthentication": docvalues.DocumentationValue{ Documentation: `Specifies whether to allow keyboard-interactive authentication. All authentication styles from login.conf(5) are supported. The default is yes. The argument to this keyword must be yes or no. ChallengeResponseAuthentication is a deprecated alias for this.`, - Value: booleanEnumValue, + Value: booleanEnumValue, }, "KerberosAuthentication": docvalues.DocumentationValue{ Documentation: `Specifies whether the password provided by the user for PasswordAuthentication will be validated through the Kerberos KDC. To use this option, the server needs a Kerberos servtab which allows the verification of the KDC's identity. The default is no.`, - Value: booleanEnumValue, + Value: booleanEnumValue, }, "KerberosGetAFSToken": docvalues.DocumentationValue{ Documentation: `If AFS is active and the user has a Kerberos 5 TGT, attempt to acquire an AFS token before accessing the user's home directory. The default is no.`, - Value: booleanEnumValue, + Value: booleanEnumValue, }, "KerberosOrLocalPasswd": docvalues.DocumentationValue{ Documentation: `If password authentication through Kerberos fails then the password will be validated via any additional local mechanism such as /etc/passwd. The default is yes.`, - Value: booleanEnumValue, + Value: booleanEnumValue, }, "KerberosTicketCleanup": docvalues.DocumentationValue{ Documentation: `Specifies whether to automatically destroy the user's ticket cache file on logout. The default is yes.`, - Value: booleanEnumValue, + Value: booleanEnumValue, }, "KexAlgorithms": docvalues.DocumentationValue{ Documentation: `Specifies the available KEX (Key Exchange) algorithms. Multiple algorithms must be comma-separated. Alternately if the specified list begins with a ‘+’ character, then the specified algorithms will be appended to the default set instead of replacing them. If the specified list begins with a ‘-’ character, then the specified algorithms (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a ‘^’ character, then the specified algorithms will be placed at the head of the default set. The supported algorithms are: @@ -471,7 +471,7 @@ Value: docvalues.GroupValue(" ", false), The default is: sntrup761x25519-sha512@openssh.com, curve25519-sha256,curve25519-sha256@libssh.org, ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521, diffie-hellman-group-exchange-sha256, diffie-hellman-group16-sha512,diffie-hellman-group18-sha512, diffie-hellman-group14-sha256 The list of available key exchange algorithms may also be obtained using "ssh -Q KexAlgorithms".`, - Value: prefixPlusMinusCaret([]docvalues.EnumString{ + Value: prefixPlusMinusCaret([]docvalues.EnumString{ docvalues.CreateEnumString("curve25519-sha256"), docvalues.CreateEnumString("curve25519-sha256@libssh.org"), docvalues.CreateEnumString("diffie-hellman-group1-sha1"), @@ -491,7 +491,7 @@ Value: docvalues.GroupValue(" ", false), Documentation: `Specifies the local addresses sshd(8) should listen on. The following forms may be used: ListenAddress hostname|address [rdomain domain] ListenAddress hostname:port [rdomain domain] ListenAddress IPv4_address:port [rdomain domain] ListenAddress [hostname|address]:port [rdomain domain] The optional rdomain qualifier requests sshd(8) listen in an explicit routing domain. If port is not specified, sshd will listen on the address and all Port options specified. The default is to listen on all local addresses on the current default routing domain. Multiple ListenAddress options are permitted. For more information on routing domains, see rdomain(4).`, - Value: docvalues.KeyValueAssignmentValue{ + Value: docvalues.KeyValueAssignmentValue{ ValueIsOptional: true, Key: docvalues.IPAddressValue{ AllowIPv4: true, @@ -505,7 +505,7 @@ Value: docvalues.GroupValue(" ", false), }, "LoginGraceTime": docvalues.DocumentationValue{ Documentation: `The server disconnects after this time if the user has not successfully logged in. If the value is 0, there is no time limit. The default is 120 seconds.`, - Value: TimeFormatValue{}, + Value: TimeFormatValue{}, }, "LogLevel": docvalues.DocumentationValue{ Documentation: `Gives the verbosity level that is used when logging messages from sshd(8). The possible values are: QUIET, FATAL, ERROR, INFO, VERBOSE, DEBUG, DEBUG1, DEBUG2, and DEBUG3. The default is INFO. DEBUG and DEBUG1 are equivalent. DEBUG2 and DEBUG3 each specify higher levels of debugging output. Logging with a DEBUG level violates the privacy of users and is not recommended.`, @@ -528,7 +528,7 @@ Value: docvalues.GroupValue(" ", false), Documentation: `Specify one or more overrides to LogLevel. An override consists of a pattern lists that matches the source file, function and line number to force detailed logging for. For example, an override pattern of: kex.c:*:1000,*:kex_exchange_identification():*,packet.c:* would enable detailed logging for line 1000 of kex.c, everything in the kex_exchange_identification() function, and all code in the packet.c file. This option is intended for debugging and no overrides are enabled by default.`, - Value: docvalues.StringValue{}, + Value: docvalues.StringValue{}, }, "MACs": docvalues.DocumentationValue{ @@ -538,7 +538,7 @@ Value: docvalues.GroupValue(" ", false), The default is: umac-64-etm@openssh.com,umac-128-etm@openssh.com, hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com, hmac-sha1-etm@openssh.com, umac-64@openssh.com,umac-128@openssh.com, hmac-sha2-256,hmac-sha2-512,hmac-sha1 The list of available MAC algorithms may also be obtained using "ssh -Q mac".`, - Value: prefixPlusMinusCaret([]docvalues.EnumString{ + Value: prefixPlusMinusCaret([]docvalues.EnumString{ docvalues.CreateEnumString("hmac-md5"), docvalues.CreateEnumString("hmac-md5-96"), docvalues.CreateEnumString("hmac-sha1"), @@ -566,11 +566,11 @@ Value: docvalues.GroupValue(" ", false), // Only a subset of keywords may be used on the lines following a Match keyword. Available keywords are AcceptEnv, AllowAgentForwarding, AllowGroups, AllowStreamLocalForwarding, AllowTcpForwarding, AllowUsers, AuthenticationMethods, AuthorizedKeysCommand, AuthorizedKeysCommandUser, AuthorizedKeysFile, AuthorizedPrincipalsCommand, AuthorizedPrincipalsCommandUser, AuthorizedPrincipalsFile, Banner, CASignatureAlgorithms, ChannelTimeout, ChrootDirectory, ClientAliveCountMax, ClientAliveInterval, DenyGroups, DenyUsers, DisableForwarding, ExposeAuthInfo, ForceCommand, GatewayPorts, GSSAPIAuthentication, HostbasedAcceptedAlgorithms, HostbasedAuthentication, HostbasedUsesNameFromPacketOnly, IgnoreRhosts, Include, IPQoS, KbdInteractiveAuthentication, KerberosAuthentication, LogLevel, MaxAuthTries, MaxSessions, PasswordAuthentication, PermitEmptyPasswords, PermitListen, PermitOpen, PermitRootLogin, PermitTTY, PermitTunnel, PermitUserRC, PubkeyAcceptedAlgorithms, PubkeyAuthentication, PubkeyAuthOptions, RekeyLimit, RevokedKeys, RDomain, SetEnv, StreamLocalBindMask, StreamLocalBindUnlink, TrustedUserCAKeys, UnusedConnectionTimeout, X11DisplayOffset, X11Forwarding and X11UseLocalhost.`, "MaxAuthTries": docvalues.DocumentationValue{ Documentation: `Specifies the maximum number of authentication attempts permitted per connection. Once the number of failures reaches half this value, additional failures are logged. The default is 6.`, - Value: docvalues.NumberValue{Min: &ZERO}, + Value: docvalues.NumberValue{Min: &ZERO}, }, "MaxSessions": docvalues.DocumentationValue{ Documentation: `Specifies the maximum number of open shell, login or subsystem (e.g. sftp) sessions permitted per network connection. Multiple sessions may be established by clients that support connection multiplexing. Setting MaxSessions to 1 will effectively disable session multiplexing, whereas setting it to 0 will prevent all shell, login and subsystem sessions while still permitting forwarding. The default is 10.`, - Value: docvalues.NumberValue{Min: &ZERO}, + Value: docvalues.NumberValue{Min: &ZERO}, }, "MaxStartups": docvalues.DocumentationValue{ Documentation: `Specifies the maximum number of concurrent unauthenticated connections to the SSH daemon. Additional connections will be dropped until authentication succeeds or the LoginGraceTime expires for a connection. The default is 10:30:100. @@ -588,17 +588,17 @@ Value: docvalues.GroupValue(" ", false), }, "PasswordAuthentication": docvalues.DocumentationValue{ Documentation: `Specifies whether password authentication is allowed. The default is yes.`, - Value: booleanEnumValue, + Value: booleanEnumValue, }, "PermitEmptyPasswords": docvalues.DocumentationValue{ Documentation: `When password authentication is allowed, it specifies whether the server allows login to accounts with empty password strings. The default is no.`, - Value: booleanEnumValue, + Value: booleanEnumValue, }, "PermitListen": docvalues.DocumentationValue{ Documentation: `Specifies the addresses/ports on which a remote TCP port forwarding may listen. The listen specification must be one of the following forms: PermitListen port PermitListen host:port Multiple permissions may be specified by separating them with whitespace. An argument of any can be used to remove all restrictions and permit any listen requests. An argument of none can be used to prohibit all listen requests. The host name may contain wildcards as described in the PATTERNS section in ssh_config(5). The wildcard ‘*’ can also be used in place of a port number to allow all ports. By default all port forwarding listen requests are permitted. Note that the GatewayPorts option may further restrict which addresses may be listened on. Note also that ssh(1) will request a listen host of “localhost” if no listen host was specifically requested, and this name is treated differently to explicit localhost addresses of “127.0.0.1” and “::1”.`, - Value: docvalues.ArrayValue{ + Value: docvalues.ArrayValue{ Separator: " ", DuplicatesExtractor: &docvalues.SimpleDuplicatesExtractor, SubValue: docvalues.KeyValueAssignmentValue{ @@ -632,7 +632,7 @@ Value: docvalues.GroupValue(" ", false), Documentation: `Specifies the destinations to which TCP port forwarding is permitted. The forwarding specification must be one of the following forms: PermitOpen host:port PermitOpen IPv4_addr:port PermitOpen [IPv6_addr]:port Multiple forwards may be specified by separating them with whitespace. An argument of any can be used to remove all restrictions and permit any forwarding requests. An argument of none can be used to prohibit all forwarding requests. The wildcard ‘*’ can be used for host or port to allow all hosts or ports respectively. Otherwise, no pattern matching or address lookups are performed on supplied names. By default all port forwarding requests are permitted.`, - Value: docvalues.ArrayValue{ + Value: docvalues.ArrayValue{ Separator: " ", DuplicatesExtractor: &docvalues.SimpleDuplicatesExtractor, SubValue: docvalues.KeyValueAssignmentValue{ @@ -680,7 +680,7 @@ Value: docvalues.GroupValue(" ", false), If this option is set to prohibit-password (or its deprecated alias, without-password), password and keyboard-interactive authentication are disabled for root. If this option is set to forced-commands-only, root login with public key authentication will be allowed, but only if the command option has been specified (which may be useful for taking remote backups even if root login is normally not allowed). All other authentication methods are disabled for root. If this option is set to no, root is not allowed to log in.`, - Value: docvalues.EnumValue{ + Value: docvalues.EnumValue{ EnforceValues: true, Values: []docvalues.EnumString{ docvalues.CreateEnumString("yes"), @@ -692,12 +692,12 @@ Value: docvalues.GroupValue(" ", false), }, "PermitTTY": docvalues.DocumentationValue{ Documentation: `Specifies whether pty(4) allocation is permitted. The default is yes.`, - Value: booleanEnumValue, + Value: booleanEnumValue, }, "PermitTunnel": docvalues.DocumentationValue{ Documentation: `Specifies whether tun(4) device forwarding is allowed. The argument must be yes, point-to-point (layer 3), ethernet (layer 2), or no. Specifying yes permits both point-to-point and ethernet. The default is no. Independent of this setting, the permissions of the selected tun(4) device must allow access to the user.`, - Value: docvalues.EnumValue{ + Value: docvalues.EnumValue{ EnforceValues: true, Values: []docvalues.EnumString{ docvalues.CreateEnumString("yes"), @@ -727,7 +727,7 @@ Value: docvalues.GroupValue(" ", false), }, "PermitUserRC": docvalues.DocumentationValue{ Documentation: `Specifies whether any ~/.ssh/rc file is executed. The default is yes.`, - Value: booleanEnumValue, + Value: booleanEnumValue, }, "PerSourceMaxStartups": docvalues.DocumentationValue{ Documentation: `Specifies the number of unauthenticated connections allowed from a given source address, or “none” if there is no limit. This limit is applied in addition to MaxStartups, whichever is lower. The default is none.`, @@ -758,26 +758,26 @@ Value: docvalues.GroupValue(" ", false), }, "PidFile": docvalues.DocumentationValue{ Documentation: `Specifies the file that contains the process ID of the SSH daemon, or none to not write one. The default is /var/run/sshd.pid.`, - Value: docvalues.StringValue{}, + Value: docvalues.StringValue{}, }, "Port": docvalues.DocumentationValue{ Documentation: `Specifies the port number that sshd(8) listens on. The default is 22. Multiple options of this type are permitted. See also ListenAddress.`, - Value: docvalues.NumberValue{Min: &ZERO, Max: &MAX_PORT}, + Value: docvalues.NumberValue{Min: &ZERO, Max: &MAX_PORT}, }, "PrintLastLog": docvalues.DocumentationValue{ Documentation: `Specifies whether sshd(8) should print the date and time of the last user login when a user logs in interactively. The default is yes.`, - Value: booleanEnumValue, + Value: booleanEnumValue, }, "PrintMotd": docvalues.DocumentationValue{ Documentation: `Specifies whether sshd(8) should print /etc/motd when a user logs in interactively. (On some systems it is also printed by the shell, /etc/profile, or equivalent.) The default is yes.`, - Value: booleanEnumValue, + Value: booleanEnumValue, }, "PubkeyAcceptedAlgorithms": docvalues.DocumentationValue{ Documentation: `Specifies the signature algorithms that will be accepted for public key authentication as a list of comma- separated patterns. Alternately if the specified list begins with a ‘+’ character, then the specified algorithms will be appended to the default set instead of replacing them. If the specified list begins with a ‘-’ character, then the specified algorithms (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a ‘^’ character, then the specified algorithms will be placed at the head of the default set. The default for this option is: ssh-ed25519-cert-v01@openssh.com, ecdsa-sha2-nistp256-cert-v01@openssh.com, ecdsa-sha2-nistp384-cert-v01@openssh.com, ecdsa-sha2-nistp521-cert-v01@openssh.com, sk-ssh-ed25519-cert-v01@openssh.com, sk-ecdsa-sha2-nistp256-cert-v01@openssh.com, rsa-sha2-512-cert-v01@openssh.com, rsa-sha2-256-cert-v01@openssh.com, ssh-ed25519, ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521, sk-ssh-ed25519@openssh.com, sk-ecdsa-sha2-nistp256@openssh.com, rsa-sha2-512,rsa-sha2-256 The list of available signature algorithms may also be obtained using "ssh -Q PubkeyAcceptedAlgorithms".`, - Value: docvalues.CustomValue{ + Value: docvalues.CustomValue{ FetchValue: func(_ docvalues.CustomValueContext) docvalues.Value { options, _ := queryOpenSSHOptions("PubkeyAcceptedAlgorithms") @@ -790,7 +790,7 @@ Value: docvalues.GroupValue(" ", false), The touch-required option causes public key authentication using a FIDO authenticator algorithm (i.e. ecdsa-sk or ed25519-sk) to always require the signature to attest that a physically present user explicitly confirmed the authentication (usually by touching the authenticator). By default, sshd(8) requires user presence unless overridden with an authorized_keys option. The touch-required flag disables this override. The verify-required option requires a FIDO key signature attest that the user was verified, e.g. via a PIN. Neither the touch-required or verify-required options have any effect for other, non-FIDO, public key types.`, - Value: docvalues.ArrayValue{ + Value: docvalues.ArrayValue{ Separator: ",", SubValue: docvalues.EnumValue{ EnforceValues: true, @@ -804,7 +804,7 @@ Value: docvalues.GroupValue(" ", false), }, "PubkeyAuthentication": docvalues.DocumentationValue{ Documentation: `Specifies whether public key authentication is allowed. The default is yes.`, - Value: booleanEnumValue, + Value: booleanEnumValue, }, "RekeyLimit": docvalues.DocumentationValue{ Documentation: `Specifies the maximum amount of data that may be transmitted or received before the session key is renegotiated, optionally followed by a maximum amount of time that may pass before the session key is renegotiated. The first argument is specified in bytes and may have a suffix of ‘K’, ‘M’, or ‘G’ to indicate Kilobytes, Megabytes, or Gigabytes, respectively. The default is between ‘1G’ and ‘4G’, depending on the cipher. The optional second value is specified in seconds and may use any of the units documented in the “TIME FORMATS” section. The default value for RekeyLimit is default none, which means that rekeying is performed after the cipher's default amount of data has been sent or received and no time based rekeying is done.`, @@ -817,11 +817,11 @@ Value: docvalues.GroupValue(" ", false), }, "RequiredRSASize": docvalues.DocumentationValue{ Documentation: `Specifies the minimum RSA key size (in bits) that sshd(8) will accept. User and host-based authentication keys smaller than this limit will be refused. The default is 1024 bits. Note that this limit may only be raised from the default.`, - Value: docvalues.NumberValue{Min: &ZERO}, + Value: docvalues.NumberValue{Min: &ZERO}, }, "RevokedKeys": docvalues.DocumentationValue{ Documentation: `Specifies revoked public keys file, or none to not use one. Keys listed in this file will be refused for public key authentication. Note that if this file is not readable, then public key authentication will be refused for all users. Keys may be specified as a text file, listing one public key per line, or as an OpenSSH Key Revocation List (KRL) as generated by ssh-keygen(1). For more information on KRLs, see the KEY REVOCATION LISTS section in ssh-keygen(1).`, - Value: docvalues.StringValue{}, + Value: docvalues.StringValue{}, }, "RDomain": docvalues.DocumentationValue{ Documentation: `Specifies an explicit routing domain that is applied after authentication has completed. The user session, as well as any forwarded or listening IP sockets, will be bound to this rdomain(4). If the routing domain is set to %D, then the domain in which the incoming connection was received will be applied.`, @@ -863,23 +863,23 @@ Value: docvalues.GroupValue(" ", false), "StreamLocalBindMask": docvalues.DocumentationValue{ Documentation: `Sets the octal file creation mode mask (umask) used when creating a Unix-domain socket file for local or remote port forwarding. This option is only used for port forwarding to a Unix-domain socket file. The default value is 0177, which creates a Unix-domain socket file that is readable and writable only by the owner. Note that not all operating systems honor the file mode on Unix-domain socket files.`, - Value: docvalues.NumberValue{Min: &ZERO, Max: &MAX_FILE_MODE}, + Value: docvalues.NumberValue{Min: &ZERO, Max: &MAX_FILE_MODE}, }, "StreamLocalBindUnlink": docvalues.DocumentationValue{ Documentation: `Specifies whether to remove an existing Unix-domain socket file for local or remote port forwarding before creating a new one. If the socket file already exists and StreamLocalBindUnlink is not enabled, sshd will be unable to forward the port to the Unix-domain socket file. This option is only used for port forwarding to a Unix-domain socket file. The argument must be yes or no. The default is no.`, - Value: booleanEnumValue, + Value: booleanEnumValue, }, "StrictModes": docvalues.DocumentationValue{ Documentation: `Specifies whether sshd(8) should check file modes and ownership of the user's files and home directory before accepting login. This is normally desirable because novices sometimes accidentally leave their directory or files world-writable. The default is yes. Note that this does not apply to ChrootDirectory, whose permissions and ownership are checked unconditionally.`, - Value: booleanEnumValue, + Value: booleanEnumValue, }, "Subsystem": docvalues.DocumentationValue{ Documentation: `Configures an external subsystem (e.g. file transfer daemon). Arguments should be a subsystem name and a command (with optional arguments) to execute upon subsystem request. The command sftp-server implements the SFTP file transfer subsystem. Alternately the name internal-sftp implements an in- process SFTP server. This may simplify configurations using ChrootDirectory to force a different filesystem root on clients. It accepts the same command line arguments as sftp-server and even though it is in- process, settings such as LogLevel or SyslogFacility do not apply to it and must be set explicitly via command line arguments. By default no subsystems are defined.`, - Value: docvalues.StringValue{}, + Value: docvalues.StringValue{}, }, "SyslogFacility": docvalues.DocumentationValue{ Documentation: `Gives the facility code that is used when logging messages from sshd(8). The possible values are: DAEMON, USER, AUTH, LOCAL0, LOCAL1, LOCAL2, LOCAL3, LOCAL4, LOCAL5, LOCAL6, LOCAL7. The default is AUTH.`, @@ -904,29 +904,29 @@ Value: docvalues.GroupValue(" ", false), Documentation: `Specifies whether the system should send TCP keepalive messages to the other side. If they are sent, death of the connection or crash of one of the machines will be properly noticed. However, this means that connections will die if the route is down temporarily, and some people find it annoying. On the other hand, if TCP keepalives are not sent, sessions may hang indefinitely on the server, leaving "ghost" users and consuming server resources. The default is yes (to send TCP keepalive messages), and the server will notice if the network goes down or the client host crashes. This avoids infinitely hanging sessions. To disable TCP keepalive messages, the value should be set to no.`, - Value: booleanEnumValue, + Value: booleanEnumValue, }, "TrustedUserCAKeys": docvalues.DocumentationValue{ Documentation: `Specifies a file containing public keys of certificate authorities that are trusted to sign user certificates for authentication, or none to not use one. Keys are listed one per line; empty lines and comments starting with ‘#’ are allowed. If a certificate is presented for authentication and has its signing CA key listed in this file, then it may be used for authentication for any user listed in the certificate's principals list. Note that certificates that lack a list of principals will not be permitted for authentication using TrustedUserCAKeys. For more details on certificates, see the CERTIFICATES section in ssh-keygen(1).`, - Value: docvalues.StringValue{}, + Value: docvalues.StringValue{}, }, "UnusedConnectionTimeout": docvalues.DocumentationValue{ Documentation: `Specifies whether and how quickly sshd(8) should close client connections with no open channels. Open channels include active shell, command execution or subsystem sessions, connected network, socket, agent or X11 forwardings. Forwarding listeners, such as those from the ssh(1) -R flag, are not considered as open channels and do not prevent the timeout. The timeout value is specified in seconds or may use any of the units documented in the “TIME FORMATS” section. Note that this timeout starts when the client connection completes user authentication but before the client has an opportunity to open any channels. Caution should be used when using short timeout values, as they may not provide sufficient time for the client to request and open its channels before terminating the connection. The default none is to never expire connections for having no open channels. This option may be useful in conjunction with ChannelTimeout.`, - Value: TimeFormatValue{}, + Value: TimeFormatValue{}, }, "UseDNS": docvalues.DocumentationValue{ Documentation: `Specifies whether sshd(8) should look up the remote host name, and to check that the resolved host name for the remote IP address maps back to the very same IP address. If this option is set to no (the default) then only addresses and not host names may be used in ~/.ssh/authorized_keys from and sshd_config Match Host directives.`, - Value: booleanEnumValue, + Value: booleanEnumValue, }, "UsePAM": docvalues.DocumentationValue{ Documentation: `Enables the Pluggable Authentication Module interface. If set to yes this will enable PAM authentication using KbdInteractiveAuthentication and PasswordAuthentication in addition to PAM account and session module processing for all authentication types. Because PAM keyboard-interactive authentication usually serves an equivalent role to password authentication, you should disable either PasswordAuthentication or KbdInteractiveAuthentication. If UsePAM is enabled, you will not be able to run sshd(8) as a non-root user. The default is no.`, - Value: booleanEnumValue, + Value: booleanEnumValue, }, "VersionAddendum": docvalues.DocumentationValue{ Documentation: `Optionally specifies additional text to append to the SSH protocol banner sent by the server upon connection. The default is none.`, @@ -944,20 +944,20 @@ Value: docvalues.GroupValue(" ", false), }, "X11DisplayOffset": docvalues.DocumentationValue{ Documentation: `Specifies the first display number available for sshd(8)'s X11 forwarding. This prevents sshd from interfering with real X11 servers. The default is 10.`, - Value: docvalues.NumberValue{Min: &ZERO}, + Value: docvalues.NumberValue{Min: &ZERO}, }, "X11Forwarding": docvalues.DocumentationValue{ Documentation: `Specifies whether X11 forwarding is permitted. The argument must be yes or no. The default is no. When X11 forwarding is enabled, there may be additional exposure to the server and to client displays if the sshd(8) proxy display is configured to listen on the wildcard address (see X11UseLocalhost), though this is not the default. Additionally, the authentication spoofing and authentication data verification and substitution occur on the client side. The security risk of using X11 forwarding is that the client's X11 display server may be exposed to attack when the SSH client requests forwarding (see the warnings for ForwardX11 in ssh_config(5)). A system administrator may have a stance in which they want to protect clients that may expose themselves to attack by unwittingly requesting X11 forwarding, which can warrant a no setting. Note that disabling X11 forwarding does not prevent users from forwarding X11 traffic, as users can always install their own forwarders.`, - Value: booleanEnumValue, + Value: booleanEnumValue, }, "X11UseLocalhost": docvalues.DocumentationValue{ Documentation: `Specifies whether sshd(8) should bind the X11 forwarding server to the loopback address or to the wildcard address. By default, sshd binds the forwarding server to the loopback address and sets the hostname part of the DISPLAY environment variable to localhost. This prevents remote hosts from connecting to the proxy display. However, some older X11 clients may not function with this configuration. X11UseLocalhost may be set to no to specify that the forwarding server should be bound to the wildcard address. The argument must be yes or no. The default is yes.`, - Value: booleanEnumValue, + Value: booleanEnumValue, }, "XAuthLocation": docvalues.DocumentationValue{ Documentation: `Specifies the full pathname of the xauth(1) program, or none to not use one. The default is /usr/X11R6/bin/xauth.`, - Value: docvalues.StringValue{}, + Value: docvalues.StringValue{}, }, } diff --git a/handlers/sshd_config/handlers/completions.go b/handlers/sshd_config/handlers/completions.go new file mode 100644 index 0000000..a23d656 --- /dev/null +++ b/handlers/sshd_config/handlers/completions.go @@ -0,0 +1,35 @@ +package handlers + +import ( + docvalues "config-lsp/doc-values" + sshdconfig "config-lsp/handlers/sshd_config" + "config-lsp/handlers/sshd_config/ast" + "config-lsp/handlers/sshd_config/fields" + "config-lsp/utils" + + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func GetRootCompletions( + d *sshdconfig.SSHDocument, + parentMatchBlock *ast.SSHMatchBlock, +) ([]protocol.CompletionItem, error) { + kind := protocol.CompletionItemKindField + format := protocol.InsertTextFormatSnippet + + return utils.MapMapToSlice( + fields.Options, + func(name string, rawValue docvalues.Value) protocol.CompletionItem { + doc := rawValue.(docvalues.DocumentationValue) + + insertText := name + " " + "${1:value}" + return protocol.CompletionItem{ + Label: name, + Kind: &kind, + Documentation: doc.Documentation, + InsertText: &insertText, + InsertTextFormat: &format, + } + }, + ), nil +} diff --git a/handlers/sshd_config/lsp/text-document-completion.go b/handlers/sshd_config/lsp/text-document-completion.go index 5c5b64a..98285fc 100644 --- a/handlers/sshd_config/lsp/text-document-completion.go +++ b/handlers/sshd_config/lsp/text-document-completion.go @@ -1,10 +1,33 @@ package lsp import ( + sshdconfig "config-lsp/handlers/sshd_config" + "config-lsp/handlers/sshd_config/handlers" + "github.com/tliron/glsp" protocol "github.com/tliron/glsp/protocol_3_16" ) func TextDocumentCompletion(context *glsp.Context, params *protocol.CompletionParams) (any, error) { + line := params.Position.Line + cursor := params.Position.Character + _ = cursor + + d := sshdconfig.DocumentParserMap[params.TextDocument.URI] + + if _, found := d.Config.CommentLines[line]; found { + return nil, nil + } + + entry, matchBlock := d.Config.FindOption(line) + + if entry == nil { + // Empty line + return handlers.GetRootCompletions( + d, + matchBlock, + ) + } + return nil, nil } diff --git a/handlers/sshd_config/lsp/text-document-did-change.go b/handlers/sshd_config/lsp/text-document-did-change.go index bed7156..82bf08e 100644 --- a/handlers/sshd_config/lsp/text-document-did-change.go +++ b/handlers/sshd_config/lsp/text-document-did-change.go @@ -2,8 +2,8 @@ package lsp import ( "config-lsp/common" - "config-lsp/handlers/sshd_config/analyzer" "config-lsp/handlers/sshd_config" + "config-lsp/handlers/sshd_config/analyzer" "config-lsp/utils" "github.com/tliron/glsp" diff --git a/handlers/sshd_config/shared.go b/handlers/sshd_config/shared.go index e5503b7..318f6ba 100644 --- a/handlers/sshd_config/shared.go +++ b/handlers/sshd_config/shared.go @@ -7,8 +7,7 @@ import ( ) type SSHDocument struct { - Config *ast.SSHConfig + Config *ast.SSHConfig } var DocumentParserMap = map[protocol.DocumentUri]*SSHDocument{} - From 01bda3b660effabc236eac766c7b2eb0a2a366ef Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Wed, 11 Sep 2024 22:54:16 +0200 Subject: [PATCH 016/133] feat(sshd_config): Add separator field --- handlers/sshd_config/Config.g4 | 6 +- handlers/sshd_config/ast/listener.go | 9 + handlers/sshd_config/ast/parser/Config.interp | 3 +- .../ast/parser/config_base_listener.go | 6 + .../sshd_config/ast/parser/config_listener.go | 6 + .../sshd_config/ast/parser/config_parser.go | 255 +++++++++++++----- handlers/sshd_config/ast/sshd_config.go | 5 + .../lsp/text-document-completion.go | 5 +- 8 files changed, 220 insertions(+), 75 deletions(-) diff --git a/handlers/sshd_config/Config.g4 b/handlers/sshd_config/Config.g4 index 0621992..42346ad 100644 --- a/handlers/sshd_config/Config.g4 +++ b/handlers/sshd_config/Config.g4 @@ -5,7 +5,11 @@ lineStatement ; entry - : WHITESPACE? key? WHITESPACE? value? WHITESPACE? leadingComment? + : WHITESPACE? key? separator? value? WHITESPACE? leadingComment? + ; + +separator + : WHITESPACE ; key diff --git a/handlers/sshd_config/ast/listener.go b/handlers/sshd_config/ast/listener.go index 48666bf..e6d4b47 100644 --- a/handlers/sshd_config/ast/listener.go +++ b/handlers/sshd_config/ast/listener.go @@ -68,6 +68,15 @@ func (s *sshParserListener) EnterKey(ctx *parser.KeyContext) { } } +func (s *sshParserListener) EnterSeparator(ctx *parser.SeparatorContext) { + location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext) + location.ChangeBothLines(s.sshContext.line) + + s.sshContext.currentOption.Separator = &SSHSeparator{ + LocationRange: location, + } +} + func (s *sshParserListener) EnterValue(ctx *parser.ValueContext) { location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext) location.ChangeBothLines(s.sshContext.line) diff --git a/handlers/sshd_config/ast/parser/Config.interp b/handlers/sshd_config/ast/parser/Config.interp index 4739ffb..e860731 100644 --- a/handlers/sshd_config/ast/parser/Config.interp +++ b/handlers/sshd_config/ast/parser/Config.interp @@ -15,10 +15,11 @@ NEWLINE rule names: lineStatement entry +separator key value leadingComment atn: -[4, 1, 4, 61, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 1, 0, 1, 0, 3, 0, 13, 8, 0, 1, 0, 1, 0, 3, 0, 17, 8, 0, 3, 0, 19, 8, 0, 1, 0, 1, 0, 1, 1, 3, 1, 24, 8, 1, 1, 1, 3, 1, 27, 8, 1, 1, 1, 3, 1, 30, 8, 1, 1, 1, 3, 1, 33, 8, 1, 1, 1, 3, 1, 36, 8, 1, 1, 1, 3, 1, 39, 8, 1, 1, 2, 1, 2, 1, 3, 1, 3, 3, 3, 45, 8, 3, 1, 3, 1, 3, 1, 4, 1, 4, 3, 4, 51, 8, 4, 1, 4, 1, 4, 3, 4, 55, 8, 4, 4, 4, 57, 8, 4, 11, 4, 12, 4, 58, 1, 4, 0, 0, 5, 0, 2, 4, 6, 8, 0, 0, 69, 0, 18, 1, 0, 0, 0, 2, 23, 1, 0, 0, 0, 4, 40, 1, 0, 0, 0, 6, 44, 1, 0, 0, 0, 8, 48, 1, 0, 0, 0, 10, 19, 3, 2, 1, 0, 11, 13, 5, 2, 0, 0, 12, 11, 1, 0, 0, 0, 12, 13, 1, 0, 0, 0, 13, 14, 1, 0, 0, 0, 14, 19, 3, 8, 4, 0, 15, 17, 5, 2, 0, 0, 16, 15, 1, 0, 0, 0, 16, 17, 1, 0, 0, 0, 17, 19, 1, 0, 0, 0, 18, 10, 1, 0, 0, 0, 18, 12, 1, 0, 0, 0, 18, 16, 1, 0, 0, 0, 19, 20, 1, 0, 0, 0, 20, 21, 5, 0, 0, 1, 21, 1, 1, 0, 0, 0, 22, 24, 5, 2, 0, 0, 23, 22, 1, 0, 0, 0, 23, 24, 1, 0, 0, 0, 24, 26, 1, 0, 0, 0, 25, 27, 3, 4, 2, 0, 26, 25, 1, 0, 0, 0, 26, 27, 1, 0, 0, 0, 27, 29, 1, 0, 0, 0, 28, 30, 5, 2, 0, 0, 29, 28, 1, 0, 0, 0, 29, 30, 1, 0, 0, 0, 30, 32, 1, 0, 0, 0, 31, 33, 3, 6, 3, 0, 32, 31, 1, 0, 0, 0, 32, 33, 1, 0, 0, 0, 33, 35, 1, 0, 0, 0, 34, 36, 5, 2, 0, 0, 35, 34, 1, 0, 0, 0, 35, 36, 1, 0, 0, 0, 36, 38, 1, 0, 0, 0, 37, 39, 3, 8, 4, 0, 38, 37, 1, 0, 0, 0, 38, 39, 1, 0, 0, 0, 39, 3, 1, 0, 0, 0, 40, 41, 5, 3, 0, 0, 41, 5, 1, 0, 0, 0, 42, 43, 5, 3, 0, 0, 43, 45, 5, 2, 0, 0, 44, 42, 1, 0, 0, 0, 44, 45, 1, 0, 0, 0, 45, 46, 1, 0, 0, 0, 46, 47, 5, 3, 0, 0, 47, 7, 1, 0, 0, 0, 48, 50, 5, 1, 0, 0, 49, 51, 5, 2, 0, 0, 50, 49, 1, 0, 0, 0, 50, 51, 1, 0, 0, 0, 51, 56, 1, 0, 0, 0, 52, 54, 5, 3, 0, 0, 53, 55, 5, 2, 0, 0, 54, 53, 1, 0, 0, 0, 54, 55, 1, 0, 0, 0, 55, 57, 1, 0, 0, 0, 56, 52, 1, 0, 0, 0, 57, 58, 1, 0, 0, 0, 58, 56, 1, 0, 0, 0, 58, 59, 1, 0, 0, 0, 59, 9, 1, 0, 0, 0, 13, 12, 16, 18, 23, 26, 29, 32, 35, 38, 44, 50, 54, 58] \ No newline at end of file +[4, 1, 4, 65, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 2, 5, 7, 5, 1, 0, 1, 0, 3, 0, 15, 8, 0, 1, 0, 1, 0, 3, 0, 19, 8, 0, 3, 0, 21, 8, 0, 1, 0, 1, 0, 1, 1, 3, 1, 26, 8, 1, 1, 1, 3, 1, 29, 8, 1, 1, 1, 3, 1, 32, 8, 1, 1, 1, 3, 1, 35, 8, 1, 1, 1, 3, 1, 38, 8, 1, 1, 1, 3, 1, 41, 8, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, 1, 4, 3, 4, 49, 8, 4, 1, 4, 1, 4, 1, 5, 1, 5, 3, 5, 55, 8, 5, 1, 5, 1, 5, 3, 5, 59, 8, 5, 4, 5, 61, 8, 5, 11, 5, 12, 5, 62, 1, 5, 0, 0, 6, 0, 2, 4, 6, 8, 10, 0, 0, 72, 0, 20, 1, 0, 0, 0, 2, 25, 1, 0, 0, 0, 4, 42, 1, 0, 0, 0, 6, 44, 1, 0, 0, 0, 8, 48, 1, 0, 0, 0, 10, 52, 1, 0, 0, 0, 12, 21, 3, 2, 1, 0, 13, 15, 5, 2, 0, 0, 14, 13, 1, 0, 0, 0, 14, 15, 1, 0, 0, 0, 15, 16, 1, 0, 0, 0, 16, 21, 3, 10, 5, 0, 17, 19, 5, 2, 0, 0, 18, 17, 1, 0, 0, 0, 18, 19, 1, 0, 0, 0, 19, 21, 1, 0, 0, 0, 20, 12, 1, 0, 0, 0, 20, 14, 1, 0, 0, 0, 20, 18, 1, 0, 0, 0, 21, 22, 1, 0, 0, 0, 22, 23, 5, 0, 0, 1, 23, 1, 1, 0, 0, 0, 24, 26, 5, 2, 0, 0, 25, 24, 1, 0, 0, 0, 25, 26, 1, 0, 0, 0, 26, 28, 1, 0, 0, 0, 27, 29, 3, 6, 3, 0, 28, 27, 1, 0, 0, 0, 28, 29, 1, 0, 0, 0, 29, 31, 1, 0, 0, 0, 30, 32, 3, 4, 2, 0, 31, 30, 1, 0, 0, 0, 31, 32, 1, 0, 0, 0, 32, 34, 1, 0, 0, 0, 33, 35, 3, 8, 4, 0, 34, 33, 1, 0, 0, 0, 34, 35, 1, 0, 0, 0, 35, 37, 1, 0, 0, 0, 36, 38, 5, 2, 0, 0, 37, 36, 1, 0, 0, 0, 37, 38, 1, 0, 0, 0, 38, 40, 1, 0, 0, 0, 39, 41, 3, 10, 5, 0, 40, 39, 1, 0, 0, 0, 40, 41, 1, 0, 0, 0, 41, 3, 1, 0, 0, 0, 42, 43, 5, 2, 0, 0, 43, 5, 1, 0, 0, 0, 44, 45, 5, 3, 0, 0, 45, 7, 1, 0, 0, 0, 46, 47, 5, 3, 0, 0, 47, 49, 5, 2, 0, 0, 48, 46, 1, 0, 0, 0, 48, 49, 1, 0, 0, 0, 49, 50, 1, 0, 0, 0, 50, 51, 5, 3, 0, 0, 51, 9, 1, 0, 0, 0, 52, 54, 5, 1, 0, 0, 53, 55, 5, 2, 0, 0, 54, 53, 1, 0, 0, 0, 54, 55, 1, 0, 0, 0, 55, 60, 1, 0, 0, 0, 56, 58, 5, 3, 0, 0, 57, 59, 5, 2, 0, 0, 58, 57, 1, 0, 0, 0, 58, 59, 1, 0, 0, 0, 59, 61, 1, 0, 0, 0, 60, 56, 1, 0, 0, 0, 61, 62, 1, 0, 0, 0, 62, 60, 1, 0, 0, 0, 62, 63, 1, 0, 0, 0, 63, 11, 1, 0, 0, 0, 13, 14, 18, 20, 25, 28, 31, 34, 37, 40, 48, 54, 58, 62] \ No newline at end of file diff --git a/handlers/sshd_config/ast/parser/config_base_listener.go b/handlers/sshd_config/ast/parser/config_base_listener.go index a161a6a..ac8bdac 100644 --- a/handlers/sshd_config/ast/parser/config_base_listener.go +++ b/handlers/sshd_config/ast/parser/config_base_listener.go @@ -33,6 +33,12 @@ func (s *BaseConfigListener) EnterEntry(ctx *EntryContext) {} // ExitEntry is called when production entry is exited. func (s *BaseConfigListener) ExitEntry(ctx *EntryContext) {} +// EnterSeparator is called when production separator is entered. +func (s *BaseConfigListener) EnterSeparator(ctx *SeparatorContext) {} + +// ExitSeparator is called when production separator is exited. +func (s *BaseConfigListener) ExitSeparator(ctx *SeparatorContext) {} + // EnterKey is called when production key is entered. func (s *BaseConfigListener) EnterKey(ctx *KeyContext) {} diff --git a/handlers/sshd_config/ast/parser/config_listener.go b/handlers/sshd_config/ast/parser/config_listener.go index 00c5695..0384e3c 100644 --- a/handlers/sshd_config/ast/parser/config_listener.go +++ b/handlers/sshd_config/ast/parser/config_listener.go @@ -14,6 +14,9 @@ type ConfigListener interface { // EnterEntry is called when entering the entry production. EnterEntry(c *EntryContext) + // EnterSeparator is called when entering the separator production. + EnterSeparator(c *SeparatorContext) + // EnterKey is called when entering the key production. EnterKey(c *KeyContext) @@ -29,6 +32,9 @@ type ConfigListener interface { // ExitEntry is called when exiting the entry production. ExitEntry(c *EntryContext) + // ExitSeparator is called when exiting the separator production. + ExitSeparator(c *SeparatorContext) + // ExitKey is called when exiting the key production. ExitKey(c *KeyContext) diff --git a/handlers/sshd_config/ast/parser/config_parser.go b/handlers/sshd_config/ast/parser/config_parser.go index bd05590..57ca885 100644 --- a/handlers/sshd_config/ast/parser/config_parser.go +++ b/handlers/sshd_config/ast/parser/config_parser.go @@ -39,37 +39,38 @@ func configParserInit() { "", "HASH", "WHITESPACE", "STRING", "NEWLINE", } staticData.RuleNames = []string{ - "lineStatement", "entry", "key", "value", "leadingComment", + "lineStatement", "entry", "separator", "key", "value", "leadingComment", } staticData.PredictionContextCache = antlr.NewPredictionContextCache() staticData.serializedATN = []int32{ - 4, 1, 4, 61, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, - 1, 0, 1, 0, 3, 0, 13, 8, 0, 1, 0, 1, 0, 3, 0, 17, 8, 0, 3, 0, 19, 8, 0, - 1, 0, 1, 0, 1, 1, 3, 1, 24, 8, 1, 1, 1, 3, 1, 27, 8, 1, 1, 1, 3, 1, 30, - 8, 1, 1, 1, 3, 1, 33, 8, 1, 1, 1, 3, 1, 36, 8, 1, 1, 1, 3, 1, 39, 8, 1, - 1, 2, 1, 2, 1, 3, 1, 3, 3, 3, 45, 8, 3, 1, 3, 1, 3, 1, 4, 1, 4, 3, 4, 51, - 8, 4, 1, 4, 1, 4, 3, 4, 55, 8, 4, 4, 4, 57, 8, 4, 11, 4, 12, 4, 58, 1, - 4, 0, 0, 5, 0, 2, 4, 6, 8, 0, 0, 69, 0, 18, 1, 0, 0, 0, 2, 23, 1, 0, 0, - 0, 4, 40, 1, 0, 0, 0, 6, 44, 1, 0, 0, 0, 8, 48, 1, 0, 0, 0, 10, 19, 3, - 2, 1, 0, 11, 13, 5, 2, 0, 0, 12, 11, 1, 0, 0, 0, 12, 13, 1, 0, 0, 0, 13, - 14, 1, 0, 0, 0, 14, 19, 3, 8, 4, 0, 15, 17, 5, 2, 0, 0, 16, 15, 1, 0, 0, - 0, 16, 17, 1, 0, 0, 0, 17, 19, 1, 0, 0, 0, 18, 10, 1, 0, 0, 0, 18, 12, - 1, 0, 0, 0, 18, 16, 1, 0, 0, 0, 19, 20, 1, 0, 0, 0, 20, 21, 5, 0, 0, 1, - 21, 1, 1, 0, 0, 0, 22, 24, 5, 2, 0, 0, 23, 22, 1, 0, 0, 0, 23, 24, 1, 0, - 0, 0, 24, 26, 1, 0, 0, 0, 25, 27, 3, 4, 2, 0, 26, 25, 1, 0, 0, 0, 26, 27, - 1, 0, 0, 0, 27, 29, 1, 0, 0, 0, 28, 30, 5, 2, 0, 0, 29, 28, 1, 0, 0, 0, - 29, 30, 1, 0, 0, 0, 30, 32, 1, 0, 0, 0, 31, 33, 3, 6, 3, 0, 32, 31, 1, - 0, 0, 0, 32, 33, 1, 0, 0, 0, 33, 35, 1, 0, 0, 0, 34, 36, 5, 2, 0, 0, 35, - 34, 1, 0, 0, 0, 35, 36, 1, 0, 0, 0, 36, 38, 1, 0, 0, 0, 37, 39, 3, 8, 4, - 0, 38, 37, 1, 0, 0, 0, 38, 39, 1, 0, 0, 0, 39, 3, 1, 0, 0, 0, 40, 41, 5, - 3, 0, 0, 41, 5, 1, 0, 0, 0, 42, 43, 5, 3, 0, 0, 43, 45, 5, 2, 0, 0, 44, - 42, 1, 0, 0, 0, 44, 45, 1, 0, 0, 0, 45, 46, 1, 0, 0, 0, 46, 47, 5, 3, 0, - 0, 47, 7, 1, 0, 0, 0, 48, 50, 5, 1, 0, 0, 49, 51, 5, 2, 0, 0, 50, 49, 1, - 0, 0, 0, 50, 51, 1, 0, 0, 0, 51, 56, 1, 0, 0, 0, 52, 54, 5, 3, 0, 0, 53, - 55, 5, 2, 0, 0, 54, 53, 1, 0, 0, 0, 54, 55, 1, 0, 0, 0, 55, 57, 1, 0, 0, - 0, 56, 52, 1, 0, 0, 0, 57, 58, 1, 0, 0, 0, 58, 56, 1, 0, 0, 0, 58, 59, - 1, 0, 0, 0, 59, 9, 1, 0, 0, 0, 13, 12, 16, 18, 23, 26, 29, 32, 35, 38, - 44, 50, 54, 58, + 4, 1, 4, 65, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, + 2, 5, 7, 5, 1, 0, 1, 0, 3, 0, 15, 8, 0, 1, 0, 1, 0, 3, 0, 19, 8, 0, 3, + 0, 21, 8, 0, 1, 0, 1, 0, 1, 1, 3, 1, 26, 8, 1, 1, 1, 3, 1, 29, 8, 1, 1, + 1, 3, 1, 32, 8, 1, 1, 1, 3, 1, 35, 8, 1, 1, 1, 3, 1, 38, 8, 1, 1, 1, 3, + 1, 41, 8, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, 1, 4, 3, 4, 49, 8, 4, 1, 4, + 1, 4, 1, 5, 1, 5, 3, 5, 55, 8, 5, 1, 5, 1, 5, 3, 5, 59, 8, 5, 4, 5, 61, + 8, 5, 11, 5, 12, 5, 62, 1, 5, 0, 0, 6, 0, 2, 4, 6, 8, 10, 0, 0, 72, 0, + 20, 1, 0, 0, 0, 2, 25, 1, 0, 0, 0, 4, 42, 1, 0, 0, 0, 6, 44, 1, 0, 0, 0, + 8, 48, 1, 0, 0, 0, 10, 52, 1, 0, 0, 0, 12, 21, 3, 2, 1, 0, 13, 15, 5, 2, + 0, 0, 14, 13, 1, 0, 0, 0, 14, 15, 1, 0, 0, 0, 15, 16, 1, 0, 0, 0, 16, 21, + 3, 10, 5, 0, 17, 19, 5, 2, 0, 0, 18, 17, 1, 0, 0, 0, 18, 19, 1, 0, 0, 0, + 19, 21, 1, 0, 0, 0, 20, 12, 1, 0, 0, 0, 20, 14, 1, 0, 0, 0, 20, 18, 1, + 0, 0, 0, 21, 22, 1, 0, 0, 0, 22, 23, 5, 0, 0, 1, 23, 1, 1, 0, 0, 0, 24, + 26, 5, 2, 0, 0, 25, 24, 1, 0, 0, 0, 25, 26, 1, 0, 0, 0, 26, 28, 1, 0, 0, + 0, 27, 29, 3, 6, 3, 0, 28, 27, 1, 0, 0, 0, 28, 29, 1, 0, 0, 0, 29, 31, + 1, 0, 0, 0, 30, 32, 3, 4, 2, 0, 31, 30, 1, 0, 0, 0, 31, 32, 1, 0, 0, 0, + 32, 34, 1, 0, 0, 0, 33, 35, 3, 8, 4, 0, 34, 33, 1, 0, 0, 0, 34, 35, 1, + 0, 0, 0, 35, 37, 1, 0, 0, 0, 36, 38, 5, 2, 0, 0, 37, 36, 1, 0, 0, 0, 37, + 38, 1, 0, 0, 0, 38, 40, 1, 0, 0, 0, 39, 41, 3, 10, 5, 0, 40, 39, 1, 0, + 0, 0, 40, 41, 1, 0, 0, 0, 41, 3, 1, 0, 0, 0, 42, 43, 5, 2, 0, 0, 43, 5, + 1, 0, 0, 0, 44, 45, 5, 3, 0, 0, 45, 7, 1, 0, 0, 0, 46, 47, 5, 3, 0, 0, + 47, 49, 5, 2, 0, 0, 48, 46, 1, 0, 0, 0, 48, 49, 1, 0, 0, 0, 49, 50, 1, + 0, 0, 0, 50, 51, 5, 3, 0, 0, 51, 9, 1, 0, 0, 0, 52, 54, 5, 1, 0, 0, 53, + 55, 5, 2, 0, 0, 54, 53, 1, 0, 0, 0, 54, 55, 1, 0, 0, 0, 55, 60, 1, 0, 0, + 0, 56, 58, 5, 3, 0, 0, 57, 59, 5, 2, 0, 0, 58, 57, 1, 0, 0, 0, 58, 59, + 1, 0, 0, 0, 59, 61, 1, 0, 0, 0, 60, 56, 1, 0, 0, 0, 61, 62, 1, 0, 0, 0, + 62, 60, 1, 0, 0, 0, 62, 63, 1, 0, 0, 0, 63, 11, 1, 0, 0, 0, 13, 14, 18, + 20, 25, 28, 31, 34, 37, 40, 48, 54, 58, 62, } deserializer := antlr.NewATNDeserializer(nil) staticData.atn = deserializer.Deserialize(staticData.serializedATN) @@ -118,9 +119,10 @@ const ( const ( ConfigParserRULE_lineStatement = 0 ConfigParserRULE_entry = 1 - ConfigParserRULE_key = 2 - ConfigParserRULE_value = 3 - ConfigParserRULE_leadingComment = 4 + ConfigParserRULE_separator = 2 + ConfigParserRULE_key = 3 + ConfigParserRULE_value = 4 + ConfigParserRULE_leadingComment = 5 ) // ILineStatementContext is an interface to support dynamic dispatch. @@ -238,7 +240,7 @@ func (p *ConfigParser) LineStatement() (localctx ILineStatementContext) { var _la int p.EnterOuterAlt(localctx, 1) - p.SetState(18) + p.SetState(20) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -247,12 +249,12 @@ func (p *ConfigParser) LineStatement() (localctx ILineStatementContext) { switch p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 2, p.GetParserRuleContext()) { case 1: { - p.SetState(10) + p.SetState(12) p.Entry() } case 2: - p.SetState(12) + p.SetState(14) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -261,7 +263,7 @@ func (p *ConfigParser) LineStatement() (localctx ILineStatementContext) { if _la == ConfigParserWHITESPACE { { - p.SetState(11) + p.SetState(13) p.Match(ConfigParserWHITESPACE) if p.HasError() { // Recognition error - abort rule @@ -271,12 +273,12 @@ func (p *ConfigParser) LineStatement() (localctx ILineStatementContext) { } { - p.SetState(14) + p.SetState(16) p.LeadingComment() } case 3: - p.SetState(16) + p.SetState(18) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -285,7 +287,7 @@ func (p *ConfigParser) LineStatement() (localctx ILineStatementContext) { if _la == ConfigParserWHITESPACE { { - p.SetState(15) + p.SetState(17) p.Match(ConfigParserWHITESPACE) if p.HasError() { // Recognition error - abort rule @@ -299,7 +301,7 @@ func (p *ConfigParser) LineStatement() (localctx ILineStatementContext) { goto errorExit } { - p.SetState(20) + p.SetState(22) p.Match(ConfigParserEOF) if p.HasError() { // Recognition error - abort rule @@ -331,6 +333,7 @@ type IEntryContext interface { AllWHITESPACE() []antlr.TerminalNode WHITESPACE(i int) antlr.TerminalNode Key() IKeyContext + Separator() ISeparatorContext Value() IValueContext LeadingComment() ILeadingCommentContext @@ -394,6 +397,22 @@ func (s *EntryContext) Key() IKeyContext { return t.(IKeyContext) } +func (s *EntryContext) Separator() ISeparatorContext { + var t antlr.RuleContext + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(ISeparatorContext); ok { + t = ctx.(antlr.RuleContext) + break + } + } + + if t == nil { + return nil + } + + return t.(ISeparatorContext) +} + func (s *EntryContext) Value() IValueContext { var t antlr.RuleContext for _, ctx := range s.GetChildren() { @@ -452,12 +471,12 @@ func (p *ConfigParser) Entry() (localctx IEntryContext) { var _la int p.EnterOuterAlt(localctx, 1) - p.SetState(23) + p.SetState(25) p.GetErrorHandler().Sync(p) if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 3, p.GetParserRuleContext()) == 1 { { - p.SetState(22) + p.SetState(24) p.Match(ConfigParserWHITESPACE) if p.HasError() { // Recognition error - abort rule @@ -468,35 +487,31 @@ func (p *ConfigParser) Entry() (localctx IEntryContext) { } else if p.HasError() { // JIM goto errorExit } - p.SetState(26) + p.SetState(28) p.GetErrorHandler().Sync(p) if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 4, p.GetParserRuleContext()) == 1 { { - p.SetState(25) + p.SetState(27) p.Key() } } else if p.HasError() { // JIM goto errorExit } - p.SetState(29) + p.SetState(31) p.GetErrorHandler().Sync(p) if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 5, p.GetParserRuleContext()) == 1 { { - p.SetState(28) - p.Match(ConfigParserWHITESPACE) - if p.HasError() { - // Recognition error - abort rule - goto errorExit - } + p.SetState(30) + p.Separator() } } else if p.HasError() { // JIM goto errorExit } - p.SetState(32) + p.SetState(34) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -505,12 +520,12 @@ func (p *ConfigParser) Entry() (localctx IEntryContext) { if _la == ConfigParserSTRING { { - p.SetState(31) + p.SetState(33) p.Value() } } - p.SetState(35) + p.SetState(37) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -519,7 +534,7 @@ func (p *ConfigParser) Entry() (localctx IEntryContext) { if _la == ConfigParserWHITESPACE { { - p.SetState(34) + p.SetState(36) p.Match(ConfigParserWHITESPACE) if p.HasError() { // Recognition error - abort rule @@ -528,7 +543,7 @@ func (p *ConfigParser) Entry() (localctx IEntryContext) { } } - p.SetState(38) + p.SetState(40) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -537,7 +552,7 @@ func (p *ConfigParser) Entry() (localctx IEntryContext) { if _la == ConfigParserHASH { { - p.SetState(37) + p.SetState(39) p.LeadingComment() } @@ -556,6 +571,102 @@ errorExit: goto errorExit // Trick to prevent compiler error if the label is not used } +// ISeparatorContext is an interface to support dynamic dispatch. +type ISeparatorContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + + // Getter signatures + WHITESPACE() antlr.TerminalNode + + // IsSeparatorContext differentiates from other interfaces. + IsSeparatorContext() +} + +type SeparatorContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptySeparatorContext() *SeparatorContext { + var p = new(SeparatorContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_separator + return p +} + +func InitEmptySeparatorContext(p *SeparatorContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_separator +} + +func (*SeparatorContext) IsSeparatorContext() {} + +func NewSeparatorContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *SeparatorContext { + var p = new(SeparatorContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = ConfigParserRULE_separator + + return p +} + +func (s *SeparatorContext) GetParser() antlr.Parser { return s.parser } + +func (s *SeparatorContext) WHITESPACE() antlr.TerminalNode { + return s.GetToken(ConfigParserWHITESPACE, 0) +} + +func (s *SeparatorContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *SeparatorContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +func (s *SeparatorContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.EnterSeparator(s) + } +} + +func (s *SeparatorContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.ExitSeparator(s) + } +} + +func (p *ConfigParser) Separator() (localctx ISeparatorContext) { + localctx = NewSeparatorContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 4, ConfigParserRULE_separator) + p.EnterOuterAlt(localctx, 1) + { + p.SetState(42) + p.Match(ConfigParserWHITESPACE) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} + // IKeyContext is an interface to support dynamic dispatch. type IKeyContext interface { antlr.ParserRuleContext @@ -628,10 +739,10 @@ func (s *KeyContext) ExitRule(listener antlr.ParseTreeListener) { func (p *ConfigParser) Key() (localctx IKeyContext) { localctx = NewKeyContext(p, p.GetParserRuleContext(), p.GetState()) - p.EnterRule(localctx, 4, ConfigParserRULE_key) + p.EnterRule(localctx, 6, ConfigParserRULE_key) p.EnterOuterAlt(localctx, 1) { - p.SetState(40) + p.SetState(44) p.Match(ConfigParserSTRING) if p.HasError() { // Recognition error - abort rule @@ -734,14 +845,14 @@ func (s *ValueContext) ExitRule(listener antlr.ParseTreeListener) { func (p *ConfigParser) Value() (localctx IValueContext) { localctx = NewValueContext(p, p.GetParserRuleContext(), p.GetState()) - p.EnterRule(localctx, 6, ConfigParserRULE_value) + p.EnterRule(localctx, 8, ConfigParserRULE_value) p.EnterOuterAlt(localctx, 1) - p.SetState(44) + p.SetState(48) p.GetErrorHandler().Sync(p) if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 9, p.GetParserRuleContext()) == 1 { { - p.SetState(42) + p.SetState(46) p.Match(ConfigParserSTRING) if p.HasError() { // Recognition error - abort rule @@ -749,7 +860,7 @@ func (p *ConfigParser) Value() (localctx IValueContext) { } } { - p.SetState(43) + p.SetState(47) p.Match(ConfigParserWHITESPACE) if p.HasError() { // Recognition error - abort rule @@ -761,7 +872,7 @@ func (p *ConfigParser) Value() (localctx IValueContext) { goto errorExit } { - p.SetState(46) + p.SetState(50) p.Match(ConfigParserSTRING) if p.HasError() { // Recognition error - abort rule @@ -874,19 +985,19 @@ func (s *LeadingCommentContext) ExitRule(listener antlr.ParseTreeListener) { func (p *ConfigParser) LeadingComment() (localctx ILeadingCommentContext) { localctx = NewLeadingCommentContext(p, p.GetParserRuleContext(), p.GetState()) - p.EnterRule(localctx, 8, ConfigParserRULE_leadingComment) + p.EnterRule(localctx, 10, ConfigParserRULE_leadingComment) var _la int p.EnterOuterAlt(localctx, 1) { - p.SetState(48) + p.SetState(52) p.Match(ConfigParserHASH) if p.HasError() { // Recognition error - abort rule goto errorExit } } - p.SetState(50) + p.SetState(54) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -895,7 +1006,7 @@ func (p *ConfigParser) LeadingComment() (localctx ILeadingCommentContext) { if _la == ConfigParserWHITESPACE { { - p.SetState(49) + p.SetState(53) p.Match(ConfigParserWHITESPACE) if p.HasError() { // Recognition error - abort rule @@ -904,7 +1015,7 @@ func (p *ConfigParser) LeadingComment() (localctx ILeadingCommentContext) { } } - p.SetState(56) + p.SetState(60) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -913,14 +1024,14 @@ func (p *ConfigParser) LeadingComment() (localctx ILeadingCommentContext) { for ok := true; ok; ok = _la == ConfigParserSTRING { { - p.SetState(52) + p.SetState(56) p.Match(ConfigParserSTRING) if p.HasError() { // Recognition error - abort rule goto errorExit } } - p.SetState(54) + p.SetState(58) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -929,7 +1040,7 @@ func (p *ConfigParser) LeadingComment() (localctx ILeadingCommentContext) { if _la == ConfigParserWHITESPACE { { - p.SetState(53) + p.SetState(57) p.Match(ConfigParserWHITESPACE) if p.HasError() { // Recognition error - abort rule @@ -939,7 +1050,7 @@ func (p *ConfigParser) LeadingComment() (localctx ILeadingCommentContext) { } - p.SetState(58) + p.SetState(62) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit diff --git a/handlers/sshd_config/ast/sshd_config.go b/handlers/sshd_config/ast/sshd_config.go index c75565c..25897e9 100644 --- a/handlers/sshd_config/ast/sshd_config.go +++ b/handlers/sshd_config/ast/sshd_config.go @@ -27,11 +27,16 @@ type SSHEntry interface { GetType() SSHEntryType } +type SSHSeparator struct { + common.LocationRange +} + type SSHOption struct { common.LocationRange Value string Key *SSHKey + Separator *SSHSeparator OptionValue *SSHValue } diff --git a/handlers/sshd_config/lsp/text-document-completion.go b/handlers/sshd_config/lsp/text-document-completion.go index 98285fc..7f9c3a2 100644 --- a/handlers/sshd_config/lsp/text-document-completion.go +++ b/handlers/sshd_config/lsp/text-document-completion.go @@ -3,11 +3,14 @@ package lsp import ( sshdconfig "config-lsp/handlers/sshd_config" "config-lsp/handlers/sshd_config/handlers" + "regexp" "github.com/tliron/glsp" protocol "github.com/tliron/glsp/protocol_3_16" ) +var containsSeparatorPattern = regexp.MustCompile(`\s+$`) + func TextDocumentCompletion(context *glsp.Context, params *protocol.CompletionParams) (any, error) { line := params.Position.Line cursor := params.Position.Character @@ -21,7 +24,7 @@ func TextDocumentCompletion(context *glsp.Context, params *protocol.CompletionPa entry, matchBlock := d.Config.FindOption(line) - if entry == nil { + if entry == nil || entry.Separator == nil { // Empty line return handlers.GetRootCompletions( d, From ea6fdd8cda3c590dbca5c8b30d386fbae57268ec Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Wed, 11 Sep 2024 23:11:09 +0200 Subject: [PATCH 017/133] fix: Add missing lsp handlers to the root-handler --- root-handler/text-document-did-change.go | 5 +++-- root-handler/text-document-did-open.go | 3 ++- root-handler/workspace-execute-command.go | 3 +++ 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/root-handler/text-document-did-change.go b/root-handler/text-document-did-change.go index a6291af..295a091 100644 --- a/root-handler/text-document-did-change.go +++ b/root-handler/text-document-did-change.go @@ -4,6 +4,7 @@ import ( aliases "config-lsp/handlers/aliases/lsp" fstab "config-lsp/handlers/fstab/lsp" hosts "config-lsp/handlers/hosts/lsp" + sshdconfig "config-lsp/handlers/sshd_config/lsp" wireguard "config-lsp/handlers/wireguard/lsp" "github.com/tliron/glsp" @@ -41,7 +42,7 @@ func TextDocumentDidChange(context *glsp.Context, params *protocol.DidChangeText case LanguageFstab: return fstab.TextDocumentDidOpen(context, params) case LanguageSSHDConfig: - break + return sshdconfig.TextDocumentDidOpen(context, params) case LanguageWireguard: return wireguard.TextDocumentDidOpen(context, params) case LanguageHosts: @@ -55,7 +56,7 @@ func TextDocumentDidChange(context *glsp.Context, params *protocol.DidChangeText case LanguageFstab: return fstab.TextDocumentDidChange(context, params) case LanguageSSHDConfig: - return nil + return sshdconfig.TextDocumentDidChange(context, params) case LanguageWireguard: return wireguard.TextDocumentDidChange(context, params) case LanguageHosts: diff --git a/root-handler/text-document-did-open.go b/root-handler/text-document-did-open.go index 799d6aa..3d18585 100644 --- a/root-handler/text-document-did-open.go +++ b/root-handler/text-document-did-open.go @@ -7,6 +7,7 @@ import ( aliases "config-lsp/handlers/aliases/lsp" fstab "config-lsp/handlers/fstab/lsp" hosts "config-lsp/handlers/hosts/lsp" + sshdconfig "config-lsp/handlers/sshd_config/lsp" wireguard "config-lsp/handlers/wireguard/lsp" "github.com/tliron/glsp" @@ -33,7 +34,7 @@ func TextDocumentDidOpen(context *glsp.Context, params *protocol.DidOpenTextDocu case LanguageFstab: return fstab.TextDocumentDidOpen(context, params) case LanguageSSHDConfig: - break + return sshdconfig.TextDocumentDidOpen(context, params) case LanguageWireguard: return wireguard.TextDocumentDidOpen(context, params) case LanguageHosts: diff --git a/root-handler/workspace-execute-command.go b/root-handler/workspace-execute-command.go index dd7f906..506384e 100644 --- a/root-handler/workspace-execute-command.go +++ b/root-handler/workspace-execute-command.go @@ -1,6 +1,7 @@ package roothandler import ( + aliases "config-lsp/handlers/aliases/lsp" hosts "config-lsp/handlers/hosts/lsp" wireguard "config-lsp/handlers/wireguard/lsp" @@ -21,6 +22,8 @@ func WorkspaceExecuteCommand(context *glsp.Context, params *protocol.ExecuteComm edit, err = wireguard.WorkspaceExecuteCommand(context, params) case "hosts": edit, err = hosts.WorkspaceExecuteCommand(context, params) + case "aliases": + edit, err = aliases.WorkspaceExecuteCommand(context, params) } if err != nil { From 47c511996b18be4259b7ef024847f94e646b2615 Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Thu, 12 Sep 2024 21:39:28 +0200 Subject: [PATCH 018/133] feat(sshd_config): Add analyzer to check whether values are valid --- doc-values/value-key-value-assignment.go | 2 +- handlers/sshd_config/analyzer/analyzer.go | 14 +++++ handlers/sshd_config/analyzer/options.go | 60 +++++++++++++++++++ handlers/sshd_config/ast/sshd_config.go | 9 +++ handlers/sshd_config/handlers/completions.go | 44 +++++++++++--- .../lsp/text-document-completion.go | 16 ++++- 6 files changed, 134 insertions(+), 11 deletions(-) create mode 100644 handlers/sshd_config/analyzer/options.go diff --git a/doc-values/value-key-value-assignment.go b/doc-values/value-key-value-assignment.go index ec37ca7..cda5c3c 100644 --- a/doc-values/value-key-value-assignment.go +++ b/doc-values/value-key-value-assignment.go @@ -104,7 +104,7 @@ func (v KeyValueAssignmentValue) CheckIsValid(value string) []*InvalidValue { } func (v KeyValueAssignmentValue) FetchCompletions(line string, cursor uint32) []protocol.CompletionItem { - if cursor == 0 { + if cursor == 0 || line == "" { return v.Key.FetchCompletions(line, cursor) } diff --git a/handlers/sshd_config/analyzer/analyzer.go b/handlers/sshd_config/analyzer/analyzer.go index 4635a05..77cf4c2 100644 --- a/handlers/sshd_config/analyzer/analyzer.go +++ b/handlers/sshd_config/analyzer/analyzer.go @@ -1,12 +1,26 @@ package analyzer import ( + "config-lsp/common" "config-lsp/handlers/sshd_config" + "config-lsp/utils" + protocol "github.com/tliron/glsp/protocol_3_16" ) func Analyze( d *sshdconfig.SSHDocument, ) []protocol.Diagnostic { + errors := analyzeOptionsAreValid(d) + + if len(errors) > 0 { + return utils.Map( + errors, + func(err common.LSPError) protocol.Diagnostic { + return err.ToDiagnostic() + }, + ) + } + return nil } diff --git a/handlers/sshd_config/analyzer/options.go b/handlers/sshd_config/analyzer/options.go new file mode 100644 index 0000000..58132b3 --- /dev/null +++ b/handlers/sshd_config/analyzer/options.go @@ -0,0 +1,60 @@ +package analyzer + +import ( + "config-lsp/common" + docvalues "config-lsp/doc-values" + sshdconfig "config-lsp/handlers/sshd_config" + "config-lsp/handlers/sshd_config/ast" + "config-lsp/handlers/sshd_config/fields" + "config-lsp/utils" + "errors" + "fmt" +) + +func analyzeOptionsAreValid( + d *sshdconfig.SSHDocument, +) []common.LSPError { + errs := make([]common.LSPError, 0) + it := d.Config.Options.Iterator() + + for it.Next() { + line := it.Key().(uint32) + entry := it.Value().(ast.SSHEntry) + + option := entry.GetOption() + + if option.Key != nil { + docOption, found := fields.Options[option.Key.Value] + + if !found { + errs = append(errs, common.LSPError{ + Range: option.Key.LocationRange, + Err: errors.New(fmt.Sprintf("Unknown option: %s", option.Key.Value)), + }) + continue + } + + if option.OptionValue == nil { + continue + } + + invalidValues := docOption.CheckIsValid(option.OptionValue.Value) + + errs = append( + errs, + utils.Map( + invalidValues, + func(invalidValue *docvalues.InvalidValue) common.LSPError { + err := docvalues.LSPErrorFromInvalidValue(line, *invalidValue) + err.ShiftCharacter(option.OptionValue.Start.Character) + + return err + }, + )..., + ) + + } + } + + return errs +} diff --git a/handlers/sshd_config/ast/sshd_config.go b/handlers/sshd_config/ast/sshd_config.go index 25897e9..2f24577 100644 --- a/handlers/sshd_config/ast/sshd_config.go +++ b/handlers/sshd_config/ast/sshd_config.go @@ -25,6 +25,7 @@ const ( type SSHEntry interface { GetType() SSHEntryType + GetOption() SSHOption } type SSHSeparator struct { @@ -44,6 +45,10 @@ func (o SSHOption) GetType() SSHEntryType { return SSHEntryTypeOption } +func (o SSHOption) GetOption() SSHOption { + return o +} + type SSHMatchBlock struct { common.LocationRange MatchEntry *SSHOption @@ -56,6 +61,10 @@ func (m SSHMatchBlock) GetType() SSHEntryType { return SSHEntryTypeMatchBlock } +func (m SSHMatchBlock) GetOption() SSHOption { + return *m.MatchEntry +} + type SSHConfig struct { // [uint32]SSHOption -> line number -> *SSHEntry Options *treemap.Map diff --git a/handlers/sshd_config/handlers/completions.go b/handlers/sshd_config/handlers/completions.go index a23d656..8d7814a 100644 --- a/handlers/sshd_config/handlers/completions.go +++ b/handlers/sshd_config/handlers/completions.go @@ -13,23 +13,51 @@ import ( func GetRootCompletions( d *sshdconfig.SSHDocument, parentMatchBlock *ast.SSHMatchBlock, + suggestValue bool, ) ([]protocol.CompletionItem, error) { kind := protocol.CompletionItemKindField - format := protocol.InsertTextFormatSnippet return utils.MapMapToSlice( fields.Options, func(name string, rawValue docvalues.Value) protocol.CompletionItem { doc := rawValue.(docvalues.DocumentationValue) - insertText := name + " " + "${1:value}" - return protocol.CompletionItem{ - Label: name, - Kind: &kind, - Documentation: doc.Documentation, - InsertText: &insertText, - InsertTextFormat: &format, + completion := &protocol.CompletionItem{ + Label: name, + Kind: &kind, + Documentation: doc.Documentation, } + + if suggestValue { + format := protocol.InsertTextFormatSnippet + insertText := name + " " + "${1:value}" + + completion.InsertTextFormat = &format + completion.InsertText = &insertText + } + + return *completion }, ), nil } + +func GetOptionCompletions( + d *sshdconfig.SSHDocument, + entry *ast.SSHOption, + cursor uint32, +) ([]protocol.CompletionItem, error) { + option, found := fields.Options[entry.Key.Value] + + if !found { + return nil, nil + } + + if entry.OptionValue == nil { + return option.FetchCompletions("", 0), nil + } + + relativeCursor := cursor - entry.OptionValue.Start.Character + line := entry.OptionValue.Value + + return option.FetchCompletions(line, relativeCursor), nil +} diff --git a/handlers/sshd_config/lsp/text-document-completion.go b/handlers/sshd_config/lsp/text-document-completion.go index 7f9c3a2..f207837 100644 --- a/handlers/sshd_config/lsp/text-document-completion.go +++ b/handlers/sshd_config/lsp/text-document-completion.go @@ -1,6 +1,7 @@ package lsp import ( + "config-lsp/common" sshdconfig "config-lsp/handlers/sshd_config" "config-lsp/handlers/sshd_config/handlers" "regexp" @@ -14,7 +15,6 @@ var containsSeparatorPattern = regexp.MustCompile(`\s+$`) func TextDocumentCompletion(context *glsp.Context, params *protocol.CompletionParams) (any, error) { line := params.Position.Line cursor := params.Position.Character - _ = cursor d := sshdconfig.DocumentParserMap[params.TextDocument.URI] @@ -24,11 +24,23 @@ func TextDocumentCompletion(context *glsp.Context, params *protocol.CompletionPa entry, matchBlock := d.Config.FindOption(line) - if entry == nil || entry.Separator == nil { + if entry == nil || + entry.Separator == nil || + entry.Key == nil || + (common.CursorToCharacterIndex(cursor)) <= entry.Key.End.Character { // Empty line return handlers.GetRootCompletions( d, matchBlock, + entry == nil || containsSeparatorPattern.Match([]byte(entry.Value)), + ) + } + + if entry.Separator != nil && cursor > entry.Separator.End.Character { + return handlers.GetOptionCompletions( + d, + entry, + cursor, ) } From 998c0740d1adc53ec03d6149ca3339d7471f6302 Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Thu, 12 Sep 2024 23:15:23 +0200 Subject: [PATCH 019/133] feat(sshd_config): Add indexes --- handlers/sshd_config/analyzer/analyzer.go | 15 +++ handlers/sshd_config/ast/parser_test.go | 2 +- handlers/sshd_config/ast/sshd_config.go | 7 +- handlers/sshd_config/indexes/indexes.go | 88 ++++++++++++++++ handlers/sshd_config/indexes/indexes_test.go | 105 +++++++++++++++++++ 5 files changed, 215 insertions(+), 2 deletions(-) create mode 100644 handlers/sshd_config/indexes/indexes.go create mode 100644 handlers/sshd_config/indexes/indexes_test.go diff --git a/handlers/sshd_config/analyzer/analyzer.go b/handlers/sshd_config/analyzer/analyzer.go index 77cf4c2..7f93902 100644 --- a/handlers/sshd_config/analyzer/analyzer.go +++ b/handlers/sshd_config/analyzer/analyzer.go @@ -3,6 +3,7 @@ package analyzer import ( "config-lsp/common" "config-lsp/handlers/sshd_config" + "config-lsp/handlers/sshd_config/indexes" "config-lsp/utils" protocol "github.com/tliron/glsp/protocol_3_16" @@ -22,5 +23,19 @@ func Analyze( ) } + indexes, indexErrors := indexes.CreateIndexes(*d.Config) + _ = indexes + + errors = append(errors, indexErrors...) + + if len(errors) > 0 { + return utils.Map( + errors, + func(err common.LSPError) protocol.Diagnostic { + return err.ToDiagnostic() + }, + ) + } + return nil } diff --git a/handlers/sshd_config/ast/parser_test.go b/handlers/sshd_config/ast/parser_test.go index 9ea5e09..c7c4876 100644 --- a/handlers/sshd_config/ast/parser_test.go +++ b/handlers/sshd_config/ast/parser_test.go @@ -158,7 +158,7 @@ Match 192.168.0.2 t.Errorf("Expected sixth entry to be 'MaxAuthTries 3', but got: %v", sixthEntry.Value) } - firstOption, firstMatchBlock := p.FindOption(uint32(4)) + firstOption, firstMatchBlock := p.FindOption(uint32(3)) if !(firstOption.Key.Value == "PasswordAuthentication" && firstOption.OptionValue.Value == "yes" && firstMatchBlock.MatchEntry.Value == "Match 192.168.0.1") { t.Errorf("Expected first option to be 'PasswordAuthentication yes' and first match block to be 'Match 192.168.0.1', but got: %v, %v", firstOption, firstMatchBlock) diff --git a/handlers/sshd_config/ast/sshd_config.go b/handlers/sshd_config/ast/sshd_config.go index 2f24577..5b30c37 100644 --- a/handlers/sshd_config/ast/sshd_config.go +++ b/handlers/sshd_config/ast/sshd_config.go @@ -103,7 +103,12 @@ func (c SSHConfig) FindOption(line uint32) (*SSHOption, *SSHMatchBlock) { rawEntry, found := c.Options.Get(line) if found { - return rawEntry.(*SSHOption), nil + switch rawEntry.(type) { + case *SSHMatchBlock: + return rawEntry.(*SSHMatchBlock).MatchEntry, rawEntry.(*SSHMatchBlock) + case *SSHOption: + return rawEntry.(*SSHOption), nil + } } return nil, nil diff --git a/handlers/sshd_config/indexes/indexes.go b/handlers/sshd_config/indexes/indexes.go new file mode 100644 index 0000000..5f46a41 --- /dev/null +++ b/handlers/sshd_config/indexes/indexes.go @@ -0,0 +1,88 @@ +package indexes + +import ( + "config-lsp/common" + "config-lsp/handlers/sshd_config/ast" + "errors" + "fmt" +) + +var allowedDoubleOptions = map[string]struct{}{ + "AllowGroups": {}, + "AllowUsers": {}, + "DenyGroups": {}, + "DenyUsers": {}, + "ListenAddress": {}, + "Match": {}, + "Port": {}, +} + +type SSHIndexEntry struct { + Option string + MatchBlock *ast.SSHMatchBlock +} + +type SSHIndexes struct { + EntriesPerKey map[SSHIndexEntry][]*ast.SSHOption +} + +func CreateIndexes(config ast.SSHConfig) (*SSHIndexes, []common.LSPError) { + errs := make([]common.LSPError, 0) + indexes := &SSHIndexes{ + EntriesPerKey: make(map[SSHIndexEntry][]*ast.SSHOption), + } + + it := config.Options.Iterator() + + for it.Next() { + entry := it.Value().(ast.SSHEntry) + + switch entry.(type) { + case *ast.SSHOption: + option := entry.(*ast.SSHOption) + + errs = append(errs, addOption(indexes, option, nil)...) + case *ast.SSHMatchBlock: + matchBlock := entry.(*ast.SSHMatchBlock) + + it := matchBlock.Options.Iterator() + + for it.Next() { + option := it.Value().(*ast.SSHOption) + + errs = append(errs, addOption(indexes, option, matchBlock)...) + } + } + } + + return indexes, errs +} + +func addOption( + i *SSHIndexes, + option *ast.SSHOption, + matchBlock *ast.SSHMatchBlock, +) []common.LSPError { + var errs []common.LSPError + + indexEntry := SSHIndexEntry{ + Option: option.Key.Value, + MatchBlock: matchBlock, + } + + if existingEntry, found := i.EntriesPerKey[indexEntry]; found { + if _, found := allowedDoubleOptions[option.Key.Value]; found { + // Double value, but doubles are allowed + i.EntriesPerKey[indexEntry] = append(existingEntry, option) + } else { + errs = append(errs, common.LSPError{ + Range: option.Key.LocationRange, + Err: errors.New(fmt.Sprintf("Option %s is already defined on line %d", option.Key.Value, existingEntry[0].Start.Line+1)), + }) + } + } else { + i.EntriesPerKey[indexEntry] = []*ast.SSHOption{option} + } + + return errs +} diff --git a/handlers/sshd_config/indexes/indexes_test.go b/handlers/sshd_config/indexes/indexes_test.go new file mode 100644 index 0000000..e9dec93 --- /dev/null +++ b/handlers/sshd_config/indexes/indexes_test.go @@ -0,0 +1,105 @@ +package indexes + +import ( + "config-lsp/handlers/sshd_config/ast" + "config-lsp/utils" + "testing" +) + +func TestSimpleExample( + t *testing.T, +) { + input := utils.Dedent(` +PermitRootLogin yes +RootLogin yes +PermitRootLogin no +`) + config := ast.NewSSHConfig() + errors := config.Parse(input) + + if len(errors) > 0 { + t.Fatalf("Unexpected errors: %v", errors) + } + + indexes, errors := CreateIndexes(*config) + + if !(len(errors) == 1) { + t.Fatalf("Expected 1 error, but got %v", len(errors)) + } + + indexEntry := SSHIndexEntry{ + Option: "PermitRootLogin", + MatchBlock: nil, + } + if !(indexes.EntriesPerKey[indexEntry][0].Value == "PermitRootLogin yes" && indexes.EntriesPerKey[indexEntry][0].Start.Line == 0) { + t.Errorf("Expected 'PermitRootLogin yes', but got %v", indexes.EntriesPerKey[indexEntry][0].Value) + } + + indexEntry = SSHIndexEntry{ + Option: "RootLogin", + MatchBlock: nil, + } + if !(indexes.EntriesPerKey[indexEntry][0].Value == "RootLogin yes" && indexes.EntriesPerKey[indexEntry][0].Start.Line == 1) { + t.Errorf("Expected 'RootLogin yes', but got %v", indexes.EntriesPerKey[indexEntry][0].Value) + } +} + +func TestComplexExample( + t *testing.T, +) { + input := utils.Dedent(` +PermitRootLogin yes +Port 22 +Port 2022 +Port 2024 + +Match Address 192.168.0.1/24 + PermitRootLogin no + RoomLogin yes + PermitRootLogin yes +`) + config := ast.NewSSHConfig() + errors := config.Parse(input) + + if len(errors) > 0 { + t.Fatalf("Expected no errors, but got %v", len(errors)) + } + + indexes, errors := CreateIndexes(*config) + + if !(len(errors) == 1) { + t.Fatalf("Expected no errors, but got %v", len(errors)) + } + + indexEntry := SSHIndexEntry{ + Option: "PermitRootLogin", + MatchBlock: nil, + } + if !(indexes.EntriesPerKey[indexEntry][0].Value == "PermitRootLogin yes" && indexes.EntriesPerKey[indexEntry][0].Start.Line == 0) { + t.Errorf("Expected 'PermitRootLogin yes' on line 0, but got %v on line %v", indexes.EntriesPerKey[indexEntry][0].Value, indexes.EntriesPerKey[indexEntry][0].Start.Line) + } + + firstMatchBlock := config.FindMatchBlock(uint32(6)) + indexEntry = SSHIndexEntry{ + Option: "PermitRootLogin", + MatchBlock: firstMatchBlock, + } + if !(indexes.EntriesPerKey[indexEntry][0].Value == "\tPermitRootLogin no" && indexes.EntriesPerKey[indexEntry][0].Start.Line == 6) { + t.Errorf("Expected 'PermitRootLogin no' on line 6, but got %v on line %v", indexes.EntriesPerKey[indexEntry][0].Value, indexes.EntriesPerKey[indexEntry][0].Start.Line) + } + + // Double check + indexEntry = SSHIndexEntry{ + Option: "Port", + MatchBlock: nil, + } + if !(indexes.EntriesPerKey[indexEntry][0].Value == "Port 22" && + indexes.EntriesPerKey[indexEntry][0].Start.Line == 1 && + len(indexes.EntriesPerKey[indexEntry]) == 3 && + indexes.EntriesPerKey[indexEntry][1].Value == "Port 2022" && + indexes.EntriesPerKey[indexEntry][1].Start.Line == 2 && + indexes.EntriesPerKey[indexEntry][2].Value == "Port 2024" && + indexes.EntriesPerKey[indexEntry][2].Start.Line == 3) { + t.Errorf("Expected 'Port 22' on line 1, but got %v on line %v", indexes.EntriesPerKey[indexEntry][0].Value, indexes.EntriesPerKey[indexEntry][0].Start.Line) + } +} From 22cbfb711c370bbbe027833551146a6cf9fa415f Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Thu, 12 Sep 2024 23:25:56 +0200 Subject: [PATCH 020/133] fix(sshd_config): Improve completions --- handlers/sshd_config/analyzer/analyzer.go | 10 ---------- handlers/sshd_config/lsp/text-document-completion.go | 7 ++++--- 2 files changed, 4 insertions(+), 13 deletions(-) diff --git a/handlers/sshd_config/analyzer/analyzer.go b/handlers/sshd_config/analyzer/analyzer.go index 7f93902..3bee59b 100644 --- a/handlers/sshd_config/analyzer/analyzer.go +++ b/handlers/sshd_config/analyzer/analyzer.go @@ -13,16 +13,6 @@ func Analyze( d *sshdconfig.SSHDocument, ) []protocol.Diagnostic { errors := analyzeOptionsAreValid(d) - - if len(errors) > 0 { - return utils.Map( - errors, - func(err common.LSPError) protocol.Diagnostic { - return err.ToDiagnostic() - }, - ) - } - indexes, indexErrors := indexes.CreateIndexes(*d.Config) _ = indexes diff --git a/handlers/sshd_config/lsp/text-document-completion.go b/handlers/sshd_config/lsp/text-document-completion.go index f207837..db7fc30 100644 --- a/handlers/sshd_config/lsp/text-document-completion.go +++ b/handlers/sshd_config/lsp/text-document-completion.go @@ -10,7 +10,7 @@ import ( protocol "github.com/tliron/glsp/protocol_3_16" ) -var containsSeparatorPattern = regexp.MustCompile(`\s+$`) +var isEmptyPattern = regexp.MustCompile(`^\s*$`) func TextDocumentCompletion(context *glsp.Context, params *protocol.CompletionParams) (any, error) { line := params.Position.Line @@ -28,11 +28,12 @@ func TextDocumentCompletion(context *glsp.Context, params *protocol.CompletionPa entry.Separator == nil || entry.Key == nil || (common.CursorToCharacterIndex(cursor)) <= entry.Key.End.Character { - // Empty line + return handlers.GetRootCompletions( d, matchBlock, - entry == nil || containsSeparatorPattern.Match([]byte(entry.Value)), + // Empty line, or currently typing a new key + entry == nil || isEmptyPattern.Match([]byte(entry.Value[cursor:])), ) } From 9f76fedabb48f81ccfedc4649a495e97d5a5b9fd Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Thu, 12 Sep 2024 23:51:19 +0200 Subject: [PATCH 021/133] feat(sshd_config): Only show allowed completions inside a Match block --- handlers/sshd_config/ast/parser_test.go | 6 +- handlers/sshd_config/ast/sshd_config.go | 2 + handlers/sshd_config/fields/match.go | 63 ++++++++++++++++++++ handlers/sshd_config/handlers/completions.go | 14 ++++- 4 files changed, 83 insertions(+), 2 deletions(-) create mode 100644 handlers/sshd_config/fields/match.go diff --git a/handlers/sshd_config/ast/parser_test.go b/handlers/sshd_config/ast/parser_test.go index c7c4876..1cea847 100644 --- a/handlers/sshd_config/ast/parser_test.go +++ b/handlers/sshd_config/ast/parser_test.go @@ -159,10 +159,14 @@ Match 192.168.0.2 } firstOption, firstMatchBlock := p.FindOption(uint32(3)) - if !(firstOption.Key.Value == "PasswordAuthentication" && firstOption.OptionValue.Value == "yes" && firstMatchBlock.MatchEntry.Value == "Match 192.168.0.1") { t.Errorf("Expected first option to be 'PasswordAuthentication yes' and first match block to be 'Match 192.168.0.1', but got: %v, %v", firstOption, firstMatchBlock) } + + emptyOption, matchBlock := p.FindOption(uint32(5)) + if !(emptyOption == nil && matchBlock.MatchEntry.Value == "Match 192.168.0.1") { + t.Errorf("Expected empty option and match block to be 'Match 192.168.0.1', but got: %v, %v", emptyOption, matchBlock) + } } func TestSimpleExampleWithComments( diff --git a/handlers/sshd_config/ast/sshd_config.go b/handlers/sshd_config/ast/sshd_config.go index 5b30c37..818aa9b 100644 --- a/handlers/sshd_config/ast/sshd_config.go +++ b/handlers/sshd_config/ast/sshd_config.go @@ -97,6 +97,8 @@ func (c SSHConfig) FindOption(line uint32) (*SSHOption, *SSHMatchBlock) { if found { return rawEntry.(*SSHOption), matchBlock + } else { + return nil, matchBlock } } diff --git a/handlers/sshd_config/fields/match.go b/handlers/sshd_config/fields/match.go new file mode 100644 index 0000000..332c699 --- /dev/null +++ b/handlers/sshd_config/fields/match.go @@ -0,0 +1,63 @@ +package fields + +var MatchAllowedOptions = map[string]struct{}{ + "AcceptEnv": {}, + "AllowAgentForwarding": {}, + "AllowGroups": {}, + "AllowStreamLocalForwarding": {}, + "AllowTcpForwarding": {}, + "AllowUsers": {}, + "AuthenticationMethods": {}, + "AuthorizedKeysCommand": {}, + "AuthorizedKeysCommandUser": {}, + "AuthorizedKeysFile": {}, + "AuthorizedPrincipalsCommand": {}, + "AuthorizedPrincipalsCommandUser": {}, + "AuthorizedPrincipalsFile": {}, + "Banner": {}, + "CASignatureAlgorithms": {}, + "ChannelTimeout": {}, + "ChrootDirectory": {}, + "ClientAliveCountMax": {}, + "ClientAliveInterval": {}, + "DenyGroups": {}, + "DenyUsers": {}, + "DisableForwarding": {}, + "ExposeAuthInfo": {}, + "ForceCommand": {}, + "GatewayPorts": {}, + "GSSAPIAuthentication": {}, + "HostbasedAcceptedAlgorithms": {}, + "HostbasedAuthentication": {}, + "HostbasedUsesNameFromPacketOnly": {}, + "IgnoreRhosts": {}, + "Include": {}, + "IPQoS": {}, + "KbdInteractiveAuthentication": {}, + "KerberosAuthentication": {}, + "LogLevel": {}, + "MaxAuthTries": {}, + "MaxSessions": {}, + "PasswordAuthentication": {}, + "PermitEmptyPasswords": {}, + "PermitListen": {}, + "PermitOpen": {}, + "PermitRootLogin": {}, + "PermitTTY": {}, + "PermitTunnel": {}, + "PermitUserRC": {}, + "PubkeyAcceptedAlgorithms": {}, + "PubkeyAuthentication": {}, + "PubkeyAuthOptions": {}, + "RekeyLimit": {}, + "RevokedKeys": {}, + "RDomain": {}, + "SetEnv": {}, + "StreamLocalBindMask": {}, + "StreamLocalBindUnlink": {}, + "TrustedUserCAKeys": {}, + "UnusedConnectionTimeout": {}, + "X11DisplayOffset": {}, + "X11Forwarding": {}, + "X11UseLocalhos": {}, +} diff --git a/handlers/sshd_config/handlers/completions.go b/handlers/sshd_config/handlers/completions.go index 8d7814a..cf8d1dd 100644 --- a/handlers/sshd_config/handlers/completions.go +++ b/handlers/sshd_config/handlers/completions.go @@ -17,8 +17,20 @@ func GetRootCompletions( ) ([]protocol.CompletionItem, error) { kind := protocol.CompletionItemKindField + availableOptions := make(map[string]docvalues.Value) + + if parentMatchBlock == nil { + availableOptions = fields.Options + } else { + for option := range fields.MatchAllowedOptions { + if opt, found := fields.Options[option]; found { + availableOptions[option] = opt + } + } + } + return utils.MapMapToSlice( - fields.Options, + availableOptions, func(name string, rawValue docvalues.Value) protocol.CompletionItem { doc := rawValue.(docvalues.DocumentationValue) From 3a1320964892daa76b93558ac580065240486f9f Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Thu, 12 Sep 2024 23:51:40 +0200 Subject: [PATCH 022/133] chore: Add packages to flake.nix --- flake.nix | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/flake.nix b/flake.nix index 337a65a..e0ffd36 100644 --- a/flake.nix +++ b/flake.nix @@ -26,7 +26,6 @@ }; inputs = [ pkgs.go_1_22 - pkgs.wireguard-tools ]; in { packages = { @@ -44,7 +43,8 @@ devShells.default = pkgs.mkShell { buildInputs = inputs ++ (with pkgs; [ mailutils - swaks + postfix + wireguard-tools ]); }; } From b9f6ed875854a8b0fbcf7420151622e94c83cc72 Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Thu, 12 Sep 2024 23:51:57 +0200 Subject: [PATCH 023/133] feat: Add more common utils --- common/lsp.go | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 common/lsp.go diff --git a/common/lsp.go b/common/lsp.go new file mode 100644 index 0000000..eede1be --- /dev/null +++ b/common/lsp.go @@ -0,0 +1,5 @@ +package common + +func CursorToCharacterIndex(cursor uint32) uint32 { + return max(0, cursor-1) +} From f25c11b966fc00190158d748ab96db08b677d257 Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Fri, 13 Sep 2024 21:45:44 +0200 Subject: [PATCH 024/133] feat(sshd_config): Add Matcbh block for completions --- handlers/sshd_config/ast/parser_test.go | 5 ++++ handlers/sshd_config/ast/sshd_config.go | 4 +++ handlers/sshd_config/fields/fields.go | 33 +++++++++++++++++++++---- 3 files changed, 37 insertions(+), 5 deletions(-) diff --git a/handlers/sshd_config/ast/parser_test.go b/handlers/sshd_config/ast/parser_test.go index 1cea847..c2135d2 100644 --- a/handlers/sshd_config/ast/parser_test.go +++ b/handlers/sshd_config/ast/parser_test.go @@ -167,6 +167,11 @@ Match 192.168.0.2 if !(emptyOption == nil && matchBlock.MatchEntry.Value == "Match 192.168.0.1") { t.Errorf("Expected empty option and match block to be 'Match 192.168.0.1', but got: %v, %v", emptyOption, matchBlock) } + + matchOption, matchBlock := p.FindOption(uint32(2)) + if !(matchOption.Value == "Match 192.168.0.1" && matchBlock.MatchEntry.Value == "Match 192.168.0.1") { + t.Errorf("Expected match option to be 'Match 192.160.0.1' and match block to be 'Match 192.168.0.1', but got: %v, %v", matchOption, matchBlock) + } } func TestSimpleExampleWithComments( diff --git a/handlers/sshd_config/ast/sshd_config.go b/handlers/sshd_config/ast/sshd_config.go index 818aa9b..f28c5d6 100644 --- a/handlers/sshd_config/ast/sshd_config.go +++ b/handlers/sshd_config/ast/sshd_config.go @@ -93,6 +93,10 @@ func (c SSHConfig) FindOption(line uint32) (*SSHOption, *SSHMatchBlock) { matchBlock := c.FindMatchBlock(line) if matchBlock != nil { + if line == matchBlock.MatchEntry.Start.Line { + return matchBlock.MatchEntry, matchBlock + } + rawEntry, found := matchBlock.Options.Get(line) if found { diff --git a/handlers/sshd_config/fields/fields.go b/handlers/sshd_config/fields/fields.go index dc8b9d5..4de4c20 100644 --- a/handlers/sshd_config/fields/fields.go +++ b/handlers/sshd_config/fields/fields.go @@ -559,11 +559,34 @@ See PATTERNS in ssh_config(5) for more information on patterns. This keyword may }), }, - // Match Introduces a conditional block. If all of the criteria on the Match line are satisfied, the keywords on the following lines override those set in the global section of the config file, until either another Match line or the end of the file. If a keyword appears in multiple Match blocks that are satisfied, only the first instance of the keyword is applied. - // The arguments to Match are one or more criteria-pattern pairs or the single token All which matches all criteria. The available criteria are User, Group, Host, LocalAddress, LocalPort, RDomain, and Address (with RDomain representing the rdomain(4) on which the connection was received). - // The match patterns may consist of single entries or comma-separated lists and may use the wildcard and negation operators described in the “PATTERNS” section of ssh_config(5). - // The patterns in an Address criteria may additionally contain addresses to match in CIDR address/masklen format, such as 192.0.2.0/24 or 2001:db8::/32. Note that the mask length provided must be consistent with the address - it is an error to specify a mask length that is too long for the address or one with bits set in this host portion of the address. For example, 192.0.2.0/33 and 192.0.2.0/8, respectively. - // Only a subset of keywords may be used on the lines following a Match keyword. Available keywords are AcceptEnv, AllowAgentForwarding, AllowGroups, AllowStreamLocalForwarding, AllowTcpForwarding, AllowUsers, AuthenticationMethods, AuthorizedKeysCommand, AuthorizedKeysCommandUser, AuthorizedKeysFile, AuthorizedPrincipalsCommand, AuthorizedPrincipalsCommandUser, AuthorizedPrincipalsFile, Banner, CASignatureAlgorithms, ChannelTimeout, ChrootDirectory, ClientAliveCountMax, ClientAliveInterval, DenyGroups, DenyUsers, DisableForwarding, ExposeAuthInfo, ForceCommand, GatewayPorts, GSSAPIAuthentication, HostbasedAcceptedAlgorithms, HostbasedAuthentication, HostbasedUsesNameFromPacketOnly, IgnoreRhosts, Include, IPQoS, KbdInteractiveAuthentication, KerberosAuthentication, LogLevel, MaxAuthTries, MaxSessions, PasswordAuthentication, PermitEmptyPasswords, PermitListen, PermitOpen, PermitRootLogin, PermitTTY, PermitTunnel, PermitUserRC, PubkeyAcceptedAlgorithms, PubkeyAuthentication, PubkeyAuthOptions, RekeyLimit, RevokedKeys, RDomain, SetEnv, StreamLocalBindMask, StreamLocalBindUnlink, TrustedUserCAKeys, UnusedConnectionTimeout, X11DisplayOffset, X11Forwarding and X11UseLocalhost.`, + "Match": docvalues.DocumentationValue{ + Documentation: `Introduces a conditional block. If all of the criteria on the Match line are satisfied, the keywords on the following lines override those set in the global section of the config file, until either another Match line or the end of the file. If a keyword appears in multiple Match blocks that are satisfied, only the first instance of the keyword is applied. +The arguments to Match are one or more criteria-pattern pairs or the single token All which matches all criteria. The available criteria are User, Group, Host, LocalAddress, LocalPort, RDomain, and Address (with RDomain representing the rdomain(4) on which the connection was received). +The match patterns may consist of single entries or comma-separated lists and may use the wildcard and negation operators described in the “PATTERNS” section of ssh_config(5). +The patterns in an Address criteria may additionally contain addresses to match in CIDR address/masklen format, such as 192.0.2.0/24 or 2001:db8::/32. Note that the mask length provided must be consistent with the address - it is an error to specify a mask length that is too long for the address or one with bits set in this host portion of the address. For example, 192.0.2.0/33 and 192.0.2.0/8, respectively. +Only a subset of keywords may be used on the lines following a Match keyword. Available keywords are AcceptEnv, AllowAgentForwarding, AllowGroups, AllowStreamLocalForwarding, AllowTcpForwarding, AllowUsers, AuthenticationMethods, AuthorizedKeysCommand, AuthorizedKeysCommandUser, AuthorizedKeysFile, AuthorizedPrincipalsCommand, AuthorizedPrincipalsCommandUser, AuthorizedPrincipalsFile, Banner, CASignatureAlgorithms, ChannelTimeout, ChrootDirectory, ClientAliveCountMax, ClientAliveInterval, DenyGroups, DenyUsers, DisableForwarding, ExposeAuthInfo, ForceCommand, GatewayPorts, GSSAPIAuthentication, HostbasedAcceptedAlgorithms, HostbasedAuthentication, HostbasedUsesNameFromPacketOnly, IgnoreRhosts, Include, IPQoS, KbdInteractiveAuthentication, KerberosAuthentication, LogLevel, MaxAuthTries, MaxSessions, PasswordAuthentication, PermitEmptyPasswords, PermitListen, PermitOpen, PermitRootLogin, PermitTTY, PermitTunnel, PermitUserRC, PubkeyAcceptedAlgorithms, PubkeyAuthentication, PubkeyAuthOptions, RekeyLimit, RevokedKeys, RDomain, SetEnv, StreamLocalBindMask, StreamLocalBindUnlink, TrustedUserCAKeys, UnusedConnectionTimeout, X11DisplayOffset, X11Forwarding and X11UseLocalhost.`, + Value: docvalues.OrValue{ + Values: []docvalues.Value{ + docvalues.SingleEnumValue("All"), + docvalues.ArrayValue{ + Separator: ",", + DuplicatesExtractor: &docvalues.SimpleDuplicatesExtractor, + SubValue: docvalues.KeyEnumAssignmentValue{ + Separator: " ", + Values: map[docvalues.EnumString]docvalues.Value{ + docvalues.CreateEnumString("User"): docvalues.UserValue("", true), + docvalues.CreateEnumString("Group"): docvalues.GroupValue("", true), + docvalues.CreateEnumString("Host"): docvalues.StringValue{}, + docvalues.CreateEnumString("LocalAddress"): docvalues.StringValue{}, + docvalues.CreateEnumString("LocalPort"): docvalues.NumberValue{Min: &ZERO, Max: &MAX_PORT}, + docvalues.CreateEnumString("RDomain"): docvalues.StringValue{}, + docvalues.CreateEnumString("Address"): docvalues.StringValue{}, + }, + }, + }, + }, + }, + }, "MaxAuthTries": docvalues.DocumentationValue{ Documentation: `Specifies the maximum number of authentication attempts permitted per connection. Once the number of failures reaches half this value, additional failures are logged. The default is 6.`, Value: docvalues.NumberValue{Min: &ZERO}, From 0abcb043ad8b41716273d90a3431710f86695d67 Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Fri, 13 Sep 2024 22:26:22 +0200 Subject: [PATCH 025/133] fix(sshd_config): Improve analyzer for match blocks --- handlers/sshd_config/analyzer/options.go | 124 +++++++++++++----- handlers/sshd_config/fields/fields.go | 4 +- .../sshd_config/lsp/text-document-hover.go | 7 + 3 files changed, 100 insertions(+), 35 deletions(-) diff --git a/handlers/sshd_config/analyzer/options.go b/handlers/sshd_config/analyzer/options.go index 58132b3..13140f0 100644 --- a/handlers/sshd_config/analyzer/options.go +++ b/handlers/sshd_config/analyzer/options.go @@ -18,42 +18,100 @@ func analyzeOptionsAreValid( it := d.Config.Options.Iterator() for it.Next() { - line := it.Key().(uint32) entry := it.Value().(ast.SSHEntry) - option := entry.GetOption() - - if option.Key != nil { - docOption, found := fields.Options[option.Key.Value] - - if !found { - errs = append(errs, common.LSPError{ - Range: option.Key.LocationRange, - Err: errors.New(fmt.Sprintf("Unknown option: %s", option.Key.Value)), - }) - continue - } - - if option.OptionValue == nil { - continue - } - - invalidValues := docOption.CheckIsValid(option.OptionValue.Value) - - errs = append( - errs, - utils.Map( - invalidValues, - func(invalidValue *docvalues.InvalidValue) common.LSPError { - err := docvalues.LSPErrorFromInvalidValue(line, *invalidValue) - err.ShiftCharacter(option.OptionValue.Start.Character) - - return err - }, - )..., - ) - + switch entry.(type) { + case *ast.SSHOption: + errs = append(errs, checkOption(entry.(*ast.SSHOption), false)...) + case *ast.SSHMatchBlock: + matchBlock := entry.(*ast.SSHMatchBlock) + errs = append(errs, checkMatchBlock(matchBlock)...) } + + } + + return errs +} + +func checkOption( + option *ast.SSHOption, + isInMatchBlock bool, +) []common.LSPError { + errs := make([]common.LSPError, 0) + + if option.Key != nil { + docOption, found := fields.Options[option.Key.Value] + + if !found { + errs = append(errs, common.LSPError{ + Range: option.Key.LocationRange, + Err: errors.New(fmt.Sprintf("Unknown option: %s", option.Key.Value)), + }) + + return errs + } + + if _, found := fields.MatchAllowedOptions[option.Key.Value]; !found && isInMatchBlock { + errs = append(errs, common.LSPError{ + Range: option.Key.LocationRange, + Err: errors.New(fmt.Sprintf("Option '%s' is not allowed inside Match blocks", option.Key.Value)), + }) + + return errs + } + + if option.OptionValue == nil { + return errs + } + + invalidValues := docOption.CheckIsValid(option.OptionValue.Value) + + errs = append( + errs, + utils.Map( + invalidValues, + func(invalidValue *docvalues.InvalidValue) common.LSPError { + err := docvalues.LSPErrorFromInvalidValue(option.Start.Line, *invalidValue) + err.ShiftCharacter(option.OptionValue.Start.Character) + + return err + }, + )..., + ) + } + + return errs +} + +func checkMatchBlock( + matchBlock *ast.SSHMatchBlock, +) []common.LSPError { + errs := make([]common.LSPError, 0) + + matchOption := matchBlock.MatchEntry.OptionValue + if matchOption != nil { + invalidValues := fields.Options["Match"].CheckIsValid(matchOption.Value) + + errs = append( + errs, + utils.Map( + invalidValues, + func(invalidValue *docvalues.InvalidValue) common.LSPError { + err := docvalues.LSPErrorFromInvalidValue(matchBlock.Start.Line, *invalidValue) + err.ShiftCharacter(matchOption.Start.Character) + + return err + }, + )..., + ) + } + + it := matchBlock.Options.Iterator() + + for it.Next() { + option := it.Value().(*ast.SSHOption) + + errs = append(errs, checkOption(option, true)...) } return errs diff --git a/handlers/sshd_config/fields/fields.go b/handlers/sshd_config/fields/fields.go index 4de4c20..41a233c 100644 --- a/handlers/sshd_config/fields/fields.go +++ b/handlers/sshd_config/fields/fields.go @@ -574,8 +574,8 @@ Only a subset of keywords may be used on the lines following a Match keyword. Av SubValue: docvalues.KeyEnumAssignmentValue{ Separator: " ", Values: map[docvalues.EnumString]docvalues.Value{ - docvalues.CreateEnumString("User"): docvalues.UserValue("", true), - docvalues.CreateEnumString("Group"): docvalues.GroupValue("", true), + docvalues.CreateEnumString("User"): docvalues.StringValue{}, + docvalues.CreateEnumString("Group"): docvalues.StringValue{}, docvalues.CreateEnumString("Host"): docvalues.StringValue{}, docvalues.CreateEnumString("LocalAddress"): docvalues.StringValue{}, docvalues.CreateEnumString("LocalPort"): docvalues.NumberValue{Min: &ZERO, Max: &MAX_PORT}, diff --git a/handlers/sshd_config/lsp/text-document-hover.go b/handlers/sshd_config/lsp/text-document-hover.go index 61d19cd..bb73a41 100644 --- a/handlers/sshd_config/lsp/text-document-hover.go +++ b/handlers/sshd_config/lsp/text-document-hover.go @@ -9,5 +9,12 @@ func TextDocumentHover( context *glsp.Context, params *protocol.HoverParams, ) (*protocol.Hover, error) { + // line := params.Position.Line + // cursor := params.Position.Character + // + // d := sshdconfig.DocumentParserMap[params.TextDocument.URI] + // + // entry, matchBlock := d.Config.FindOption(line) + return nil, nil } From 0453f74a3104ba24169a3293f8d95c8daf60a82a Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Sat, 14 Sep 2024 13:09:34 +0200 Subject: [PATCH 026/133] feat(sshd_config): Add hover support --- handlers/sshd_config/fields/fields.go | 198 +++++++++--------- handlers/sshd_config/handlers/completions.go | 6 +- handlers/sshd_config/handlers/hover.go | 63 ++++++ .../sshd_config/lsp/text-document-hover.go | 22 +- 4 files changed, 179 insertions(+), 110 deletions(-) create mode 100644 handlers/sshd_config/handlers/hover.go diff --git a/handlers/sshd_config/fields/fields.go b/handlers/sshd_config/fields/fields.go index 41a233c..586da43 100644 --- a/handlers/sshd_config/fields/fields.go +++ b/handlers/sshd_config/fields/fields.go @@ -9,12 +9,12 @@ var ZERO = 0 var MAX_PORT = 65535 var MAX_FILE_MODE = 0777 -var Options = map[string]docvalues.Value{ - "AcceptEnv": docvalues.DocumentationValue{ +var Options = map[string]docvalues.DocumentationValue{ + "AcceptEnv": { Documentation: `Specifies what environment variables sent by the client will be copied into the session's environ(7). See SendEnv and SetEnv in ssh_config(5) for how to configure the client. The TERM environment variable is always accepted whenever the client requests a pseudo-terminal as it is required by the protocol. Variables are specified by name, which may contain the wildcard characters ‘*’ and ‘?’. Multiple environment variables may be separated by whitespace or spread across multiple AcceptEnv directives. Be warned that some environment variables could be used to bypass restricted user environments. For this reason, care should be taken in the use of this directive. The default is not to accept any environment variables.`, Value: docvalues.StringValue{}, }, - "AddressFamily": docvalues.DocumentationValue{ + "AddressFamily": { Documentation: `Specifies which address family should be used by sshd(8). Valid arguments are any (the default), inet (use IPv4 only), or inet6 (use IPv6 only).`, Value: docvalues.EnumValue{ EnforceValues: true, @@ -25,17 +25,17 @@ var Options = map[string]docvalues.Value{ }, }, }, - "AllowAgentForwarding": docvalues.DocumentationValue{ + "AllowAgentForwarding": { Documentation: `Specifies whether ssh-agent(1) forwarding is permitted. The default is yes. Note that disabling agent forwarding does not improve security unless users are also denied shell access, as they can always install their own forwarders.`, Value: booleanEnumValue, }, - "AllowGroups": docvalues.DocumentationValue{ + "AllowGroups": { Documentation: `This keyword can be followed by a list of group name patterns, separated by spaces. If specified, login is allowed only for users whose primary group or supplementary group list matches one of the patterns. Only group names are valid; a numerical group ID is not recognized. By default, login is allowed for all groups. The allow/deny groups directives are processed in the following order: DenyGroups, AllowGroups. See PATTERNS in ssh_config(5) for more information on patterns. This keyword may appear multiple times in sshd_config with each instance appending to the list.`, Value: docvalues.GroupValue(" ", false), }, - "AllowStreamLocalForwarding": docvalues.DocumentationValue{ + "AllowStreamLocalForwarding": { Documentation: `Specifies whether StreamLocal (Unix-domain socket) forwarding is permitted. The available options are yes (the default) or all to allow StreamLocal forwarding, no to prevent all StreamLocal forwarding, local to allow local (from the perspective of ssh(1)) forwarding only or remote to allow remote forwarding only. Note that disabling StreamLocal forwarding does not improve security unless users are also denied shell access, as they can always install their own forwarders.`, Value: docvalues.EnumValue{ EnforceValues: true, @@ -48,7 +48,7 @@ See PATTERNS in ssh_config(5) for more information on patterns. This keyword may }, }, }, - "AllowTcpForwarding": docvalues.DocumentationValue{ + "AllowTcpForwarding": { Documentation: `Specifies whether TCP forwarding is permitted. The available options are yes (the default) or all to allow TCP forwarding, no to prevent all TCP forwarding, local to allow local (from the perspective of ssh(1)) forwarding only or remote to allow remote forwarding only. Note that disabling TCP forwarding does not improve security unless users are also denied shell access, as they can always install their own forwarders.`, Value: docvalues.EnumValue{ EnforceValues: true, @@ -61,12 +61,12 @@ See PATTERNS in ssh_config(5) for more information on patterns. This keyword may }, }, }, - "AllowUsers": docvalues.DocumentationValue{ + "AllowUsers": { Documentation: `This keyword can be followed by a list of user name patterns, separated by spaces. If specified, login is allowed only for user names that match one of the patterns. Only user names are valid; a numerical user ID is not recognized. By default, login is allowed for all users. If the pattern takes the form USER@HOST then USER and HOST are separately checked, restricting logins to particular users from particular hosts. HOST criteria may additionally contain addresses to match in CIDR address/masklen format. The allow/deny users directives are processed in the following order: DenyUsers, AllowUsers. See PATTERNS in ssh_config(5) for more information on patterns. This keyword may appear multiple times in sshd_config with each instance appending to the list.`, Value: docvalues.UserValue(" ", false), }, - "AuthenticationMethods": docvalues.DocumentationValue{ + "AuthenticationMethods": { Documentation: `Specifies the authentication methods that must be successfully completed for a user to be granted access. This option must be followed by one or more lists of comma-separated authentication method names, or by the single string any to indicate the default behaviour of accepting any single authentication method. If the default is overridden, then successful authentication requires completion of every method in at least one of these lists. For example, "publickey,password publickey,keyboard-interactive" would require the user to complete public key authentication, followed by either password or keyboard interactive authentication. Only methods that are next in one or more lists are offered at each stage, so for this example it would not be possible to attempt password or keyboard-interactive authentication before public key. For keyboard interactive authentication it is also possible to restrict authentication to a specific device by appending a colon followed by the device identifier bsdauth or pam. depending on the server configuration. For example, "keyboard-interactive:bsdauth" would restrict keyboard interactive authentication to the bsdauth device. @@ -110,17 +110,17 @@ See PATTERNS in ssh_config(5) for more information on patterns. This keyword may }, }, }, - "AuthorizedKeysCommand": docvalues.DocumentationValue{ + "AuthorizedKeysCommand": { Documentation: `Specifies a program to be used to look up the user's public keys. The program must be owned by root, not writable by group or others and specified by an absolute path. Arguments to AuthorizedKeysCommand accept the tokens described in the “TOKENS” section. If no arguments are specified then the username of the target user is used. The program should produce on standard output zero or more lines of authorized_keys output (see “AUTHORIZED_KEYS” in sshd(8)). AuthorizedKeysCommand is tried after the usual AuthorizedKeysFile files and will not be executed if a matching key is found there. By default, no AuthorizedKeysCommand is run.`, Value: docvalues.StringValue{}, }, - "AuthorizedKeysCommandUser": docvalues.DocumentationValue{ + "AuthorizedKeysCommandUser": { Documentation: `Specifies the user under whose account the AuthorizedKeysCommand is run. It is recommended to use a dedicated user that has no other role on the host than running authorized keys commands. If AuthorizedKeysCommand is specified but AuthorizedKeysCommandUser is not, then sshd(8) will refuse to start.`, Value: docvalues.UserValue("", true), }, - "AuthorizedKeysFile": docvalues.DocumentationValue{ + "AuthorizedKeysFile": { Documentation: `Specifies the file that contains the public keys used for user authentication. The format is described in the AUTHORIZED_KEYS FILE FORMAT section of sshd(8). Arguments to AuthorizedKeysFile accept the tokens described in the “TOKENS” section. After expansion, AuthorizedKeysFile is taken to be an absolute path or one relative to the user's home directory. Multiple files may be listed, separated by whitespace. Alternately this option may be set to none to skip checking for user keys in files. The default is ".ssh/authorized_keys .ssh/authorized_keys2".`, Value: docvalues.ArrayValue{ SubValue: docvalues.StringValue{}, @@ -128,16 +128,16 @@ See PATTERNS in ssh_config(5) for more information on patterns. This keyword may DuplicatesExtractor: &docvalues.DuplicatesAllowedExtractor, }, }, - "AuthorizedPrincipalsCommand": docvalues.DocumentationValue{ + "AuthorizedPrincipalsCommand": { Documentation: `Specifies a program to be used to generate the list of allowed certificate principals as per AuthorizedPrincipalsFile. The program must be owned by root, not writable by group or others and specified by an absolute path. Arguments to AuthorizedPrincipalsCommand accept the tokens described in the “TOKENS” section. If no arguments are specified then the username of the target user is used. The program should produce on standard output zero or more lines of AuthorizedPrincipalsFile output. If either AuthorizedPrincipalsCommand or AuthorizedPrincipalsFile is specified, then certificates offered by the client for authentication must contain a principal that is listed. By default, no AuthorizedPrincipalsCommand is run.`, Value: docvalues.StringValue{}, }, - "AuthorizedPrincipalsCommandUser": docvalues.DocumentationValue{ + "AuthorizedPrincipalsCommandUser": { Documentation: `Specifies the user under whose account the AuthorizedPrincipalsCommand is run. It is recommended to use a dedicated user that has no other role on the host than running authorized principals commands. If AuthorizedPrincipalsCommand is specified but AuthorizedPrincipalsCommandUser is not, then sshd(8) will refuse to start.`, Value: docvalues.UserValue("", true), }, - "AuthorizedPrincipalsFile": docvalues.DocumentationValue{ + "AuthorizedPrincipalsFile": { Documentation: `Specifies a file that lists principal names that are accepted for certificate authentication. When using certificates signed by a key listed in TrustedUserCAKeys, this file lists names, one of which must appear in the certificate for it to be accepted for authentication. Names are listed one per line preceded by key options (as described in “AUTHORIZED_KEYS FILE FORMAT” in sshd(8)). Empty lines and comments starting with ‘#’ are ignored. Arguments to AuthorizedPrincipalsFile accept the tokens described in the “TOKENS” section. After expansion, AuthorizedPrincipalsFile is taken to be an absolute path or one relative to the user's home directory. The default is none, i.e. not to use a principals file – in this case, the username of the user must appear in a certificate's principals list for it to be accepted. Note that AuthorizedPrincipalsFile is only used when authentication proceeds using a CA listed in TrustedUserCAKeys and is not consulted for certification authorities trusted via ~/.ssh/authorized_keys, though the principals= key option offers a similar facility (see sshd(8) for details).`, @@ -145,13 +145,13 @@ See PATTERNS in ssh_config(5) for more information on patterns. This keyword may RequiredType: docvalues.PathTypeFile, }, }, - "Banner": docvalues.DocumentationValue{ + "Banner": { Documentation: `The contents of the specified file are sent to the remote user before authentication is allowed. If the argument is none then no banner is displayed. By default, no banner is displayed.`, Value: docvalues.PathValue{ RequiredType: docvalues.PathTypeFile, }, }, - "CASignatureAlgorithms": docvalues.DocumentationValue{ + "CASignatureAlgorithms": { Documentation: `Specifies which algorithms are allowed for signing of certificates by certificate authorities (CAs). The default is: ssh-ed25519,ecdsa-sha2-nistp256, ecdsa-sha2-nistp384,ecdsa-sha2-nistp521, sk-ssh-ed25519@openssh.com, sk-ecdsa-sha2-nistp256@openssh.com, rsa-sha2-512,rsa-sha2-256 If the specified list begins with a ‘+’ character, then the specified algorithms will be appended to the default set instead of replacing them. If the specified list begins with a ‘-’ character, then the specified algorithms (including wildcards) will be removed from the default set instead of replacing them. @@ -175,7 +175,7 @@ See PATTERNS in ssh_config(5) for more information on patterns. This keyword may }, }, }, - "ChannelTimeout": docvalues.DocumentationValue{ + "ChannelTimeout": { Documentation: `Specifies whether and how quickly sshd(8) should close inactive channels. Timeouts are specified as one or more “type=interval” pairs separated by whitespace, where the “type” must be the special keyword “global” or a channel type name from the list below, optionally containing wildcard characters. The timeout value “interval” is specified in seconds or may use any of the units documented in the “TIME FORMATS” section. For example, “session=5m” would cause interactive sessions to terminate after five minutes of inactivity. Specifying a zero value disables the inactivity timeout. The special timeout “global” applies to all active channels, taken together. Traffic on any active channel will reset the timeout, but when the timeout expires then all open channels will be closed. Note that this global timeout is not matched by wildcards and must be specified explicitly. @@ -214,14 +214,14 @@ See PATTERNS in ssh_config(5) for more information on patterns. This keyword may }, }, }, - "ChrootDirectory": docvalues.DocumentationValue{ + "ChrootDirectory": { Documentation: `Specifies the pathname of a directory to chroot(2) to after authentication. At session startup sshd(8) checks that all components of the pathname are root-owned directories which are not writable by group or others. After the chroot, sshd(8) changes the working directory to the user's home directory. Arguments to ChrootDirectory accept the tokens described in the “TOKENS” section. The ChrootDirectory must contain the necessary files and directories to support the user's session. For an interactive session this requires at least a shell, typically sh(1), and basic /dev nodes such as null(4), zero(4), stdin(4), stdout(4), stderr(4), and tty(4) devices. For file transfer sessions using SFTP no additional configuration of the environment is necessary if the in-process sftp-server is used, though sessions which use logging may require /dev/log inside the chroot directory on some operating systems (see sftp-server(8) for details). For safety, it is very important that the directory hierarchy be prevented from modification by other processes on the system (especially those outside the jail). Misconfiguration can lead to unsafe environments which sshd(8) cannot detect. The default is none, indicating not to chroot(2).`, Value: docvalues.StringValue{}, }, - "Ciphers": docvalues.DocumentationValue{ + "Ciphers": { Documentation: `Specifies the ciphers allowed. Multiple ciphers must be comma-separated. If the specified list begins with a ‘+’ character, then the specified ciphers will be appended to the default set instead of replacing them. If the specified list begins with a ‘-’ character, then the specified ciphers (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a ‘^’ character, then the specified ciphers will be placed at the head of the default set. The supported ciphers are: 3des-cbc aes128-cbc aes192-cbc aes256-cbc aes128-ctr aes192-ctr aes256-ctr aes128-gcm@openssh.com aes256-gcm@openssh.com chacha20-poly1305@openssh.com @@ -241,16 +241,16 @@ See PATTERNS in ssh_config(5) for more information on patterns. This keyword may docvalues.CreateEnumString("chacha20-poly1305@openssh.com"), }), }, - "ClientAliveCountMax": docvalues.DocumentationValue{ + "ClientAliveCountMax": { Documentation: `Sets the number of client alive messages which may be sent without sshd(8) receiving any messages back from the client. If this threshold is reached while client alive messages are being sent, sshd will disconnect the client, terminating the session. It is important to note that the use of client alive messages is very different from TCPKeepAlive. The client alive messages are sent through the encrypted channel and therefore will not be spoofable. The TCP keepalive option enabled by TCPKeepAlive is spoofable. The client alive mechanism is valuable when the client or server depend on knowing when a connection has become unresponsive. The default value is 3. If ClientAliveInterval is set to 15, and ClientAliveCountMax is left at the default, unresponsive SSH clients will be disconnected after approximately 45 seconds. Setting a zero ClientAliveCountMax disables connection termination.`, Value: docvalues.NumberValue{Min: &ZERO}, }, - "ClientAliveInterval": docvalues.DocumentationValue{ + "ClientAliveInterval": { Documentation: `Sets a timeout interval in seconds after which if no data has been received from the client, sshd(8) will send a message through the encrypted channel to request a response from the client. The default is 0, indicating that these messages will not be sent to the client.`, Value: docvalues.NumberValue{Min: &ZERO}, }, - "Compression": docvalues.DocumentationValue{ + "Compression": { Documentation: `Specifies whether compression is enabled after the user has authenticated successfully. The argument must be yes, delayed (a legacy synonym for yes) or no. The default is yes.`, Value: docvalues.EnumValue{ EnforceValues: true, @@ -261,25 +261,25 @@ See PATTERNS in ssh_config(5) for more information on patterns. This keyword may }, }, }, - "DenyGroups": docvalues.DocumentationValue{ + "DenyGroups": { Documentation: `This keyword can be followed by a list of group name patterns, separated by spaces. Login is disallowed for users whose primary group or supplementary group list matches one of the patterns. Only group names are valid; a numerical group ID is not recognized. By default, login is allowed for all groups. The allow/deny groups directives are processed in the following order: DenyGroups, AllowGroups. See PATTERNS in ssh_config(5) for more information on patterns. This keyword may appear multiple times in sshd_config with each instance appending to the list.`, Value: docvalues.GroupValue(" ", false), }, - "DenyUsers": docvalues.DocumentationValue{ + "DenyUsers": { Documentation: `This keyword can be followed by a list of user name patterns, separated by spaces. Login is disallowed for user names that match one of the patterns. Only user names are valid; a numerical user ID is not recognized. By default, login is allowed for all users. If the pattern takes the form USER@HOST then USER and HOST are separately checked, restricting logins to particular users from particular hosts. HOST criteria may additionally contain addresses to match in CIDR address/masklen format. The allow/deny users directives are processed in the following order: DenyUsers, AllowUsers. See PATTERNS in ssh_config(5) for more information on patterns. This keyword may appear multiple times in sshd_config with each instance appending to the list.`, Value: docvalues.UserValue(" ", false), }, - "DisableForwarding": docvalues.DocumentationValue{ + "DisableForwarding": { Documentation: `Disables all forwarding features, including X11, ssh-agent(1), TCP and StreamLocal. This option overrides all other forwarding-related options and may simplify restricted configurations.`, Value: booleanEnumValue, }, - "ExposeAuthInfo": docvalues.DocumentationValue{ + "ExposeAuthInfo": { Documentation: `Writes a temporary file containing a list of authentication methods and public credentials (e.g. keys) used to authenticate the user. The location of the file is exposed to the user session through the SSH_USER_AUTH environment variable. The default is no.`, Value: booleanEnumValue, }, - "FingerprintHash": docvalues.DocumentationValue{ + "FingerprintHash": { Documentation: `Specifies the hash algorithm used when logging key fingerprints. Valid options are: md5 and sha256. The default is sha256.`, Value: docvalues.EnumValue{ EnforceValues: true, @@ -289,27 +289,27 @@ See PATTERNS in ssh_config(5) for more information on patterns. This keyword may }, }, }, - "ForceCommand": docvalues.DocumentationValue{ + "ForceCommand": { Documentation: `Forces the execution of the command specified by ForceCommand, ignoring any command supplied by the client and ~/.ssh/rc if present. The command is invoked by using the user's login shell with the -c option. This applies to shell, command, or subsystem execution. It is most useful inside a Match block. The command originally supplied by the client is available in the SSH_ORIGINAL_COMMAND environment variable. Specifying a command of internal-sftp will force the use of an in- process SFTP server that requires no support files when used with ChrootDirectory. The default is none.`, Value: docvalues.StringValue{}, }, - "GatewayPorts": docvalues.DocumentationValue{ + "GatewayPorts": { Documentation: `Specifies whether remote hosts are allowed to connect to ports forwarded for the client. By default, sshd(8) binds remote port forwardings to the loopback address. This prevents other remote hosts from connecting to forwarded ports. GatewayPorts can be used to specify that sshd should allow remote port forwardings to bind to non-loopback addresses, thus allowing other hosts to connect. The argument may be no to force remote port forwardings to be available to the local host only, yes to force remote port forwardings to bind to the wildcard address, or clientspecified to allow the client to select the address to which the forwarding is bound. The default is no.`, Value: booleanEnumValue, }, - "GSSAPIAuthentication": docvalues.DocumentationValue{ + "GSSAPIAuthentication": { Documentation: `Specifies whether user authentication based on GSSAPI is allowed. The default is no.`, Value: booleanEnumValue, }, - "GSSAPICleanupCredentials": docvalues.DocumentationValue{ + "GSSAPICleanupCredentials": { Documentation: `Specifies whether to automatically destroy the user's credentials cache on logout. The default is yes.`, Value: booleanEnumValue, }, - "GSSAPIStrictAcceptorCheck": docvalues.DocumentationValue{ + "GSSAPIStrictAcceptorCheck": { Documentation: `Determines whether to be strict about the identity of the GSSAPI acceptor a client authenticates against. If set to yes then the client must authenticate against the host service on the current hostname. If set to no then the client may authenticate against any service key stored in the machine's default store. This facility is provided to assist with operation on multi homed machines. The default is yes.`, Value: booleanEnumValue, }, - "HostbasedAcceptedAlgorithms": docvalues.DocumentationValue{ + "HostbasedAcceptedAlgorithms": { Documentation: `Specifies the signature algorithms that will be accepted for hostbased authentication as a list of comma-separated patterns. Alternately if the specified list begins with a ‘+’ character, then the specified signature algorithms will be appended to the default set instead of replacing them. If the specified list begins with a ‘-’ character, then the specified signature algorithms (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a ‘^’ character, then the specified signature algorithms will be placed at the head of the default set. The default for this option is: ssh-ed25519-cert-v01@openssh.com, ecdsa-sha2-nistp256-cert-v01@openssh.com, ecdsa-sha2-nistp384-cert-v01@openssh.com, ecdsa-sha2-nistp521-cert-v01@openssh.com, sk-ssh-ed25519-cert-v01@openssh.com, sk-ecdsa-sha2-nistp256-cert-v01@openssh.com, rsa-sha2-512-cert-v01@openssh.com, rsa-sha2-256-cert-v01@openssh.com, ssh-ed25519, ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521, sk-ssh-ed25519@openssh.com, sk-ecdsa-sha2-nistp256@openssh.com, rsa-sha2-512,rsa-sha2-256 The list of available signature algorithms may also be obtained using "ssh -Q HostbasedAcceptedAlgorithms". This was formerly named HostbasedAcceptedKeyTypes.`, @@ -326,25 +326,25 @@ See PATTERNS in ssh_config(5) for more information on patterns. This keyword may }, }, }, - "HostbasedAuthentication": docvalues.DocumentationValue{ + "HostbasedAuthentication": { Documentation: `Specifies whether rhosts or /etc/hosts.equiv authentication together with successful public key client host authentication is allowed (host-based authentication). The default is no.`, Value: booleanEnumValue, }, - "HostbasedUsesNameFromPacketOnly": docvalues.DocumentationValue{ + "HostbasedUsesNameFromPacketOnly": { Documentation: `Specifies whether or not the server will attempt to perform a reverse name lookup when matching the name in the ~/.shosts, ~/.rhosts, and /etc/hosts.equiv files during HostbasedAuthentication. A setting of yes means that sshd(8) uses the name supplied by the client rather than attempting to resolve the name from the TCP connection itself. The default is no.`, Value: booleanEnumValue, }, - "HostCertificate": docvalues.DocumentationValue{ + "HostCertificate": { Documentation: `Specifies a file containing a public host certificate. The certificate's public key must match a private host key already specified by HostKey. The default behaviour of sshd(8) is not to load any certificates.`, Value: docvalues.PathValue{}, }, - "HostKey": docvalues.DocumentationValue{ + "HostKey": { Documentation: `Specifies a file containing a private host key used by SSH. The defaults are /etc/ssh/ssh_host_ecdsa_key, /etc/ssh/ssh_host_ed25519_key and /etc/ssh/ssh_host_rsa_key. Note that sshd(8) will refuse to use a file if it is group/world-accessible and that the HostKeyAlgorithms option restricts which of the keys are actually used by sshd(8). It is possible to have multiple host key files. It is also possible to specify public host key files instead. In this case operations on the private key will be delegated to an ssh-agent(1).`, Value: docvalues.PathValue{}, }, - "HostKeyAgent": docvalues.DocumentationValue{ + "HostKeyAgent": { Documentation: `Identifies the UNIX-domain socket used to communicate with an agent that has access to the private host keys. If the string "SSH_AUTH_SOCK" is specified, the location of the socket will be read from the SSH_AUTH_SOCK environment variable.`, Value: docvalues.OrValue{ Values: []docvalues.Value{ @@ -358,7 +358,7 @@ See PATTERNS in ssh_config(5) for more information on patterns. This keyword may }, }, }, - "HostKeyAlgorithms": docvalues.DocumentationValue{ + "HostKeyAlgorithms": { Documentation: `Specifies the host key signature algorithms that the server offers. The default for this option is: ssh-ed25519-cert-v01@openssh.com, ecdsa-sha2-nistp256-cert-v01@openssh.com, ecdsa-sha2-nistp384-cert-v01@openssh.com, ecdsa-sha2-nistp521-cert-v01@openssh.com, sk-ssh-ed25519-cert-v01@openssh.com, sk-ecdsa-sha2-nistp256-cert-v01@openssh.com, rsa-sha2-512-cert-v01@openssh.com, rsa-sha2-256-cert-v01@openssh.com, ssh-ed25519, ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521, sk-ssh-ed25519@openssh.com, sk-ecdsa-sha2-nistp256@openssh.com, rsa-sha2-512,rsa-sha2-256 The list of available signature algorithms may also be obtained using "ssh -Q HostKeyAlgorithms".`, @@ -370,7 +370,7 @@ See PATTERNS in ssh_config(5) for more information on patterns. This keyword may }, }, }, - "IgnoreRhosts": docvalues.DocumentationValue{ + "IgnoreRhosts": { Documentation: `Specifies whether to ignore per-user .rhosts and .shosts files during HostbasedAuthentication. The system-wide /etc/hosts.equiv and /etc/shosts.equiv are still used regardless of this setting. Accepted values are yes (the default) to ignore all per- user files, shosts-only to allow the use of .shosts but to ignore .rhosts or no to allow both .shosts and rhosts.`, Value: docvalues.EnumValue{ @@ -382,11 +382,11 @@ See PATTERNS in ssh_config(5) for more information on patterns. This keyword may }, }, }, - "IgnoreUserKnownHosts": docvalues.DocumentationValue{ + "IgnoreUserKnownHosts": { Documentation: `Specifies whether sshd(8) should ignore the user's ~/.ssh/known_hosts during HostbasedAuthentication and use only the system-wide known hosts file /etc/ssh/ssh_known_hosts. The default is “no”.`, Value: booleanEnumValue, }, - "Include": docvalues.DocumentationValue{ + "Include": { Documentation: `Include the specified configuration file(s). Multiple pathnames may be specified and each pathname may contain glob(7) wildcards that will be expanded and processed in lexical order. Files without absolute paths are assumed to be in /etc/ssh. An Include directive may appear inside a Match block to perform conditional inclusion.`, Value: docvalues.ArrayValue{ Separator: " ", @@ -398,7 +398,7 @@ See PATTERNS in ssh_config(5) for more information on patterns. This keyword may // TODO: Add extra check }, - "IPQoS": docvalues.DocumentationValue{ + "IPQoS": { Documentation: `Specifies the IPv4 type-of-service or DSCP class for the connection. Accepted values are af11, af12, af13, af21, af22, af23, af31, af32, af33, af41, af42, af43, cs0, cs1, cs2, cs3, cs4, cs5, cs6, cs7, ef, le, lowdelay, throughput, reliability, a numeric value, or none to use the operating system default. This option may take one or two arguments, separated by whitespace. If one argument is specified, it is used as the packet class unconditionally. If two values are specified, the first is automatically selected for interactive sessions and the second for non-interactive sessions. The default is af21 (Low-Latency Data) for interactive sessions and cs1 (Lower Effort) for non-interactive sessions.`, Value: docvalues.OrValue{ Values: []docvalues.Value{ @@ -445,27 +445,27 @@ See PATTERNS in ssh_config(5) for more information on patterns. This keyword may }, }, }, - "KbdInteractiveAuthentication": docvalues.DocumentationValue{ + "KbdInteractiveAuthentication": { Documentation: `Specifies whether to allow keyboard-interactive authentication. All authentication styles from login.conf(5) are supported. The default is yes. The argument to this keyword must be yes or no. ChallengeResponseAuthentication is a deprecated alias for this.`, Value: booleanEnumValue, }, - "KerberosAuthentication": docvalues.DocumentationValue{ + "KerberosAuthentication": { Documentation: `Specifies whether the password provided by the user for PasswordAuthentication will be validated through the Kerberos KDC. To use this option, the server needs a Kerberos servtab which allows the verification of the KDC's identity. The default is no.`, Value: booleanEnumValue, }, - "KerberosGetAFSToken": docvalues.DocumentationValue{ + "KerberosGetAFSToken": { Documentation: `If AFS is active and the user has a Kerberos 5 TGT, attempt to acquire an AFS token before accessing the user's home directory. The default is no.`, Value: booleanEnumValue, }, - "KerberosOrLocalPasswd": docvalues.DocumentationValue{ + "KerberosOrLocalPasswd": { Documentation: `If password authentication through Kerberos fails then the password will be validated via any additional local mechanism such as /etc/passwd. The default is yes.`, Value: booleanEnumValue, }, - "KerberosTicketCleanup": docvalues.DocumentationValue{ + "KerberosTicketCleanup": { Documentation: `Specifies whether to automatically destroy the user's ticket cache file on logout. The default is yes.`, Value: booleanEnumValue, }, - "KexAlgorithms": docvalues.DocumentationValue{ + "KexAlgorithms": { Documentation: `Specifies the available KEX (Key Exchange) algorithms. Multiple algorithms must be comma-separated. Alternately if the specified list begins with a ‘+’ character, then the specified algorithms will be appended to the default set instead of replacing them. If the specified list begins with a ‘-’ character, then the specified algorithms (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a ‘^’ character, then the specified algorithms will be placed at the head of the default set. The supported algorithms are: curve25519-sha256 curve25519-sha256@libssh.org diffie-hellman-group1-sha1 diffie-hellman-group14-sha1 diffie-hellman-group14-sha256 diffie-hellman-group16-sha512 diffie-hellman-group18-sha512 diffie-hellman-group-exchange-sha1 diffie-hellman-group-exchange-sha256 ecdh-sha2-nistp256 ecdh-sha2-nistp384 ecdh-sha2-nistp521 sntrup761x25519-sha512@openssh.com The default is: @@ -487,7 +487,7 @@ See PATTERNS in ssh_config(5) for more information on patterns. This keyword may docvalues.CreateEnumString("sntrup761x25519-sha512@openssh.com"), }), }, - "ListenAddress": docvalues.DocumentationValue{ + "ListenAddress": { Documentation: `Specifies the local addresses sshd(8) should listen on. The following forms may be used: ListenAddress hostname|address [rdomain domain] ListenAddress hostname:port [rdomain domain] ListenAddress IPv4_address:port [rdomain domain] ListenAddress [hostname|address]:port [rdomain domain] The optional rdomain qualifier requests sshd(8) listen in an explicit routing domain. If port is not specified, sshd will listen on the address and all Port options specified. The default is to listen on all local addresses on the current default routing domain. Multiple ListenAddress options are permitted. For more information on routing domains, see rdomain(4).`, @@ -503,11 +503,11 @@ See PATTERNS in ssh_config(5) for more information on patterns. This keyword may Value: docvalues.NumberValue{Min: &ZERO, Max: &MAX_PORT}, }, }, - "LoginGraceTime": docvalues.DocumentationValue{ + "LoginGraceTime": { Documentation: `The server disconnects after this time if the user has not successfully logged in. If the value is 0, there is no time limit. The default is 120 seconds.`, Value: TimeFormatValue{}, }, - "LogLevel": docvalues.DocumentationValue{ + "LogLevel": { Documentation: `Gives the verbosity level that is used when logging messages from sshd(8). The possible values are: QUIET, FATAL, ERROR, INFO, VERBOSE, DEBUG, DEBUG1, DEBUG2, and DEBUG3. The default is INFO. DEBUG and DEBUG1 are equivalent. DEBUG2 and DEBUG3 each specify higher levels of debugging output. Logging with a DEBUG level violates the privacy of users and is not recommended.`, Value: docvalues.EnumValue{ EnforceValues: true, @@ -524,14 +524,14 @@ See PATTERNS in ssh_config(5) for more information on patterns. This keyword may }, }, }, - "LogVerbose": docvalues.DocumentationValue{ + "LogVerbose": { Documentation: `Specify one or more overrides to LogLevel. An override consists of a pattern lists that matches the source file, function and line number to force detailed logging for. For example, an override pattern of: kex.c:*:1000,*:kex_exchange_identification():*,packet.c:* would enable detailed logging for line 1000 of kex.c, everything in the kex_exchange_identification() function, and all code in the packet.c file. This option is intended for debugging and no overrides are enabled by default.`, Value: docvalues.StringValue{}, }, - "MACs": docvalues.DocumentationValue{ + "MACs": { Documentation: `Specifies the available MAC (message authentication code) algorithms. The MAC algorithm is used for data integrity protection. Multiple algorithms must be comma-separated. If the specified list begins with a ‘+’ character, then the specified algorithms will be appended to the default set instead of replacing them. If the specified list begins with a ‘-’ character, then the specified algorithms (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a ‘^’ character, then the specified algorithms will be placed at the head of the default set. The algorithms that contain "-etm" calculate the MAC after encryption (encrypt-then-mac). These are considered safer and their use recommended. The supported MACs are: hmac-md5 hmac-md5-96 hmac-sha1 hmac-sha1-96 hmac-sha2-256 hmac-sha2-512 umac-64@openssh.com umac-128@openssh.com hmac-md5-etm@openssh.com hmac-md5-96-etm@openssh.com hmac-sha1-etm@openssh.com hmac-sha1-96-etm@openssh.com hmac-sha2-256-etm@openssh.com hmac-sha2-512-etm@openssh.com umac-64-etm@openssh.com umac-128-etm@openssh.com @@ -559,7 +559,7 @@ See PATTERNS in ssh_config(5) for more information on patterns. This keyword may }), }, - "Match": docvalues.DocumentationValue{ + "Match": { Documentation: `Introduces a conditional block. If all of the criteria on the Match line are satisfied, the keywords on the following lines override those set in the global section of the config file, until either another Match line or the end of the file. If a keyword appears in multiple Match blocks that are satisfied, only the first instance of the keyword is applied. The arguments to Match are one or more criteria-pattern pairs or the single token All which matches all criteria. The available criteria are User, Group, Host, LocalAddress, LocalPort, RDomain, and Address (with RDomain representing the rdomain(4) on which the connection was received). The match patterns may consist of single entries or comma-separated lists and may use the wildcard and negation operators described in the “PATTERNS” section of ssh_config(5). @@ -587,15 +587,15 @@ Only a subset of keywords may be used on the lines following a Match keyword. Av }, }, }, - "MaxAuthTries": docvalues.DocumentationValue{ + "MaxAuthTries": { Documentation: `Specifies the maximum number of authentication attempts permitted per connection. Once the number of failures reaches half this value, additional failures are logged. The default is 6.`, Value: docvalues.NumberValue{Min: &ZERO}, }, - "MaxSessions": docvalues.DocumentationValue{ + "MaxSessions": { Documentation: `Specifies the maximum number of open shell, login or subsystem (e.g. sftp) sessions permitted per network connection. Multiple sessions may be established by clients that support connection multiplexing. Setting MaxSessions to 1 will effectively disable session multiplexing, whereas setting it to 0 will prevent all shell, login and subsystem sessions while still permitting forwarding. The default is 10.`, Value: docvalues.NumberValue{Min: &ZERO}, }, - "MaxStartups": docvalues.DocumentationValue{ + "MaxStartups": { Documentation: `Specifies the maximum number of concurrent unauthenticated connections to the SSH daemon. Additional connections will be dropped until authentication succeeds or the LoginGraceTime expires for a connection. The default is 10:30:100. Alternatively, random early drop can be enabled by specifying the three colon separated values start:rate:full (e.g. "10:30:60"). sshd(8) will refuse connection attempts with a probability of rate/100 (30%) if there are currently start (10) unauthenticated connections. The probability increases linearly and all connection attempts are refused if the number of unauthenticated connections reaches full (60).`, // TODO: Add custom value `SeapartorValue` that takes an array of values and separators @@ -603,21 +603,21 @@ Only a subset of keywords may be used on the lines following a Match keyword. Av Regex: *regexp.MustCompile(`^(\d+):(\d+):(\d+)$`), }, }, - "ModuliFile": docvalues.DocumentationValue{ + "ModuliFile": { Documentation: `Specifies the moduli(5) file that contains the Diffie- Hellman groups used for the “diffie-hellman-group-exchange-sha1” and “diffie-hellman-group-exchange-sha256” key exchange methods. The default is /etc/moduli.`, Value: docvalues.PathValue{ RequiredType: docvalues.PathTypeFile, }, }, - "PasswordAuthentication": docvalues.DocumentationValue{ + "PasswordAuthentication": { Documentation: `Specifies whether password authentication is allowed. The default is yes.`, Value: booleanEnumValue, }, - "PermitEmptyPasswords": docvalues.DocumentationValue{ + "PermitEmptyPasswords": { Documentation: `When password authentication is allowed, it specifies whether the server allows login to accounts with empty password strings. The default is no.`, Value: booleanEnumValue, }, - "PermitListen": docvalues.DocumentationValue{ + "PermitListen": { Documentation: `Specifies the addresses/ports on which a remote TCP port forwarding may listen. The listen specification must be one of the following forms: PermitListen port PermitListen host:port Multiple permissions may be specified by separating them with whitespace. An argument of any can be used to remove all restrictions and permit any listen requests. An argument of none can be used to prohibit all listen requests. The host name may contain wildcards as described in the PATTERNS section in ssh_config(5). The wildcard ‘*’ can also be used in place of a port number to allow all ports. By default all port forwarding listen requests are permitted. Note that the GatewayPorts option may further restrict which addresses may be listened on. Note also that ssh(1) will request a listen host of “localhost” if no listen host was specifically requested, and this name is treated differently to explicit localhost addresses of “127.0.0.1” and “::1”.`, @@ -651,7 +651,7 @@ Only a subset of keywords may be used on the lines following a Match keyword. Av }, }, }, - "PermitOpen": docvalues.DocumentationValue{ + "PermitOpen": { Documentation: `Specifies the destinations to which TCP port forwarding is permitted. The forwarding specification must be one of the following forms: PermitOpen host:port PermitOpen IPv4_addr:port PermitOpen [IPv6_addr]:port Multiple forwards may be specified by separating them with whitespace. An argument of any can be used to remove all restrictions and permit any forwarding requests. An argument of none can be used to prohibit all forwarding requests. The wildcard ‘*’ can be used for host or port to allow all hosts or ports respectively. Otherwise, no pattern matching or address lookups are performed on supplied names. By default all port forwarding requests are permitted.`, @@ -698,7 +698,7 @@ Only a subset of keywords may be used on the lines following a Match keyword. Av }, }, }, - "PermitRootLogin": docvalues.DocumentationValue{ + "PermitRootLogin": { Documentation: `Specifies whether root can log in using ssh(1). The argument must be yes, prohibit-password, forced-commands-only, or no. The default is prohibit-password. If this option is set to prohibit-password (or its deprecated alias, without-password), password and keyboard-interactive authentication are disabled for root. If this option is set to forced-commands-only, root login with public key authentication will be allowed, but only if the command option has been specified (which may be useful for taking remote backups even if root login is normally not allowed). All other authentication methods are disabled for root. @@ -713,11 +713,11 @@ Only a subset of keywords may be used on the lines following a Match keyword. Av }, }, }, - "PermitTTY": docvalues.DocumentationValue{ + "PermitTTY": { Documentation: `Specifies whether pty(4) allocation is permitted. The default is yes.`, Value: booleanEnumValue, }, - "PermitTunnel": docvalues.DocumentationValue{ + "PermitTunnel": { Documentation: `Specifies whether tun(4) device forwarding is allowed. The argument must be yes, point-to-point (layer 3), ethernet (layer 2), or no. Specifying yes permits both point-to-point and ethernet. The default is no. Independent of this setting, the permissions of the selected tun(4) device must allow access to the user.`, Value: docvalues.EnumValue{ @@ -730,7 +730,7 @@ Only a subset of keywords may be used on the lines following a Match keyword. Av }, }, }, - "PermitUserEnvironment": docvalues.DocumentationValue{ + "PermitUserEnvironment": { Documentation: `Specifies whether ~/.ssh/environment and environment= options in ~/.ssh/authorized_keys are processed by sshd(8). Valid options are yes, no or a pattern-list specifying which environment variable names to accept (for example "LANG,LC_*"). The default is no. Enabling environment processing may enable users to bypass access restrictions in some configurations using mechanisms such as LD_PRELOAD.`, Value: docvalues.OrValue{ Values: []docvalues.Value{ @@ -748,11 +748,11 @@ Only a subset of keywords may be used on the lines following a Match keyword. Av }, }, }, - "PermitUserRC": docvalues.DocumentationValue{ + "PermitUserRC": { Documentation: `Specifies whether any ~/.ssh/rc file is executed. The default is yes.`, Value: booleanEnumValue, }, - "PerSourceMaxStartups": docvalues.DocumentationValue{ + "PerSourceMaxStartups": { Documentation: `Specifies the number of unauthenticated connections allowed from a given source address, or “none” if there is no limit. This limit is applied in addition to MaxStartups, whichever is lower. The default is none.`, Value: docvalues.OrValue{ Values: []docvalues.Value{ @@ -770,7 +770,7 @@ Only a subset of keywords may be used on the lines following a Match keyword. Av }, }, }, - "PerSourceNetBlockSize": docvalues.DocumentationValue{ + "PerSourceNetBlockSize": { Documentation: `Specifies the number of bits of source address that are grouped together for the purposes of applying PerSourceMaxStartups limits. Values for IPv4 and optionally IPv6 may be specified, separated by a colon. The default is 32:128, which means each address is considered individually.`, Value: docvalues.KeyValueAssignmentValue{ Separator: ":", @@ -779,24 +779,24 @@ Only a subset of keywords may be used on the lines following a Match keyword. Av Value: docvalues.NumberValue{Min: &ZERO}, }, }, - "PidFile": docvalues.DocumentationValue{ + "PidFile": { Documentation: `Specifies the file that contains the process ID of the SSH daemon, or none to not write one. The default is /var/run/sshd.pid.`, Value: docvalues.StringValue{}, }, - "Port": docvalues.DocumentationValue{ + "Port": { Documentation: `Specifies the port number that sshd(8) listens on. The default is 22. Multiple options of this type are permitted. See also ListenAddress.`, Value: docvalues.NumberValue{Min: &ZERO, Max: &MAX_PORT}, }, - "PrintLastLog": docvalues.DocumentationValue{ + "PrintLastLog": { Documentation: `Specifies whether sshd(8) should print the date and time of the last user login when a user logs in interactively. The default is yes.`, Value: booleanEnumValue, }, - "PrintMotd": docvalues.DocumentationValue{ + "PrintMotd": { Documentation: `Specifies whether sshd(8) should print /etc/motd when a user logs in interactively. (On some systems it is also printed by the shell, /etc/profile, or equivalent.) The default is yes.`, Value: booleanEnumValue, }, - "PubkeyAcceptedAlgorithms": docvalues.DocumentationValue{ + "PubkeyAcceptedAlgorithms": { Documentation: `Specifies the signature algorithms that will be accepted for public key authentication as a list of comma- separated patterns. Alternately if the specified list begins with a ‘+’ character, then the specified algorithms will be appended to the default set instead of replacing them. If the specified list begins with a ‘-’ character, then the specified algorithms (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a ‘^’ character, then the specified algorithms will be placed at the head of the default set. The default for this option is: ssh-ed25519-cert-v01@openssh.com, ecdsa-sha2-nistp256-cert-v01@openssh.com, ecdsa-sha2-nistp384-cert-v01@openssh.com, ecdsa-sha2-nistp521-cert-v01@openssh.com, sk-ssh-ed25519-cert-v01@openssh.com, sk-ecdsa-sha2-nistp256-cert-v01@openssh.com, rsa-sha2-512-cert-v01@openssh.com, rsa-sha2-256-cert-v01@openssh.com, ssh-ed25519, ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521, sk-ssh-ed25519@openssh.com, sk-ecdsa-sha2-nistp256@openssh.com, rsa-sha2-512,rsa-sha2-256 The list of available signature algorithms may also be obtained using "ssh -Q PubkeyAcceptedAlgorithms".`, @@ -808,7 +808,7 @@ Only a subset of keywords may be used on the lines following a Match keyword. Av }, }, }, - "PubkeyAuthOptions": docvalues.DocumentationValue{ + "PubkeyAuthOptions": { Documentation: `Sets one or more public key authentication options. The supported keywords are: none (the default; indicating no additional options are enabled), touch-required and verify-required. The touch-required option causes public key authentication using a FIDO authenticator algorithm (i.e. ecdsa-sk or ed25519-sk) to always require the signature to attest that a physically present user explicitly confirmed the authentication (usually by touching the authenticator). By default, sshd(8) requires user presence unless overridden with an authorized_keys option. The touch-required flag disables this override. The verify-required option requires a FIDO key signature attest that the user was verified, e.g. via a PIN. @@ -825,11 +825,11 @@ Only a subset of keywords may be used on the lines following a Match keyword. Av }, }, }, - "PubkeyAuthentication": docvalues.DocumentationValue{ + "PubkeyAuthentication": { Documentation: `Specifies whether public key authentication is allowed. The default is yes.`, Value: booleanEnumValue, }, - "RekeyLimit": docvalues.DocumentationValue{ + "RekeyLimit": { Documentation: `Specifies the maximum amount of data that may be transmitted or received before the session key is renegotiated, optionally followed by a maximum amount of time that may pass before the session key is renegotiated. The first argument is specified in bytes and may have a suffix of ‘K’, ‘M’, or ‘G’ to indicate Kilobytes, Megabytes, or Gigabytes, respectively. The default is between ‘1G’ and ‘4G’, depending on the cipher. The optional second value is specified in seconds and may use any of the units documented in the “TIME FORMATS” section. The default value for RekeyLimit is default none, which means that rekeying is performed after the cipher's default amount of data has been sent or received and no time based rekeying is done.`, Value: docvalues.KeyValueAssignmentValue{ Separator: " ", @@ -838,15 +838,15 @@ Only a subset of keywords may be used on the lines following a Match keyword. Av Value: TimeFormatValue{}, }, }, - "RequiredRSASize": docvalues.DocumentationValue{ + "RequiredRSASize": { Documentation: `Specifies the minimum RSA key size (in bits) that sshd(8) will accept. User and host-based authentication keys smaller than this limit will be refused. The default is 1024 bits. Note that this limit may only be raised from the default.`, Value: docvalues.NumberValue{Min: &ZERO}, }, - "RevokedKeys": docvalues.DocumentationValue{ + "RevokedKeys": { Documentation: `Specifies revoked public keys file, or none to not use one. Keys listed in this file will be refused for public key authentication. Note that if this file is not readable, then public key authentication will be refused for all users. Keys may be specified as a text file, listing one public key per line, or as an OpenSSH Key Revocation List (KRL) as generated by ssh-keygen(1). For more information on KRLs, see the KEY REVOCATION LISTS section in ssh-keygen(1).`, Value: docvalues.StringValue{}, }, - "RDomain": docvalues.DocumentationValue{ + "RDomain": { Documentation: `Specifies an explicit routing domain that is applied after authentication has completed. The user session, as well as any forwarded or listening IP sockets, will be bound to this rdomain(4). If the routing domain is set to %D, then the domain in which the incoming connection was received will be applied.`, Value: docvalues.OrValue{ Values: []docvalues.Value{ @@ -863,14 +863,14 @@ Only a subset of keywords may be used on the lines following a Match keyword. Av }, }, }, - "SecurityKeyProvider": docvalues.DocumentationValue{ + "SecurityKeyProvider": { Documentation: `Specifies a path to a library that will be used when loading FIDO authenticator-hosted keys, overriding the default of using the built-in USB HID support.`, Value: docvalues.PathValue{ RequiredType: docvalues.PathTypeFile, }, }, - "SetEnv": docvalues.DocumentationValue{ + "SetEnv": { Documentation: `Specifies one or more environment variables to set in child sessions started by sshd(8) as “NAME=VALUE”. The environment value may be quoted (e.g. if it contains whitespace characters). Environment variables set by SetEnv override the default environment and any variables specified by the user via AcceptEnv or PermitUserEnvironment.`, Value: docvalues.ArrayValue{ Separator: " ", @@ -883,28 +883,28 @@ Only a subset of keywords may be used on the lines following a Match keyword. Av }, }, }, - "StreamLocalBindMask": docvalues.DocumentationValue{ + "StreamLocalBindMask": { Documentation: `Sets the octal file creation mode mask (umask) used when creating a Unix-domain socket file for local or remote port forwarding. This option is only used for port forwarding to a Unix-domain socket file. The default value is 0177, which creates a Unix-domain socket file that is readable and writable only by the owner. Note that not all operating systems honor the file mode on Unix-domain socket files.`, Value: docvalues.NumberValue{Min: &ZERO, Max: &MAX_FILE_MODE}, }, - "StreamLocalBindUnlink": docvalues.DocumentationValue{ + "StreamLocalBindUnlink": { Documentation: `Specifies whether to remove an existing Unix-domain socket file for local or remote port forwarding before creating a new one. If the socket file already exists and StreamLocalBindUnlink is not enabled, sshd will be unable to forward the port to the Unix-domain socket file. This option is only used for port forwarding to a Unix-domain socket file. The argument must be yes or no. The default is no.`, Value: booleanEnumValue, }, - "StrictModes": docvalues.DocumentationValue{ + "StrictModes": { Documentation: `Specifies whether sshd(8) should check file modes and ownership of the user's files and home directory before accepting login. This is normally desirable because novices sometimes accidentally leave their directory or files world-writable. The default is yes. Note that this does not apply to ChrootDirectory, whose permissions and ownership are checked unconditionally.`, Value: booleanEnumValue, }, - "Subsystem": docvalues.DocumentationValue{ + "Subsystem": { Documentation: `Configures an external subsystem (e.g. file transfer daemon). Arguments should be a subsystem name and a command (with optional arguments) to execute upon subsystem request. The command sftp-server implements the SFTP file transfer subsystem. Alternately the name internal-sftp implements an in- process SFTP server. This may simplify configurations using ChrootDirectory to force a different filesystem root on clients. It accepts the same command line arguments as sftp-server and even though it is in- process, settings such as LogLevel or SyslogFacility do not apply to it and must be set explicitly via command line arguments. By default no subsystems are defined.`, Value: docvalues.StringValue{}, }, - "SyslogFacility": docvalues.DocumentationValue{ + "SyslogFacility": { Documentation: `Gives the facility code that is used when logging messages from sshd(8). The possible values are: DAEMON, USER, AUTH, LOCAL0, LOCAL1, LOCAL2, LOCAL3, LOCAL4, LOCAL5, LOCAL6, LOCAL7. The default is AUTH.`, Value: docvalues.EnumValue{ EnforceValues: true, @@ -923,35 +923,35 @@ Only a subset of keywords may be used on the lines following a Match keyword. Av }, }, }, - "TCPKeepAlive": docvalues.DocumentationValue{ + "TCPKeepAlive": { Documentation: `Specifies whether the system should send TCP keepalive messages to the other side. If they are sent, death of the connection or crash of one of the machines will be properly noticed. However, this means that connections will die if the route is down temporarily, and some people find it annoying. On the other hand, if TCP keepalives are not sent, sessions may hang indefinitely on the server, leaving "ghost" users and consuming server resources. The default is yes (to send TCP keepalive messages), and the server will notice if the network goes down or the client host crashes. This avoids infinitely hanging sessions. To disable TCP keepalive messages, the value should be set to no.`, Value: booleanEnumValue, }, - "TrustedUserCAKeys": docvalues.DocumentationValue{ + "TrustedUserCAKeys": { Documentation: `Specifies a file containing public keys of certificate authorities that are trusted to sign user certificates for authentication, or none to not use one. Keys are listed one per line; empty lines and comments starting with ‘#’ are allowed. If a certificate is presented for authentication and has its signing CA key listed in this file, then it may be used for authentication for any user listed in the certificate's principals list. Note that certificates that lack a list of principals will not be permitted for authentication using TrustedUserCAKeys. For more details on certificates, see the CERTIFICATES section in ssh-keygen(1).`, Value: docvalues.StringValue{}, }, - "UnusedConnectionTimeout": docvalues.DocumentationValue{ + "UnusedConnectionTimeout": { Documentation: `Specifies whether and how quickly sshd(8) should close client connections with no open channels. Open channels include active shell, command execution or subsystem sessions, connected network, socket, agent or X11 forwardings. Forwarding listeners, such as those from the ssh(1) -R flag, are not considered as open channels and do not prevent the timeout. The timeout value is specified in seconds or may use any of the units documented in the “TIME FORMATS” section. Note that this timeout starts when the client connection completes user authentication but before the client has an opportunity to open any channels. Caution should be used when using short timeout values, as they may not provide sufficient time for the client to request and open its channels before terminating the connection. The default none is to never expire connections for having no open channels. This option may be useful in conjunction with ChannelTimeout.`, Value: TimeFormatValue{}, }, - "UseDNS": docvalues.DocumentationValue{ + "UseDNS": { Documentation: `Specifies whether sshd(8) should look up the remote host name, and to check that the resolved host name for the remote IP address maps back to the very same IP address. If this option is set to no (the default) then only addresses and not host names may be used in ~/.ssh/authorized_keys from and sshd_config Match Host directives.`, Value: booleanEnumValue, }, - "UsePAM": docvalues.DocumentationValue{ + "UsePAM": { Documentation: `Enables the Pluggable Authentication Module interface. If set to yes this will enable PAM authentication using KbdInteractiveAuthentication and PasswordAuthentication in addition to PAM account and session module processing for all authentication types. Because PAM keyboard-interactive authentication usually serves an equivalent role to password authentication, you should disable either PasswordAuthentication or KbdInteractiveAuthentication. If UsePAM is enabled, you will not be able to run sshd(8) as a non-root user. The default is no.`, Value: booleanEnumValue, }, - "VersionAddendum": docvalues.DocumentationValue{ + "VersionAddendum": { Documentation: `Optionally specifies additional text to append to the SSH protocol banner sent by the server upon connection. The default is none.`, Value: docvalues.OrValue{ Values: []docvalues.Value{ @@ -965,21 +965,21 @@ Only a subset of keywords may be used on the lines following a Match keyword. Av }, }, }, - "X11DisplayOffset": docvalues.DocumentationValue{ + "X11DisplayOffset": { Documentation: `Specifies the first display number available for sshd(8)'s X11 forwarding. This prevents sshd from interfering with real X11 servers. The default is 10.`, Value: docvalues.NumberValue{Min: &ZERO}, }, - "X11Forwarding": docvalues.DocumentationValue{ + "X11Forwarding": { Documentation: `Specifies whether X11 forwarding is permitted. The argument must be yes or no. The default is no. When X11 forwarding is enabled, there may be additional exposure to the server and to client displays if the sshd(8) proxy display is configured to listen on the wildcard address (see X11UseLocalhost), though this is not the default. Additionally, the authentication spoofing and authentication data verification and substitution occur on the client side. The security risk of using X11 forwarding is that the client's X11 display server may be exposed to attack when the SSH client requests forwarding (see the warnings for ForwardX11 in ssh_config(5)). A system administrator may have a stance in which they want to protect clients that may expose themselves to attack by unwittingly requesting X11 forwarding, which can warrant a no setting. Note that disabling X11 forwarding does not prevent users from forwarding X11 traffic, as users can always install their own forwarders.`, Value: booleanEnumValue, }, - "X11UseLocalhost": docvalues.DocumentationValue{ + "X11UseLocalhost": { Documentation: `Specifies whether sshd(8) should bind the X11 forwarding server to the loopback address or to the wildcard address. By default, sshd binds the forwarding server to the loopback address and sets the hostname part of the DISPLAY environment variable to localhost. This prevents remote hosts from connecting to the proxy display. However, some older X11 clients may not function with this configuration. X11UseLocalhost may be set to no to specify that the forwarding server should be bound to the wildcard address. The argument must be yes or no. The default is yes.`, Value: booleanEnumValue, }, - "XAuthLocation": docvalues.DocumentationValue{ + "XAuthLocation": { Documentation: `Specifies the full pathname of the xauth(1) program, or none to not use one. The default is /usr/X11R6/bin/xauth.`, Value: docvalues.StringValue{}, }, diff --git a/handlers/sshd_config/handlers/completions.go b/handlers/sshd_config/handlers/completions.go index cf8d1dd..0e4f48f 100644 --- a/handlers/sshd_config/handlers/completions.go +++ b/handlers/sshd_config/handlers/completions.go @@ -17,7 +17,7 @@ func GetRootCompletions( ) ([]protocol.CompletionItem, error) { kind := protocol.CompletionItemKindField - availableOptions := make(map[string]docvalues.Value) + availableOptions := make(map[string]docvalues.DocumentationValue) if parentMatchBlock == nil { availableOptions = fields.Options @@ -31,9 +31,7 @@ func GetRootCompletions( return utils.MapMapToSlice( availableOptions, - func(name string, rawValue docvalues.Value) protocol.CompletionItem { - doc := rawValue.(docvalues.DocumentationValue) - + func(name string, doc docvalues.DocumentationValue) protocol.CompletionItem { completion := &protocol.CompletionItem{ Label: name, Kind: &kind, diff --git a/handlers/sshd_config/handlers/hover.go b/handlers/sshd_config/handlers/hover.go new file mode 100644 index 0000000..b18efa5 --- /dev/null +++ b/handlers/sshd_config/handlers/hover.go @@ -0,0 +1,63 @@ +package handlers + +import ( + docvalues "config-lsp/doc-values" + "config-lsp/handlers/sshd_config/ast" + "config-lsp/handlers/sshd_config/fields" + "strings" + + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func GetHoverInfoForOption( + option *ast.SSHOption, + matchBlock *ast.SSHMatchBlock, + cursor uint32, +) (*protocol.Hover, error) { + var docValue *docvalues.DocumentationValue + + if matchBlock == nil { + val := fields.Options[option.Key.Value] + docValue = &val + } else { + if _, found := fields.MatchAllowedOptions[option.Key.Value]; found { + val := fields.Options[option.Key.Value] + docValue = &val + } + } + + if cursor >= option.Key.Start.Character && cursor <= option.Key.End.Character { + if docValue != nil { + contents := []string{ + "## " + option.Key.Value, + "", + } + contents = append(contents, docValue.Documentation) + contents = append(contents, []string{ + "", + "---", + "", + }...) + contents = append(contents, []string{ + "### Type", + "", + }...) + contents = append(contents, docValue.GetTypeDescription()...) + + return &protocol.Hover{ + Contents: strings.Join(contents, "\n"), + }, nil + } + } + + if option.OptionValue != nil && cursor >= option.OptionValue.Start.Character && cursor <= option.OptionValue.End.Character { + relativeCursor := cursor - option.OptionValue.Start.Character + contents := docValue.FetchHoverInfo(option.OptionValue.Value, relativeCursor) + + return &protocol.Hover{ + Contents: strings.Join(contents, "\n"), + }, nil + } + + return nil, nil +} diff --git a/handlers/sshd_config/lsp/text-document-hover.go b/handlers/sshd_config/lsp/text-document-hover.go index bb73a41..f6b5d96 100644 --- a/handlers/sshd_config/lsp/text-document-hover.go +++ b/handlers/sshd_config/lsp/text-document-hover.go @@ -1,6 +1,9 @@ package lsp import ( + sshdconfig "config-lsp/handlers/sshd_config" + "config-lsp/handlers/sshd_config/handlers" + "github.com/tliron/glsp" protocol "github.com/tliron/glsp/protocol_3_16" ) @@ -9,12 +12,17 @@ func TextDocumentHover( context *glsp.Context, params *protocol.HoverParams, ) (*protocol.Hover, error) { - // line := params.Position.Line - // cursor := params.Position.Character - // - // d := sshdconfig.DocumentParserMap[params.TextDocument.URI] - // - // entry, matchBlock := d.Config.FindOption(line) + line := params.Position.Line + cursor := params.Position.Character - return nil, nil + d := sshdconfig.DocumentParserMap[params.TextDocument.URI] + + option, matchBlock := d.Config.FindOption(line) + + if option == nil || option.Key == nil { + // Empty line + return nil, nil + } + + return handlers.GetHoverInfoForOption(option, matchBlock, cursor) } From 97034b783eb5c9c2ffaf66c1ec910e3c81506a8a Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Sat, 14 Sep 2024 13:24:41 +0200 Subject: [PATCH 027/133] fix(sshd_config): Rename index field --- handlers/sshd_config/indexes/indexes.go | 14 +++---- handlers/sshd_config/indexes/indexes_test.go | 42 ++++++++++---------- 2 files changed, 28 insertions(+), 28 deletions(-) diff --git a/handlers/sshd_config/indexes/indexes.go b/handlers/sshd_config/indexes/indexes.go index 5f46a41..3cf15f8 100644 --- a/handlers/sshd_config/indexes/indexes.go +++ b/handlers/sshd_config/indexes/indexes.go @@ -17,19 +17,19 @@ var allowedDoubleOptions = map[string]struct{}{ "Port": {}, } -type SSHIndexEntry struct { +type SSHIndexKey struct { Option string MatchBlock *ast.SSHMatchBlock } type SSHIndexes struct { - EntriesPerKey map[SSHIndexEntry][]*ast.SSHOption + OptionsPerRelativeKey map[SSHIndexKey][]*ast.SSHOption } func CreateIndexes(config ast.SSHConfig) (*SSHIndexes, []common.LSPError) { errs := make([]common.LSPError, 0) indexes := &SSHIndexes{ - EntriesPerKey: make(map[SSHIndexEntry][]*ast.SSHOption), + OptionsPerRelativeKey: make(map[SSHIndexKey][]*ast.SSHOption), } it := config.Options.Iterator() @@ -65,15 +65,15 @@ func addOption( ) []common.LSPError { var errs []common.LSPError - indexEntry := SSHIndexEntry{ + indexEntry := SSHIndexKey{ Option: option.Key.Value, MatchBlock: matchBlock, } - if existingEntry, found := i.EntriesPerKey[indexEntry]; found { + if existingEntry, found := i.OptionsPerRelativeKey[indexEntry]; found { if _, found := allowedDoubleOptions[option.Key.Value]; found { // Double value, but doubles are allowed - i.EntriesPerKey[indexEntry] = append(existingEntry, option) + i.OptionsPerRelativeKey[indexEntry] = append(existingEntry, option) } else { errs = append(errs, common.LSPError{ Range: option.Key.LocationRange, @@ -81,7 +81,7 @@ func addOption( }) } } else { - i.EntriesPerKey[indexEntry] = []*ast.SSHOption{option} + i.OptionsPerRelativeKey[indexEntry] = []*ast.SSHOption{option} } return errs diff --git a/handlers/sshd_config/indexes/indexes_test.go b/handlers/sshd_config/indexes/indexes_test.go index e9dec93..d54f573 100644 --- a/handlers/sshd_config/indexes/indexes_test.go +++ b/handlers/sshd_config/indexes/indexes_test.go @@ -27,20 +27,20 @@ PermitRootLogin no t.Fatalf("Expected 1 error, but got %v", len(errors)) } - indexEntry := SSHIndexEntry{ + indexEntry := SSHIndexKey{ Option: "PermitRootLogin", MatchBlock: nil, } - if !(indexes.EntriesPerKey[indexEntry][0].Value == "PermitRootLogin yes" && indexes.EntriesPerKey[indexEntry][0].Start.Line == 0) { - t.Errorf("Expected 'PermitRootLogin yes', but got %v", indexes.EntriesPerKey[indexEntry][0].Value) + if !(indexes.OptionsPerRelativeKey[indexEntry][0].Value == "PermitRootLogin yes" && indexes.OptionsPerRelativeKey[indexEntry][0].Start.Line == 0) { + t.Errorf("Expected 'PermitRootLogin yes', but got %v", indexes.OptionsPerRelativeKey[indexEntry][0].Value) } - indexEntry = SSHIndexEntry{ + indexEntry = SSHIndexKey{ Option: "RootLogin", MatchBlock: nil, } - if !(indexes.EntriesPerKey[indexEntry][0].Value == "RootLogin yes" && indexes.EntriesPerKey[indexEntry][0].Start.Line == 1) { - t.Errorf("Expected 'RootLogin yes', but got %v", indexes.EntriesPerKey[indexEntry][0].Value) + if !(indexes.OptionsPerRelativeKey[indexEntry][0].Value == "RootLogin yes" && indexes.OptionsPerRelativeKey[indexEntry][0].Start.Line == 1) { + t.Errorf("Expected 'RootLogin yes', but got %v", indexes.OptionsPerRelativeKey[indexEntry][0].Value) } } @@ -71,35 +71,35 @@ Match Address 192.168.0.1/24 t.Fatalf("Expected no errors, but got %v", len(errors)) } - indexEntry := SSHIndexEntry{ + indexEntry := SSHIndexKey{ Option: "PermitRootLogin", MatchBlock: nil, } - if !(indexes.EntriesPerKey[indexEntry][0].Value == "PermitRootLogin yes" && indexes.EntriesPerKey[indexEntry][0].Start.Line == 0) { - t.Errorf("Expected 'PermitRootLogin yes' on line 0, but got %v on line %v", indexes.EntriesPerKey[indexEntry][0].Value, indexes.EntriesPerKey[indexEntry][0].Start.Line) + if !(indexes.OptionsPerRelativeKey[indexEntry][0].Value == "PermitRootLogin yes" && indexes.OptionsPerRelativeKey[indexEntry][0].Start.Line == 0) { + t.Errorf("Expected 'PermitRootLogin yes' on line 0, but got %v on line %v", indexes.OptionsPerRelativeKey[indexEntry][0].Value, indexes.OptionsPerRelativeKey[indexEntry][0].Start.Line) } firstMatchBlock := config.FindMatchBlock(uint32(6)) - indexEntry = SSHIndexEntry{ + indexEntry = SSHIndexKey{ Option: "PermitRootLogin", MatchBlock: firstMatchBlock, } - if !(indexes.EntriesPerKey[indexEntry][0].Value == "\tPermitRootLogin no" && indexes.EntriesPerKey[indexEntry][0].Start.Line == 6) { - t.Errorf("Expected 'PermitRootLogin no' on line 6, but got %v on line %v", indexes.EntriesPerKey[indexEntry][0].Value, indexes.EntriesPerKey[indexEntry][0].Start.Line) + if !(indexes.OptionsPerRelativeKey[indexEntry][0].Value == "\tPermitRootLogin no" && indexes.OptionsPerRelativeKey[indexEntry][0].Start.Line == 6) { + t.Errorf("Expected 'PermitRootLogin no' on line 6, but got %v on line %v", indexes.OptionsPerRelativeKey[indexEntry][0].Value, indexes.OptionsPerRelativeKey[indexEntry][0].Start.Line) } // Double check - indexEntry = SSHIndexEntry{ + indexEntry = SSHIndexKey{ Option: "Port", MatchBlock: nil, } - if !(indexes.EntriesPerKey[indexEntry][0].Value == "Port 22" && - indexes.EntriesPerKey[indexEntry][0].Start.Line == 1 && - len(indexes.EntriesPerKey[indexEntry]) == 3 && - indexes.EntriesPerKey[indexEntry][1].Value == "Port 2022" && - indexes.EntriesPerKey[indexEntry][1].Start.Line == 2 && - indexes.EntriesPerKey[indexEntry][2].Value == "Port 2024" && - indexes.EntriesPerKey[indexEntry][2].Start.Line == 3) { - t.Errorf("Expected 'Port 22' on line 1, but got %v on line %v", indexes.EntriesPerKey[indexEntry][0].Value, indexes.EntriesPerKey[indexEntry][0].Start.Line) + if !(indexes.OptionsPerRelativeKey[indexEntry][0].Value == "Port 22" && + indexes.OptionsPerRelativeKey[indexEntry][0].Start.Line == 1 && + len(indexes.OptionsPerRelativeKey[indexEntry]) == 3 && + indexes.OptionsPerRelativeKey[indexEntry][1].Value == "Port 2022" && + indexes.OptionsPerRelativeKey[indexEntry][1].Start.Line == 2 && + indexes.OptionsPerRelativeKey[indexEntry][2].Value == "Port 2024" && + indexes.OptionsPerRelativeKey[indexEntry][2].Start.Line == 3) { + t.Errorf("Expected 'Port 22' on line 1, but got %v on line %v", indexes.OptionsPerRelativeKey[indexEntry][0].Value, indexes.OptionsPerRelativeKey[indexEntry][0].Start.Line) } } From 774ee52a3b84646cfe84c713ddb335754b38df82 Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Sat, 14 Sep 2024 13:58:30 +0200 Subject: [PATCH 028/133] feat(sshd_config): Add indexes for all option names --- handlers/sshd_config/ast/parser_test.go | 9 ++++--- handlers/sshd_config/indexes/indexes.go | 28 ++++++++++++++++++++ handlers/sshd_config/indexes/indexes_test.go | 13 +++++++++ 3 files changed, 46 insertions(+), 4 deletions(-) diff --git a/handlers/sshd_config/ast/parser_test.go b/handlers/sshd_config/ast/parser_test.go index c2135d2..5077ac6 100644 --- a/handlers/sshd_config/ast/parser_test.go +++ b/handlers/sshd_config/ast/parser_test.go @@ -136,13 +136,13 @@ Match 192.168.0.2 rawThirdEntry, _ := secondEntry.Options.Get(uint32(3)) thirdEntry := rawThirdEntry.(*SSHOption) - if !(thirdEntry.Key.Value == "PasswordAuthentication" && thirdEntry.OptionValue.Value == "yes") { + if !(thirdEntry.Key.Value == "PasswordAuthentication" && thirdEntry.OptionValue.Value == "yes" && thirdEntry.LocationRange.Start.Line == 3) { t.Errorf("Expected third entry to be 'PasswordAuthentication yes', but got: %v", thirdEntry.Value) } rawFourthEntry, _ := secondEntry.Options.Get(uint32(4)) fourthEntry := rawFourthEntry.(*SSHOption) - if !(fourthEntry.Key.Value == "AllowUsers" && fourthEntry.OptionValue.Value == "root user") { + if !(fourthEntry.Key.Value == "AllowUsers" && fourthEntry.OptionValue.Value == "root user" && fourthEntry.LocationRange.Start.Line == 4) { t.Errorf("Expected fourth entry to be 'AllowUsers root user', but got: %v", fourthEntry.Value) } @@ -154,7 +154,7 @@ Match 192.168.0.2 rawSixthEntry, _ := fifthEntry.Options.Get(uint32(7)) sixthEntry := rawSixthEntry.(*SSHOption) - if !(sixthEntry.Key.Value == "MaxAuthTries" && sixthEntry.OptionValue.Value == "3") { + if !(sixthEntry.Key.Value == "MaxAuthTries" && sixthEntry.OptionValue.Value == "3" && sixthEntry.LocationRange.Start.Line == 7) { t.Errorf("Expected sixth entry to be 'MaxAuthTries 3', but got: %v", sixthEntry.Value) } @@ -199,7 +199,8 @@ Sample rawFirstEntry, _ := p.Options.Get(uint32(1)) firstEntry := rawFirstEntry.(*SSHOption) - if !(firstEntry.Value == "PermitRootLogin no") { + firstEntryOpt, _ := p.FindOption(uint32(1)) + if !(firstEntry.Value == "PermitRootLogin no" && firstEntry.LocationRange.Start.Line == 1 && firstEntryOpt == firstEntry) { t.Errorf("Expected first entry to be 'PermitRootLogin no', but got: %v", firstEntry.Value) } diff --git a/handlers/sshd_config/indexes/indexes.go b/handlers/sshd_config/indexes/indexes.go index 3cf15f8..9cab396 100644 --- a/handlers/sshd_config/indexes/indexes.go +++ b/handlers/sshd_config/indexes/indexes.go @@ -22,14 +22,27 @@ type SSHIndexKey struct { MatchBlock *ast.SSHMatchBlock } +type SSHIndexAllOption struct { + MatchBlock *ast.SSHMatchBlock + Option *ast.SSHOption +} + type SSHIndexes struct { + // Contains a map of `Option name + MatchBlock` to a list of options with that name + // This means an option may be specified inside a match block, and to get this + // option you need to know the match block it was specified in + // If you want to get all options for a specific name, you can use the `AllOptionsPerName` field OptionsPerRelativeKey map[SSHIndexKey][]*ast.SSHOption + + // This is a map of `Option name` to a list of options with that name + AllOptionsPerName map[string][]*SSHIndexAllOption } func CreateIndexes(config ast.SSHConfig) (*SSHIndexes, []common.LSPError) { errs := make([]common.LSPError, 0) indexes := &SSHIndexes{ OptionsPerRelativeKey: make(map[SSHIndexKey][]*ast.SSHOption), + AllOptionsPerName: make(map[string][]*SSHIndexAllOption), } it := config.Options.Iterator() @@ -84,5 +97,20 @@ func addOption( i.OptionsPerRelativeKey[indexEntry] = []*ast.SSHOption{option} } + + if existingEntry, found := i.AllOptionsPerName[option.Key.Value]; found { + i.AllOptionsPerName[option.Key.Value] = append(existingEntry, &SSHIndexAllOption{ + MatchBlock: matchBlock, + Option: option, + }) + } else { + i.AllOptionsPerName[option.Key.Value] = []*SSHIndexAllOption{ + { + MatchBlock: matchBlock, + Option: option, + }, + } + } + return errs } diff --git a/handlers/sshd_config/indexes/indexes_test.go b/handlers/sshd_config/indexes/indexes_test.go index d54f573..c6901d3 100644 --- a/handlers/sshd_config/indexes/indexes_test.go +++ b/handlers/sshd_config/indexes/indexes_test.go @@ -102,4 +102,17 @@ Match Address 192.168.0.1/24 indexes.OptionsPerRelativeKey[indexEntry][2].Start.Line == 3) { t.Errorf("Expected 'Port 22' on line 1, but got %v on line %v", indexes.OptionsPerRelativeKey[indexEntry][0].Value, indexes.OptionsPerRelativeKey[indexEntry][0].Start.Line) } + + if !(len(indexes.AllOptionsPerName["PermitRootLogin"]) == 3 && + indexes.AllOptionsPerName["PermitRootLogin"][0].Option.Value == "PermitRootLogin yes" && + indexes.AllOptionsPerName["PermitRootLogin"][0].Option.Start.Line == 0 && + indexes.AllOptionsPerName["PermitRootLogin"][0].MatchBlock == nil && + indexes.AllOptionsPerName["PermitRootLogin"][1].Option.Value == "\tPermitRootLogin no" && + indexes.AllOptionsPerName["PermitRootLogin"][1].Option.Start.Line == 6 && + indexes.AllOptionsPerName["PermitRootLogin"][1].MatchBlock == firstMatchBlock && + indexes.AllOptionsPerName["PermitRootLogin"][2].Option.Value == "\tPermitRootLogin yes" && + indexes.AllOptionsPerName["PermitRootLogin"][2].Option.Start.Line == 8 && + indexes.AllOptionsPerName["PermitRootLogin"][2].MatchBlock == firstMatchBlock) { + t.Errorf("Expected 3 PermitRootLogin options, but got %v", indexes.AllOptionsPerName["PermitRootLogin"]) + } } From 6c9ebc1b16482c4fae2ce302b066291deb5357bd Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Sat, 14 Sep 2024 18:31:31 +0200 Subject: [PATCH 029/133] feat(sshd_config): Add include support --- handlers/sshd_config/analyzer/analyzer.go | 49 ++++++++-- handlers/sshd_config/analyzer/include.go | 95 +++++++++++++++++++ handlers/sshd_config/analyzer/options.go | 37 ++++---- handlers/sshd_config/fields/fields.go | 4 +- handlers/sshd_config/handlers/definition.go | 47 +++++++++ handlers/sshd_config/indexes/indexes.go | 85 ++++++++++++++--- handlers/sshd_config/indexes/indexes_test.go | 45 +++++++++ .../lsp/text-document-definition.go | 23 +++++ handlers/sshd_config/shared.go | 4 +- root-handler/text-document-definition.go | 3 +- 10 files changed, 350 insertions(+), 42 deletions(-) create mode 100644 handlers/sshd_config/analyzer/include.go create mode 100644 handlers/sshd_config/handlers/definition.go create mode 100644 handlers/sshd_config/lsp/text-document-definition.go diff --git a/handlers/sshd_config/analyzer/analyzer.go b/handlers/sshd_config/analyzer/analyzer.go index 3bee59b..0b661c6 100644 --- a/handlers/sshd_config/analyzer/analyzer.go +++ b/handlers/sshd_config/analyzer/analyzer.go @@ -13,19 +13,54 @@ func Analyze( d *sshdconfig.SSHDocument, ) []protocol.Diagnostic { errors := analyzeOptionsAreValid(d) + + if len(errors) > 0 { + return errsToDiagnostics(errors) + } + indexes, indexErrors := indexes.CreateIndexes(*d.Config) - _ = indexes + + d.Indexes = indexes errors = append(errors, indexErrors...) if len(errors) > 0 { - return utils.Map( - errors, - func(err common.LSPError) protocol.Diagnostic { - return err.ToDiagnostic() - }, - ) + return errsToDiagnostics(errors) + } + + includeErrors := analyzeIncludeValues(d) + + if len(includeErrors) > 0 { + errors = append(errors, includeErrors...) + } else { + for _, include := range d.Indexes.Includes { + for _, value := range include.Values { + for _, path := range value.Paths { + _, err := parseFile(string(path)) + + if err != nil { + errors = append(errors, common.LSPError{ + Range: value.LocationRange, + Err: err, + }) + } + } + } + } + } + + if len(errors) > 0 { + return errsToDiagnostics(errors) } return nil } + +func errsToDiagnostics(errs []common.LSPError) []protocol.Diagnostic { + return utils.Map( + errs, + func(err common.LSPError) protocol.Diagnostic { + return err.ToDiagnostic() + }, + ) +} diff --git a/handlers/sshd_config/analyzer/include.go b/handlers/sshd_config/analyzer/include.go new file mode 100644 index 0000000..f785df3 --- /dev/null +++ b/handlers/sshd_config/analyzer/include.go @@ -0,0 +1,95 @@ +package analyzer + +import ( + "config-lsp/common" + sshdconfig "config-lsp/handlers/sshd_config" + "config-lsp/handlers/sshd_config/ast" + "config-lsp/handlers/sshd_config/indexes" + "config-lsp/utils" + "errors" + "fmt" + "os" + "path" + "path/filepath" + "regexp" +) + +var whitespacePattern = regexp.MustCompile(`\S+`) + +func analyzeIncludeValues( + d *sshdconfig.SSHDocument, +) []common.LSPError { + errs := make([]common.LSPError, 0) + + for _, include := range d.Indexes.Includes { + for _, value := range include.Values { + validPaths, err := createIncludePaths(value.Value) + + if err != nil { + errs = append(errs, common.LSPError{ + Range: value.LocationRange, + Err: err, + }) + } else { + value.Paths = validPaths + } + } + } + + return errs +} + +func createIncludePaths( + suggestedPath string, +) ([]indexes.ValidPath, error) { + var absolutePath string + + if path.IsAbs(suggestedPath) { + absolutePath = suggestedPath + } else { + absolutePath = path.Join("/etc", "ssh", suggestedPath) + } + + files, err := filepath.Glob(absolutePath) + + if err != nil { + return nil, errors.New(fmt.Sprintf("Could not find file %s (error: %s)", absolutePath, err)) + } + + if len(files) == 0 { + return nil, errors.New(fmt.Sprintf("Could not find file %s", absolutePath)) + } + + return utils.Map( + files, + func(file string) indexes.ValidPath { + return indexes.ValidPath(file) + }, + ), nil +} + +func parseFile( + filePath string, +) (*sshdconfig.SSHDocument, error) { + c := ast.NewSSHConfig() + + content, err := os.ReadFile(filePath) + + if err != nil { + return nil, err + } + + c.Parse(string(content)) + + d := &sshdconfig.SSHDocument{ + Config: c, + } + + errs := Analyze(d) + + if len(errs) > 0 { + return nil, errors.New(fmt.Sprintf("Errors in %s", filePath)) + } + + return d, nil +} diff --git a/handlers/sshd_config/analyzer/options.go b/handlers/sshd_config/analyzer/options.go index 13140f0..67aaf87 100644 --- a/handlers/sshd_config/analyzer/options.go +++ b/handlers/sshd_config/analyzer/options.go @@ -60,24 +60,27 @@ func checkOption( return errs } - if option.OptionValue == nil { - return errs + if option.OptionValue == nil || option.OptionValue.Value == "" { + errs = append(errs, common.LSPError{ + Range: option.Key.LocationRange, + Err: errors.New(fmt.Sprintf("Option '%s' requires a value", option.Key.Value)), + }) + } else { + invalidValues := docOption.CheckIsValid(option.OptionValue.Value) + + errs = append( + errs, + utils.Map( + invalidValues, + func(invalidValue *docvalues.InvalidValue) common.LSPError { + err := docvalues.LSPErrorFromInvalidValue(option.Start.Line, *invalidValue) + err.ShiftCharacter(option.OptionValue.Start.Character) + + return err + }, + )..., + ) } - - invalidValues := docOption.CheckIsValid(option.OptionValue.Value) - - errs = append( - errs, - utils.Map( - invalidValues, - func(invalidValue *docvalues.InvalidValue) common.LSPError { - err := docvalues.LSPErrorFromInvalidValue(option.Start.Line, *invalidValue) - err.ShiftCharacter(option.OptionValue.Start.Character) - - return err - }, - )..., - ) } return errs diff --git a/handlers/sshd_config/fields/fields.go b/handlers/sshd_config/fields/fields.go index 586da43..d7abb52 100644 --- a/handlers/sshd_config/fields/fields.go +++ b/handlers/sshd_config/fields/fields.go @@ -391,9 +391,7 @@ See PATTERNS in ssh_config(5) for more information on patterns. This keyword may Value: docvalues.ArrayValue{ Separator: " ", DuplicatesExtractor: &docvalues.SimpleDuplicatesExtractor, - SubValue: docvalues.PathValue{ - RequiredType: docvalues.PathTypeFile, - }, + SubValue: docvalues.StringValue{}, }, // TODO: Add extra check }, diff --git a/handlers/sshd_config/handlers/definition.go b/handlers/sshd_config/handlers/definition.go new file mode 100644 index 0000000..19449c3 --- /dev/null +++ b/handlers/sshd_config/handlers/definition.go @@ -0,0 +1,47 @@ +package handlers + +import ( + "config-lsp/handlers/sshd_config/indexes" + "config-lsp/utils" + "fmt" + "slices" + + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func GetIncludeOptionLocation( + include *indexes.SSHIndexIncludeLine, + cursor uint32, +) []protocol.Location { + index, found := slices.BinarySearchFunc( + include.Values, + cursor, + func(i *indexes.SSHIndexIncludeValue, cursor uint32) int { + if cursor < i.Start.Character { + return -1 + } + + if cursor > i.End.Character { + return 1 + } + + return 0 + }, + ) + + if !found { + return nil + } + + path := include.Values[index] + println("paths", fmt.Sprintf("%v", path.Paths)) + + return utils.Map( + path.Paths, + func(path indexes.ValidPath) protocol.Location { + return protocol.Location{ + URI: path.AsURI(), + } + }, + ) +} diff --git a/handlers/sshd_config/indexes/indexes.go b/handlers/sshd_config/indexes/indexes.go index 9cab396..ed56afd 100644 --- a/handlers/sshd_config/indexes/indexes.go +++ b/handlers/sshd_config/indexes/indexes.go @@ -5,6 +5,7 @@ import ( "config-lsp/handlers/sshd_config/ast" "errors" "fmt" + "regexp" ) var allowedDoubleOptions = map[string]struct{}{ @@ -24,7 +25,26 @@ type SSHIndexKey struct { type SSHIndexAllOption struct { MatchBlock *ast.SSHMatchBlock - Option *ast.SSHOption + Option *ast.SSHOption +} + +type ValidPath string + +func (v ValidPath) AsURI() string { + return "file://" + string(v) +} + +type SSHIndexIncludeValue struct { + common.LocationRange + Value string + + // Actual valid paths, these will be set by the analyzer + Paths []ValidPath +} + +type SSHIndexIncludeLine struct { + Values []*SSHIndexIncludeValue + Option *SSHIndexAllOption } type SSHIndexes struct { @@ -35,18 +55,22 @@ type SSHIndexes struct { OptionsPerRelativeKey map[SSHIndexKey][]*ast.SSHOption // This is a map of `Option name` to a list of options with that name - AllOptionsPerName map[string][]*SSHIndexAllOption + AllOptionsPerName map[string]map[uint32]*SSHIndexAllOption + + Includes map[uint32]*SSHIndexIncludeLine } +var whitespacePattern = regexp.MustCompile(`\S+`) + func CreateIndexes(config ast.SSHConfig) (*SSHIndexes, []common.LSPError) { errs := make([]common.LSPError, 0) indexes := &SSHIndexes{ OptionsPerRelativeKey: make(map[SSHIndexKey][]*ast.SSHOption), - AllOptionsPerName: make(map[string][]*SSHIndexAllOption), + AllOptionsPerName: make(map[string]map[uint32]*SSHIndexAllOption), + Includes: make(map[uint32]*SSHIndexIncludeLine), } it := config.Options.Iterator() - for it.Next() { entry := it.Value().(ast.SSHEntry) @@ -59,7 +83,6 @@ func CreateIndexes(config ast.SSHConfig) (*SSHIndexes, []common.LSPError) { matchBlock := entry.(*ast.SSHMatchBlock) it := matchBlock.Options.Iterator() - for it.Next() { option := it.Value().(*ast.SSHOption) @@ -68,6 +91,43 @@ func CreateIndexes(config ast.SSHConfig) (*SSHIndexes, []common.LSPError) { } } + // Add Includes + for _, includeOption := range indexes.AllOptionsPerName["Include"] { + rawValue := includeOption.Option.OptionValue.Value + pathIndexes := whitespacePattern.FindAllStringIndex(rawValue, -1) + paths := make([]*SSHIndexIncludeValue, 0) + + for _, pathIndex := range pathIndexes { + startIndex := pathIndex[0] + endIndex := pathIndex[1] + + rawPath := rawValue[startIndex:endIndex] + + offset := includeOption.Option.OptionValue.Start.Character + path := SSHIndexIncludeValue{ + LocationRange: common.LocationRange{ + Start: common.Location{ + Line: includeOption.Option.Start.Line, + Character: uint32(startIndex) + offset, + }, + End: common.Location{ + Line: includeOption.Option.Start.Line, + Character: uint32(endIndex) + offset - 1, + }, + }, + Value: rawPath, + Paths: make([]ValidPath, 0), + } + + paths = append(paths, &path) + } + + indexes.Includes[includeOption.Option.Start.Line] = &SSHIndexIncludeLine{ + Values: paths, + Option: includeOption, + } + } + return indexes, errs } @@ -97,17 +157,16 @@ func addOption( i.OptionsPerRelativeKey[indexEntry] = []*ast.SSHOption{option} } - - if existingEntry, found := i.AllOptionsPerName[option.Key.Value]; found { - i.AllOptionsPerName[option.Key.Value] = append(existingEntry, &SSHIndexAllOption{ + if _, found := i.AllOptionsPerName[option.Key.Value]; found { + i.AllOptionsPerName[option.Key.Value][option.Start.Line] = &SSHIndexAllOption{ MatchBlock: matchBlock, - Option: option, - }) + Option: option, + } } else { - i.AllOptionsPerName[option.Key.Value] = []*SSHIndexAllOption{ - { + i.AllOptionsPerName[option.Key.Value] = map[uint32]*SSHIndexAllOption{ + option.Start.Line: { MatchBlock: matchBlock, - Option: option, + Option: option, }, } } diff --git a/handlers/sshd_config/indexes/indexes_test.go b/handlers/sshd_config/indexes/indexes_test.go index c6901d3..7271dc6 100644 --- a/handlers/sshd_config/indexes/indexes_test.go +++ b/handlers/sshd_config/indexes/indexes_test.go @@ -116,3 +116,48 @@ Match Address 192.168.0.1/24 t.Errorf("Expected 3 PermitRootLogin options, but got %v", indexes.AllOptionsPerName["PermitRootLogin"]) } } + +func TestIncludeExample( + t *testing.T, +) { + input := utils.Dedent(` +PermitRootLogin yes +Include /etc/ssh/sshd_config.d/*.conf hello_world +`) + config := ast.NewSSHConfig() + errors := config.Parse(input) + + if len(errors) > 0 { + t.Fatalf("Expected no errors, but got %v", len(errors)) + } + + indexes, errors := CreateIndexes(*config) + + if len(errors) > 0 { + t.Fatalf("Expected no errors, but got %v", len(errors)) + } + + if !(len(indexes.Includes) == 1) { + t.Fatalf("Expected 1 include, but got %v", len(indexes.Includes)) + } + + if !(len(indexes.Includes[1].Values) == 2) { + t.Fatalf("Expected 2 include path, but got %v", len(indexes.Includes[1].Values)) + } + + if !(indexes.Includes[1].Values[0].Value == "/etc/ssh/sshd_config.d/*.conf" && + indexes.Includes[1].Values[0].Start.Line == 1 && + indexes.Includes[1].Values[0].End.Line == 1 && + indexes.Includes[1].Values[0].Start.Character == 8 && + indexes.Includes[1].Values[0].End.Character == 36) { + t.Errorf("Expected '/etc/ssh/sshd_config.d/*.conf' on line 1, but got %v on line %v", indexes.Includes[1].Values[0].Value, indexes.Includes[1].Values[0].Start.Line) + } + + if !(indexes.Includes[1].Values[1].Value == "hello_world" && + indexes.Includes[1].Values[1].Start.Line == 1 && + indexes.Includes[1].Values[1].End.Line == 1 && + indexes.Includes[1].Values[1].Start.Character == 38 && + indexes.Includes[1].Values[1].End.Character == 48) { + t.Errorf("Expected 'hello_world' on line 1, but got %v on line %v", indexes.Includes[1].Values[1].Value, indexes.Includes[1].Values[1].Start.Line) + } +} diff --git a/handlers/sshd_config/lsp/text-document-definition.go b/handlers/sshd_config/lsp/text-document-definition.go new file mode 100644 index 0000000..7ccdb66 --- /dev/null +++ b/handlers/sshd_config/lsp/text-document-definition.go @@ -0,0 +1,23 @@ +package lsp + +import ( + sshdconfig "config-lsp/handlers/sshd_config" + "config-lsp/handlers/sshd_config/handlers" + + "github.com/tliron/glsp" + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func TextDocumentDefinition(context *glsp.Context, params *protocol.DefinitionParams) ([]protocol.Location, error) { + d := sshdconfig.DocumentParserMap[params.TextDocument.URI] + cursor := params.Position.Character + line := params.Position.Line + + if include, found := d.Indexes.Includes[line]; found { + relativeCursor := cursor - include.Option.Option.LocationRange.Start.Character + + return handlers.GetIncludeOptionLocation(include, relativeCursor), nil + } + + return nil, nil +} diff --git a/handlers/sshd_config/shared.go b/handlers/sshd_config/shared.go index 318f6ba..b44850f 100644 --- a/handlers/sshd_config/shared.go +++ b/handlers/sshd_config/shared.go @@ -2,12 +2,14 @@ package sshdconfig import ( "config-lsp/handlers/sshd_config/ast" + "config-lsp/handlers/sshd_config/indexes" protocol "github.com/tliron/glsp/protocol_3_16" ) type SSHDocument struct { - Config *ast.SSHConfig + Config *ast.SSHConfig + Indexes *indexes.SSHIndexes } var DocumentParserMap = map[protocol.DocumentUri]*SSHDocument{} diff --git a/root-handler/text-document-definition.go b/root-handler/text-document-definition.go index 194bcb8..70e7b6a 100644 --- a/root-handler/text-document-definition.go +++ b/root-handler/text-document-definition.go @@ -2,6 +2,7 @@ package roothandler import ( aliases "config-lsp/handlers/aliases/lsp" + sshdconfig "config-lsp/handlers/sshd_config/lsp" "github.com/tliron/glsp" protocol "github.com/tliron/glsp/protocol_3_16" @@ -24,7 +25,7 @@ func TextDocumentDefinition(context *glsp.Context, params *protocol.DefinitionPa case LanguageHosts: return nil, nil case LanguageSSHDConfig: - return nil, nil + return sshdconfig.TextDocumentDefinition(context, params) case LanguageFstab: return nil, nil case LanguageWireguard: From be8c92f605fa68bfdcc8bd7af9b2b3f770287f92 Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Sat, 14 Sep 2024 19:30:02 +0200 Subject: [PATCH 030/133] fix(sshd_config): Improve include --- handlers/sshd_config/analyzer/include.go | 12 ++++++++++- .../sshd_config/lsp/text-document-did-open.go | 20 ++++++++++++------- 2 files changed, 24 insertions(+), 8 deletions(-) diff --git a/handlers/sshd_config/analyzer/include.go b/handlers/sshd_config/analyzer/include.go index f785df3..04164d8 100644 --- a/handlers/sshd_config/analyzer/include.go +++ b/handlers/sshd_config/analyzer/include.go @@ -71,6 +71,10 @@ func createIncludePaths( func parseFile( filePath string, ) (*sshdconfig.SSHDocument, error) { + if d, ok := sshdconfig.DocumentParserMap[filePath]; ok { + return d, nil + } + c := ast.NewSSHConfig() content, err := os.ReadFile(filePath) @@ -79,7 +83,11 @@ func parseFile( return nil, err } - c.Parse(string(content)) + parseErrors := c.Parse(string(content)) + + if len(parseErrors) > 0 { + return nil, errors.New(fmt.Sprintf("Errors in %s", filePath)) + } d := &sshdconfig.SSHDocument{ Config: c, @@ -91,5 +99,7 @@ func parseFile( return nil, errors.New(fmt.Sprintf("Errors in %s", filePath)) } + sshdconfig.DocumentParserMap[filePath] = d + return d, nil } diff --git a/handlers/sshd_config/lsp/text-document-did-open.go b/handlers/sshd_config/lsp/text-document-did-open.go index 7906931..24bb7c0 100644 --- a/handlers/sshd_config/lsp/text-document-did-open.go +++ b/handlers/sshd_config/lsp/text-document-did-open.go @@ -17,13 +17,19 @@ func TextDocumentDidOpen( ) error { common.ClearDiagnostics(context, params.TextDocument.URI) - parser := ast.NewSSHConfig() - document := sshdconfig.SSHDocument{ - Config: parser, - } - sshdconfig.DocumentParserMap[params.TextDocument.URI] = &document + var document *sshdconfig.SSHDocument - errors := parser.Parse(params.TextDocument.Text) + if foundDocument, ok := sshdconfig.DocumentParserMap[params.TextDocument.URI]; ok { + document = foundDocument + } else { + config := ast.NewSSHConfig() + document = &sshdconfig.SSHDocument{ + Config: config, + } + sshdconfig.DocumentParserMap[params.TextDocument.URI] = document + } + + errors := document.Config.Parse(params.TextDocument.Text) diagnostics := utils.Map( errors, @@ -34,7 +40,7 @@ func TextDocumentDidOpen( diagnostics = append( diagnostics, - analyzer.Analyze(&document)..., + analyzer.Analyze(document)..., ) if len(diagnostics) > 0 { From d3b655dc686ac8e69e82f31c132e467e6d424486 Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Sat, 14 Sep 2024 21:08:46 +0200 Subject: [PATCH 031/133] fix: Bugfixes --- doc-values/value-array.go | 40 +++-- doc-values/value-key-enum-assignment.go | 2 +- doc-values/value-key-value-assignment.go | 2 +- doc-values/value-or.go | 2 +- handlers/sshd_config/Config.g4 | 4 +- handlers/sshd_config/ast/parser/Config.interp | 2 +- .../sshd_config/ast/parser/config_parser.go | 152 +++++++++--------- handlers/sshd_config/fields/fields.go | 4 +- handlers/sshd_config/handlers/completions.go | 3 +- 9 files changed, 116 insertions(+), 95 deletions(-) diff --git a/doc-values/value-array.go b/doc-values/value-array.go index 1fd7263..e69d98f 100644 --- a/doc-values/value-array.go +++ b/doc-values/value-array.go @@ -119,24 +119,34 @@ func (v ArrayValue) getCurrentValue(line string, cursor uint32) (string, uint32) return line, cursor } + MIN := uint32(0) + MAX := uint32(len(line) - 1) + var start uint32 var end uint32 + // hello,w[o]rld,and,more + // [h]ello,world + // hello,[w]orld + // hell[o],world + // hello,worl[d] + // hello,world[,] + // hello[,]world,how,are,you + relativePosition, found := utils.FindPreviousCharacter( line, v.Separator, - // defaults - min(len(line)-1, int(cursor)-1), + int(cursor), ) if found { - // +1 to skip the separator + // + 1 to skip the separator start = min( - min(uint32(len(line)), uint32(relativePosition+1)), - uint32(relativePosition+1), + MAX, + uint32(relativePosition)+1, ) } else { - start = 0 + start = MIN } relativePosition, found = utils.FindNextCharacter( @@ -146,21 +156,27 @@ func (v ArrayValue) getCurrentValue(line string, cursor uint32) (string, uint32) ) if found { - // -1 to skip the separator - end = min( - min(uint32(len(line)), uint32(relativePosition)), - cursor, + // - 1 to skip the separator + end = max( + MIN, + uint32(relativePosition)-1, ) } else { - end = uint32(len(line)) + end = MAX } - return line[start:end], cursor - start + if cursor > end { + // The user is typing a new (yet empty) value + return "", 0 + } + + return line[start : end+1], cursor - start } func (v ArrayValue) FetchCompletions(line string, cursor uint32) []protocol.CompletionItem { value, cursor := v.getCurrentValue(line, cursor) + println("after array", value, cursor) return v.SubValue.FetchCompletions(value, cursor) } diff --git a/doc-values/value-key-enum-assignment.go b/doc-values/value-key-enum-assignment.go index 2f27a60..4953caa 100644 --- a/doc-values/value-key-enum-assignment.go +++ b/doc-values/value-key-enum-assignment.go @@ -173,7 +173,7 @@ func (v KeyEnumAssignmentValue) FetchCompletions(line string, cursor uint32) []p relativePosition, found := utils.FindPreviousCharacter( line, v.Separator, - max(0, int(cursor-1)), + int(cursor), ) if found { diff --git a/doc-values/value-key-value-assignment.go b/doc-values/value-key-value-assignment.go index cda5c3c..77e60b7 100644 --- a/doc-values/value-key-value-assignment.go +++ b/doc-values/value-key-value-assignment.go @@ -111,7 +111,7 @@ func (v KeyValueAssignmentValue) FetchCompletions(line string, cursor uint32) [] relativePosition, found := utils.FindPreviousCharacter( line, v.Separator, - max(0, int(cursor-1)), + int(cursor), ) if found { diff --git a/doc-values/value-or.go b/doc-values/value-or.go index 3991a75..37bc8d3 100644 --- a/doc-values/value-or.go +++ b/doc-values/value-or.go @@ -63,7 +63,7 @@ func (v OrValue) FetchCompletions(line string, cursor uint32) []protocol.Complet _, found := utils.FindPreviousCharacter( line, keyEnumValue.Separator, - int(cursor-1), + int(cursor), ) if found { diff --git a/handlers/sshd_config/Config.g4 b/handlers/sshd_config/Config.g4 index 42346ad..376950e 100644 --- a/handlers/sshd_config/Config.g4 +++ b/handlers/sshd_config/Config.g4 @@ -5,7 +5,7 @@ lineStatement ; entry - : WHITESPACE? key? separator? value? WHITESPACE? leadingComment? + : WHITESPACE? key? separator? value? leadingComment? ; separator @@ -17,7 +17,7 @@ key ; value - : (STRING WHITESPACE)? STRING + : (STRING WHITESPACE)? STRING WHITESPACE? ; leadingComment diff --git a/handlers/sshd_config/ast/parser/Config.interp b/handlers/sshd_config/ast/parser/Config.interp index e860731..b286373 100644 --- a/handlers/sshd_config/ast/parser/Config.interp +++ b/handlers/sshd_config/ast/parser/Config.interp @@ -22,4 +22,4 @@ leadingComment atn: -[4, 1, 4, 65, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 2, 5, 7, 5, 1, 0, 1, 0, 3, 0, 15, 8, 0, 1, 0, 1, 0, 3, 0, 19, 8, 0, 3, 0, 21, 8, 0, 1, 0, 1, 0, 1, 1, 3, 1, 26, 8, 1, 1, 1, 3, 1, 29, 8, 1, 1, 1, 3, 1, 32, 8, 1, 1, 1, 3, 1, 35, 8, 1, 1, 1, 3, 1, 38, 8, 1, 1, 1, 3, 1, 41, 8, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, 1, 4, 3, 4, 49, 8, 4, 1, 4, 1, 4, 1, 5, 1, 5, 3, 5, 55, 8, 5, 1, 5, 1, 5, 3, 5, 59, 8, 5, 4, 5, 61, 8, 5, 11, 5, 12, 5, 62, 1, 5, 0, 0, 6, 0, 2, 4, 6, 8, 10, 0, 0, 72, 0, 20, 1, 0, 0, 0, 2, 25, 1, 0, 0, 0, 4, 42, 1, 0, 0, 0, 6, 44, 1, 0, 0, 0, 8, 48, 1, 0, 0, 0, 10, 52, 1, 0, 0, 0, 12, 21, 3, 2, 1, 0, 13, 15, 5, 2, 0, 0, 14, 13, 1, 0, 0, 0, 14, 15, 1, 0, 0, 0, 15, 16, 1, 0, 0, 0, 16, 21, 3, 10, 5, 0, 17, 19, 5, 2, 0, 0, 18, 17, 1, 0, 0, 0, 18, 19, 1, 0, 0, 0, 19, 21, 1, 0, 0, 0, 20, 12, 1, 0, 0, 0, 20, 14, 1, 0, 0, 0, 20, 18, 1, 0, 0, 0, 21, 22, 1, 0, 0, 0, 22, 23, 5, 0, 0, 1, 23, 1, 1, 0, 0, 0, 24, 26, 5, 2, 0, 0, 25, 24, 1, 0, 0, 0, 25, 26, 1, 0, 0, 0, 26, 28, 1, 0, 0, 0, 27, 29, 3, 6, 3, 0, 28, 27, 1, 0, 0, 0, 28, 29, 1, 0, 0, 0, 29, 31, 1, 0, 0, 0, 30, 32, 3, 4, 2, 0, 31, 30, 1, 0, 0, 0, 31, 32, 1, 0, 0, 0, 32, 34, 1, 0, 0, 0, 33, 35, 3, 8, 4, 0, 34, 33, 1, 0, 0, 0, 34, 35, 1, 0, 0, 0, 35, 37, 1, 0, 0, 0, 36, 38, 5, 2, 0, 0, 37, 36, 1, 0, 0, 0, 37, 38, 1, 0, 0, 0, 38, 40, 1, 0, 0, 0, 39, 41, 3, 10, 5, 0, 40, 39, 1, 0, 0, 0, 40, 41, 1, 0, 0, 0, 41, 3, 1, 0, 0, 0, 42, 43, 5, 2, 0, 0, 43, 5, 1, 0, 0, 0, 44, 45, 5, 3, 0, 0, 45, 7, 1, 0, 0, 0, 46, 47, 5, 3, 0, 0, 47, 49, 5, 2, 0, 0, 48, 46, 1, 0, 0, 0, 48, 49, 1, 0, 0, 0, 49, 50, 1, 0, 0, 0, 50, 51, 5, 3, 0, 0, 51, 9, 1, 0, 0, 0, 52, 54, 5, 1, 0, 0, 53, 55, 5, 2, 0, 0, 54, 53, 1, 0, 0, 0, 54, 55, 1, 0, 0, 0, 55, 60, 1, 0, 0, 0, 56, 58, 5, 3, 0, 0, 57, 59, 5, 2, 0, 0, 58, 57, 1, 0, 0, 0, 58, 59, 1, 0, 0, 0, 59, 61, 1, 0, 0, 0, 60, 56, 1, 0, 0, 0, 61, 62, 1, 0, 0, 0, 62, 60, 1, 0, 0, 0, 62, 63, 1, 0, 0, 0, 63, 11, 1, 0, 0, 0, 13, 14, 18, 20, 25, 28, 31, 34, 37, 40, 48, 54, 58, 62] \ No newline at end of file +[4, 1, 4, 64, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 2, 5, 7, 5, 1, 0, 1, 0, 3, 0, 15, 8, 0, 1, 0, 1, 0, 3, 0, 19, 8, 0, 3, 0, 21, 8, 0, 1, 0, 1, 0, 1, 1, 3, 1, 26, 8, 1, 1, 1, 3, 1, 29, 8, 1, 1, 1, 3, 1, 32, 8, 1, 1, 1, 3, 1, 35, 8, 1, 1, 1, 3, 1, 38, 8, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, 1, 4, 3, 4, 46, 8, 4, 1, 4, 1, 4, 3, 4, 50, 8, 4, 1, 5, 1, 5, 3, 5, 54, 8, 5, 1, 5, 1, 5, 3, 5, 58, 8, 5, 4, 5, 60, 8, 5, 11, 5, 12, 5, 61, 1, 5, 0, 0, 6, 0, 2, 4, 6, 8, 10, 0, 0, 71, 0, 20, 1, 0, 0, 0, 2, 25, 1, 0, 0, 0, 4, 39, 1, 0, 0, 0, 6, 41, 1, 0, 0, 0, 8, 45, 1, 0, 0, 0, 10, 51, 1, 0, 0, 0, 12, 21, 3, 2, 1, 0, 13, 15, 5, 2, 0, 0, 14, 13, 1, 0, 0, 0, 14, 15, 1, 0, 0, 0, 15, 16, 1, 0, 0, 0, 16, 21, 3, 10, 5, 0, 17, 19, 5, 2, 0, 0, 18, 17, 1, 0, 0, 0, 18, 19, 1, 0, 0, 0, 19, 21, 1, 0, 0, 0, 20, 12, 1, 0, 0, 0, 20, 14, 1, 0, 0, 0, 20, 18, 1, 0, 0, 0, 21, 22, 1, 0, 0, 0, 22, 23, 5, 0, 0, 1, 23, 1, 1, 0, 0, 0, 24, 26, 5, 2, 0, 0, 25, 24, 1, 0, 0, 0, 25, 26, 1, 0, 0, 0, 26, 28, 1, 0, 0, 0, 27, 29, 3, 6, 3, 0, 28, 27, 1, 0, 0, 0, 28, 29, 1, 0, 0, 0, 29, 31, 1, 0, 0, 0, 30, 32, 3, 4, 2, 0, 31, 30, 1, 0, 0, 0, 31, 32, 1, 0, 0, 0, 32, 34, 1, 0, 0, 0, 33, 35, 3, 8, 4, 0, 34, 33, 1, 0, 0, 0, 34, 35, 1, 0, 0, 0, 35, 37, 1, 0, 0, 0, 36, 38, 3, 10, 5, 0, 37, 36, 1, 0, 0, 0, 37, 38, 1, 0, 0, 0, 38, 3, 1, 0, 0, 0, 39, 40, 5, 2, 0, 0, 40, 5, 1, 0, 0, 0, 41, 42, 5, 3, 0, 0, 42, 7, 1, 0, 0, 0, 43, 44, 5, 3, 0, 0, 44, 46, 5, 2, 0, 0, 45, 43, 1, 0, 0, 0, 45, 46, 1, 0, 0, 0, 46, 47, 1, 0, 0, 0, 47, 49, 5, 3, 0, 0, 48, 50, 5, 2, 0, 0, 49, 48, 1, 0, 0, 0, 49, 50, 1, 0, 0, 0, 50, 9, 1, 0, 0, 0, 51, 53, 5, 1, 0, 0, 52, 54, 5, 2, 0, 0, 53, 52, 1, 0, 0, 0, 53, 54, 1, 0, 0, 0, 54, 59, 1, 0, 0, 0, 55, 57, 5, 3, 0, 0, 56, 58, 5, 2, 0, 0, 57, 56, 1, 0, 0, 0, 57, 58, 1, 0, 0, 0, 58, 60, 1, 0, 0, 0, 59, 55, 1, 0, 0, 0, 60, 61, 1, 0, 0, 0, 61, 59, 1, 0, 0, 0, 61, 62, 1, 0, 0, 0, 62, 11, 1, 0, 0, 0, 13, 14, 18, 20, 25, 28, 31, 34, 37, 45, 49, 53, 57, 61] \ No newline at end of file diff --git a/handlers/sshd_config/ast/parser/config_parser.go b/handlers/sshd_config/ast/parser/config_parser.go index 57ca885..79e7cfd 100644 --- a/handlers/sshd_config/ast/parser/config_parser.go +++ b/handlers/sshd_config/ast/parser/config_parser.go @@ -43,34 +43,34 @@ func configParserInit() { } staticData.PredictionContextCache = antlr.NewPredictionContextCache() staticData.serializedATN = []int32{ - 4, 1, 4, 65, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, + 4, 1, 4, 64, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 2, 5, 7, 5, 1, 0, 1, 0, 3, 0, 15, 8, 0, 1, 0, 1, 0, 3, 0, 19, 8, 0, 3, 0, 21, 8, 0, 1, 0, 1, 0, 1, 1, 3, 1, 26, 8, 1, 1, 1, 3, 1, 29, 8, 1, 1, - 1, 3, 1, 32, 8, 1, 1, 1, 3, 1, 35, 8, 1, 1, 1, 3, 1, 38, 8, 1, 1, 1, 3, - 1, 41, 8, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, 1, 4, 3, 4, 49, 8, 4, 1, 4, - 1, 4, 1, 5, 1, 5, 3, 5, 55, 8, 5, 1, 5, 1, 5, 3, 5, 59, 8, 5, 4, 5, 61, - 8, 5, 11, 5, 12, 5, 62, 1, 5, 0, 0, 6, 0, 2, 4, 6, 8, 10, 0, 0, 72, 0, - 20, 1, 0, 0, 0, 2, 25, 1, 0, 0, 0, 4, 42, 1, 0, 0, 0, 6, 44, 1, 0, 0, 0, - 8, 48, 1, 0, 0, 0, 10, 52, 1, 0, 0, 0, 12, 21, 3, 2, 1, 0, 13, 15, 5, 2, - 0, 0, 14, 13, 1, 0, 0, 0, 14, 15, 1, 0, 0, 0, 15, 16, 1, 0, 0, 0, 16, 21, - 3, 10, 5, 0, 17, 19, 5, 2, 0, 0, 18, 17, 1, 0, 0, 0, 18, 19, 1, 0, 0, 0, - 19, 21, 1, 0, 0, 0, 20, 12, 1, 0, 0, 0, 20, 14, 1, 0, 0, 0, 20, 18, 1, - 0, 0, 0, 21, 22, 1, 0, 0, 0, 22, 23, 5, 0, 0, 1, 23, 1, 1, 0, 0, 0, 24, - 26, 5, 2, 0, 0, 25, 24, 1, 0, 0, 0, 25, 26, 1, 0, 0, 0, 26, 28, 1, 0, 0, - 0, 27, 29, 3, 6, 3, 0, 28, 27, 1, 0, 0, 0, 28, 29, 1, 0, 0, 0, 29, 31, - 1, 0, 0, 0, 30, 32, 3, 4, 2, 0, 31, 30, 1, 0, 0, 0, 31, 32, 1, 0, 0, 0, - 32, 34, 1, 0, 0, 0, 33, 35, 3, 8, 4, 0, 34, 33, 1, 0, 0, 0, 34, 35, 1, - 0, 0, 0, 35, 37, 1, 0, 0, 0, 36, 38, 5, 2, 0, 0, 37, 36, 1, 0, 0, 0, 37, - 38, 1, 0, 0, 0, 38, 40, 1, 0, 0, 0, 39, 41, 3, 10, 5, 0, 40, 39, 1, 0, - 0, 0, 40, 41, 1, 0, 0, 0, 41, 3, 1, 0, 0, 0, 42, 43, 5, 2, 0, 0, 43, 5, - 1, 0, 0, 0, 44, 45, 5, 3, 0, 0, 45, 7, 1, 0, 0, 0, 46, 47, 5, 3, 0, 0, - 47, 49, 5, 2, 0, 0, 48, 46, 1, 0, 0, 0, 48, 49, 1, 0, 0, 0, 49, 50, 1, - 0, 0, 0, 50, 51, 5, 3, 0, 0, 51, 9, 1, 0, 0, 0, 52, 54, 5, 1, 0, 0, 53, - 55, 5, 2, 0, 0, 54, 53, 1, 0, 0, 0, 54, 55, 1, 0, 0, 0, 55, 60, 1, 0, 0, - 0, 56, 58, 5, 3, 0, 0, 57, 59, 5, 2, 0, 0, 58, 57, 1, 0, 0, 0, 58, 59, - 1, 0, 0, 0, 59, 61, 1, 0, 0, 0, 60, 56, 1, 0, 0, 0, 61, 62, 1, 0, 0, 0, - 62, 60, 1, 0, 0, 0, 62, 63, 1, 0, 0, 0, 63, 11, 1, 0, 0, 0, 13, 14, 18, - 20, 25, 28, 31, 34, 37, 40, 48, 54, 58, 62, + 1, 3, 1, 32, 8, 1, 1, 1, 3, 1, 35, 8, 1, 1, 1, 3, 1, 38, 8, 1, 1, 2, 1, + 2, 1, 3, 1, 3, 1, 4, 1, 4, 3, 4, 46, 8, 4, 1, 4, 1, 4, 3, 4, 50, 8, 4, + 1, 5, 1, 5, 3, 5, 54, 8, 5, 1, 5, 1, 5, 3, 5, 58, 8, 5, 4, 5, 60, 8, 5, + 11, 5, 12, 5, 61, 1, 5, 0, 0, 6, 0, 2, 4, 6, 8, 10, 0, 0, 71, 0, 20, 1, + 0, 0, 0, 2, 25, 1, 0, 0, 0, 4, 39, 1, 0, 0, 0, 6, 41, 1, 0, 0, 0, 8, 45, + 1, 0, 0, 0, 10, 51, 1, 0, 0, 0, 12, 21, 3, 2, 1, 0, 13, 15, 5, 2, 0, 0, + 14, 13, 1, 0, 0, 0, 14, 15, 1, 0, 0, 0, 15, 16, 1, 0, 0, 0, 16, 21, 3, + 10, 5, 0, 17, 19, 5, 2, 0, 0, 18, 17, 1, 0, 0, 0, 18, 19, 1, 0, 0, 0, 19, + 21, 1, 0, 0, 0, 20, 12, 1, 0, 0, 0, 20, 14, 1, 0, 0, 0, 20, 18, 1, 0, 0, + 0, 21, 22, 1, 0, 0, 0, 22, 23, 5, 0, 0, 1, 23, 1, 1, 0, 0, 0, 24, 26, 5, + 2, 0, 0, 25, 24, 1, 0, 0, 0, 25, 26, 1, 0, 0, 0, 26, 28, 1, 0, 0, 0, 27, + 29, 3, 6, 3, 0, 28, 27, 1, 0, 0, 0, 28, 29, 1, 0, 0, 0, 29, 31, 1, 0, 0, + 0, 30, 32, 3, 4, 2, 0, 31, 30, 1, 0, 0, 0, 31, 32, 1, 0, 0, 0, 32, 34, + 1, 0, 0, 0, 33, 35, 3, 8, 4, 0, 34, 33, 1, 0, 0, 0, 34, 35, 1, 0, 0, 0, + 35, 37, 1, 0, 0, 0, 36, 38, 3, 10, 5, 0, 37, 36, 1, 0, 0, 0, 37, 38, 1, + 0, 0, 0, 38, 3, 1, 0, 0, 0, 39, 40, 5, 2, 0, 0, 40, 5, 1, 0, 0, 0, 41, + 42, 5, 3, 0, 0, 42, 7, 1, 0, 0, 0, 43, 44, 5, 3, 0, 0, 44, 46, 5, 2, 0, + 0, 45, 43, 1, 0, 0, 0, 45, 46, 1, 0, 0, 0, 46, 47, 1, 0, 0, 0, 47, 49, + 5, 3, 0, 0, 48, 50, 5, 2, 0, 0, 49, 48, 1, 0, 0, 0, 49, 50, 1, 0, 0, 0, + 50, 9, 1, 0, 0, 0, 51, 53, 5, 1, 0, 0, 52, 54, 5, 2, 0, 0, 53, 52, 1, 0, + 0, 0, 53, 54, 1, 0, 0, 0, 54, 59, 1, 0, 0, 0, 55, 57, 5, 3, 0, 0, 56, 58, + 5, 2, 0, 0, 57, 56, 1, 0, 0, 0, 57, 58, 1, 0, 0, 0, 58, 60, 1, 0, 0, 0, + 59, 55, 1, 0, 0, 0, 60, 61, 1, 0, 0, 0, 61, 59, 1, 0, 0, 0, 61, 62, 1, + 0, 0, 0, 62, 11, 1, 0, 0, 0, 13, 14, 18, 20, 25, 28, 31, 34, 37, 45, 49, + 53, 57, 61, } deserializer := antlr.NewATNDeserializer(nil) staticData.atn = deserializer.Deserialize(staticData.serializedATN) @@ -330,8 +330,7 @@ type IEntryContext interface { GetParser() antlr.Parser // Getter signatures - AllWHITESPACE() []antlr.TerminalNode - WHITESPACE(i int) antlr.TerminalNode + WHITESPACE() antlr.TerminalNode Key() IKeyContext Separator() ISeparatorContext Value() IValueContext @@ -373,12 +372,8 @@ func NewEntryContext(parser antlr.Parser, parent antlr.ParserRuleContext, invoki func (s *EntryContext) GetParser() antlr.Parser { return s.parser } -func (s *EntryContext) AllWHITESPACE() []antlr.TerminalNode { - return s.GetTokens(ConfigParserWHITESPACE) -} - -func (s *EntryContext) WHITESPACE(i int) antlr.TerminalNode { - return s.GetToken(ConfigParserWHITESPACE, i) +func (s *EntryContext) WHITESPACE() antlr.TerminalNode { + return s.GetToken(ConfigParserWHITESPACE, 0) } func (s *EntryContext) Key() IKeyContext { @@ -501,15 +496,17 @@ func (p *ConfigParser) Entry() (localctx IEntryContext) { } p.SetState(31) p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) - if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 5, p.GetParserRuleContext()) == 1 { + if _la == ConfigParserWHITESPACE { { p.SetState(30) p.Separator() } - } else if p.HasError() { // JIM - goto errorExit } p.SetState(34) p.GetErrorHandler().Sync(p) @@ -532,27 +529,9 @@ func (p *ConfigParser) Entry() (localctx IEntryContext) { } _la = p.GetTokenStream().LA(1) - if _la == ConfigParserWHITESPACE { - { - p.SetState(36) - p.Match(ConfigParserWHITESPACE) - if p.HasError() { - // Recognition error - abort rule - goto errorExit - } - } - - } - p.SetState(40) - p.GetErrorHandler().Sync(p) - if p.HasError() { - goto errorExit - } - _la = p.GetTokenStream().LA(1) - if _la == ConfigParserHASH { { - p.SetState(39) + p.SetState(36) p.LeadingComment() } @@ -646,7 +625,7 @@ func (p *ConfigParser) Separator() (localctx ISeparatorContext) { p.EnterRule(localctx, 4, ConfigParserRULE_separator) p.EnterOuterAlt(localctx, 1) { - p.SetState(42) + p.SetState(39) p.Match(ConfigParserWHITESPACE) if p.HasError() { // Recognition error - abort rule @@ -742,7 +721,7 @@ func (p *ConfigParser) Key() (localctx IKeyContext) { p.EnterRule(localctx, 6, ConfigParserRULE_key) p.EnterOuterAlt(localctx, 1) { - p.SetState(44) + p.SetState(41) p.Match(ConfigParserSTRING) if p.HasError() { // Recognition error - abort rule @@ -773,7 +752,8 @@ type IValueContext interface { // Getter signatures AllSTRING() []antlr.TerminalNode STRING(i int) antlr.TerminalNode - WHITESPACE() antlr.TerminalNode + AllWHITESPACE() []antlr.TerminalNode + WHITESPACE(i int) antlr.TerminalNode // IsValueContext differentiates from other interfaces. IsValueContext() @@ -819,8 +799,12 @@ func (s *ValueContext) STRING(i int) antlr.TerminalNode { return s.GetToken(ConfigParserSTRING, i) } -func (s *ValueContext) WHITESPACE() antlr.TerminalNode { - return s.GetToken(ConfigParserWHITESPACE, 0) +func (s *ValueContext) AllWHITESPACE() []antlr.TerminalNode { + return s.GetTokens(ConfigParserWHITESPACE) +} + +func (s *ValueContext) WHITESPACE(i int) antlr.TerminalNode { + return s.GetToken(ConfigParserWHITESPACE, i) } func (s *ValueContext) GetRuleContext() antlr.RuleContext { @@ -846,13 +830,15 @@ func (s *ValueContext) ExitRule(listener antlr.ParseTreeListener) { func (p *ConfigParser) Value() (localctx IValueContext) { localctx = NewValueContext(p, p.GetParserRuleContext(), p.GetState()) p.EnterRule(localctx, 8, ConfigParserRULE_value) + var _la int + p.EnterOuterAlt(localctx, 1) - p.SetState(48) + p.SetState(45) p.GetErrorHandler().Sync(p) - if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 9, p.GetParserRuleContext()) == 1 { + if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 8, p.GetParserRuleContext()) == 1 { { - p.SetState(46) + p.SetState(43) p.Match(ConfigParserSTRING) if p.HasError() { // Recognition error - abort rule @@ -860,7 +846,7 @@ func (p *ConfigParser) Value() (localctx IValueContext) { } } { - p.SetState(47) + p.SetState(44) p.Match(ConfigParserWHITESPACE) if p.HasError() { // Recognition error - abort rule @@ -872,13 +858,31 @@ func (p *ConfigParser) Value() (localctx IValueContext) { goto errorExit } { - p.SetState(50) + p.SetState(47) p.Match(ConfigParserSTRING) if p.HasError() { // Recognition error - abort rule goto errorExit } } + p.SetState(49) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + if _la == ConfigParserWHITESPACE { + { + p.SetState(48) + p.Match(ConfigParserWHITESPACE) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + + } errorExit: if p.HasError() { @@ -990,14 +994,14 @@ func (p *ConfigParser) LeadingComment() (localctx ILeadingCommentContext) { p.EnterOuterAlt(localctx, 1) { - p.SetState(52) + p.SetState(51) p.Match(ConfigParserHASH) if p.HasError() { // Recognition error - abort rule goto errorExit } } - p.SetState(54) + p.SetState(53) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -1006,7 +1010,7 @@ func (p *ConfigParser) LeadingComment() (localctx ILeadingCommentContext) { if _la == ConfigParserWHITESPACE { { - p.SetState(53) + p.SetState(52) p.Match(ConfigParserWHITESPACE) if p.HasError() { // Recognition error - abort rule @@ -1015,7 +1019,7 @@ func (p *ConfigParser) LeadingComment() (localctx ILeadingCommentContext) { } } - p.SetState(60) + p.SetState(59) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -1024,14 +1028,14 @@ func (p *ConfigParser) LeadingComment() (localctx ILeadingCommentContext) { for ok := true; ok; ok = _la == ConfigParserSTRING { { - p.SetState(56) + p.SetState(55) p.Match(ConfigParserSTRING) if p.HasError() { // Recognition error - abort rule goto errorExit } } - p.SetState(58) + p.SetState(57) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -1040,7 +1044,7 @@ func (p *ConfigParser) LeadingComment() (localctx ILeadingCommentContext) { if _la == ConfigParserWHITESPACE { { - p.SetState(57) + p.SetState(56) p.Match(ConfigParserWHITESPACE) if p.HasError() { // Recognition error - abort rule @@ -1050,7 +1054,7 @@ func (p *ConfigParser) LeadingComment() (localctx ILeadingCommentContext) { } - p.SetState(62) + p.SetState(61) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit diff --git a/handlers/sshd_config/fields/fields.go b/handlers/sshd_config/fields/fields.go index d7abb52..b58c6f3 100644 --- a/handlers/sshd_config/fields/fields.go +++ b/handlers/sshd_config/fields/fields.go @@ -572,8 +572,8 @@ Only a subset of keywords may be used on the lines following a Match keyword. Av SubValue: docvalues.KeyEnumAssignmentValue{ Separator: " ", Values: map[docvalues.EnumString]docvalues.Value{ - docvalues.CreateEnumString("User"): docvalues.StringValue{}, - docvalues.CreateEnumString("Group"): docvalues.StringValue{}, + docvalues.CreateEnumString("User"): docvalues.UserValue("", false), + docvalues.CreateEnumString("Group"): docvalues.GroupValue("", false), docvalues.CreateEnumString("Host"): docvalues.StringValue{}, docvalues.CreateEnumString("LocalAddress"): docvalues.StringValue{}, docvalues.CreateEnumString("LocalPort"): docvalues.NumberValue{Min: &ZERO, Max: &MAX_PORT}, diff --git a/handlers/sshd_config/handlers/completions.go b/handlers/sshd_config/handlers/completions.go index 0e4f48f..ceba5e7 100644 --- a/handlers/sshd_config/handlers/completions.go +++ b/handlers/sshd_config/handlers/completions.go @@ -1,6 +1,7 @@ package handlers import ( + "config-lsp/common" docvalues "config-lsp/doc-values" sshdconfig "config-lsp/handlers/sshd_config" "config-lsp/handlers/sshd_config/ast" @@ -66,7 +67,7 @@ func GetOptionCompletions( return option.FetchCompletions("", 0), nil } - relativeCursor := cursor - entry.OptionValue.Start.Character + relativeCursor := common.CursorToCharacterIndex(cursor - entry.OptionValue.Start.Character) line := entry.OptionValue.Value return option.FetchCompletions(line, relativeCursor), nil From 83d7ac144ff46597116255c1bf725162d08fcc73 Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Sat, 14 Sep 2024 22:22:01 +0200 Subject: [PATCH 032/133] feat(sshd_config): Add antlr parser for match option --- handlers/sshd_config/ast/listener.go | 22 +- .../sshd_config/fields/match-parser/Match.g4 | 67 ++ .../fields/match-parser/error-listener.go | 45 + .../fields/match-parser/listener.go | 99 ++ .../fields/match-parser/match_ast.go | 40 + .../sshd_config/fields/match-parser/parser.go | 52 + .../fields/match-parser/parser/Match.interp | 36 + .../fields/match-parser/parser/Match.tokens | 11 + .../match-parser/parser/MatchLexer.interp | 47 + .../match-parser/parser/MatchLexer.tokens | 11 + .../parser/match_base_listener.go | 52 + .../fields/match-parser/parser/match_lexer.go | 148 +++ .../match-parser/parser/match_listener.go | 40 + .../match-parser/parser/match_parser.go | 887 ++++++++++++++++++ .../fields/match-parser/parser_test.go | 79 ++ 15 files changed, 1625 insertions(+), 11 deletions(-) create mode 100644 handlers/sshd_config/fields/match-parser/Match.g4 create mode 100644 handlers/sshd_config/fields/match-parser/error-listener.go create mode 100644 handlers/sshd_config/fields/match-parser/listener.go create mode 100644 handlers/sshd_config/fields/match-parser/match_ast.go create mode 100644 handlers/sshd_config/fields/match-parser/parser.go create mode 100644 handlers/sshd_config/fields/match-parser/parser/Match.interp create mode 100644 handlers/sshd_config/fields/match-parser/parser/Match.tokens create mode 100644 handlers/sshd_config/fields/match-parser/parser/MatchLexer.interp create mode 100644 handlers/sshd_config/fields/match-parser/parser/MatchLexer.tokens create mode 100644 handlers/sshd_config/fields/match-parser/parser/match_base_listener.go create mode 100644 handlers/sshd_config/fields/match-parser/parser/match_lexer.go create mode 100644 handlers/sshd_config/fields/match-parser/parser/match_listener.go create mode 100644 handlers/sshd_config/fields/match-parser/parser/match_parser.go create mode 100644 handlers/sshd_config/fields/match-parser/parser_test.go diff --git a/handlers/sshd_config/ast/listener.go b/handlers/sshd_config/ast/listener.go index e6d4b47..2b3583c 100644 --- a/handlers/sshd_config/ast/listener.go +++ b/handlers/sshd_config/ast/listener.go @@ -8,17 +8,6 @@ import ( "strings" ) -func createListener( - config *SSHConfig, - context *sshListenerContext, -) sshParserListener { - return sshParserListener{ - Config: config, - Errors: make([]common.LSPError, 0), - sshContext: context, - } -} - type sshListenerContext struct { line uint32 currentOption *SSHOption @@ -33,6 +22,17 @@ func createSSHListenerContext() *sshListenerContext { return context } +func createListener( + config *SSHConfig, + context *sshListenerContext, +) sshParserListener { + return sshParserListener{ + Config: config, + Errors: make([]common.LSPError, 0), + sshContext: context, + } +} + type sshParserListener struct { *parser.BaseConfigListener Config *SSHConfig diff --git a/handlers/sshd_config/fields/match-parser/Match.g4 b/handlers/sshd_config/fields/match-parser/Match.g4 new file mode 100644 index 0000000..9c2c54b --- /dev/null +++ b/handlers/sshd_config/fields/match-parser/Match.g4 @@ -0,0 +1,67 @@ +grammar Match; + +root + : matchEntry? (WHITESPACE matchEntry)* EOF + ; + +matchEntry + : criteria WHITESPACE? values? + ; + +criteria + : USER + | GROUP + | HOST + | LOCALADDRESS + | LOCALPORT + | RDOMAIN + | ADDRESS + ; + +values + : value? (COMMA value?)* + ; + +value + : STRING + ; + +USER + : ('U'|'u') ('S'|'s') ('E'|'e') ('R'|'r') + ; + +GROUP + : ('G'|'g') ('R'|'r') ('O'|'o') ('U'|'u') ('P'|'p') + ; + +HOST + : ('H'|'h') ('O'|'o') ('S'|'s') ('T'|'t') + ; + +LOCALADDRESS + : ('L'|'l') ('O'|'o') ('C'|'c') ('A'|'a') ('L'|'l') ('A'|'a') ('D'|'d') ('D'|'d') ('R'|'r') ('E'|'e') ('S'|'s') ('S'|'s') + ; + +LOCALPORT + : ('L'|'l') ('O'|'o') ('C'|'c') ('A'|'a') ('L'|'l') ('P'|'p') ('O'|'o') ('R'|'r') ('T'|'t') + ; + +RDOMAIN + : ('R'|'r') ('D'|'d') ('O'|'o') ('M'|'m') ('A'|'a') ('I'|'i') ('N'|'n') + ; + +ADDRESS + : ('A'|'a') ('D'|'d') ('D'|'d') ('R'|'r') ('E'|'e') ('S'|'s') ('S'|'s') + ; + +COMMA + : ',' + ; + +STRING + : ~(' ' | '\t' | '\r' | '\n' | '#' | ',')+ + ; + +WHITESPACE + : [ \t]+ + ; diff --git a/handlers/sshd_config/fields/match-parser/error-listener.go b/handlers/sshd_config/fields/match-parser/error-listener.go new file mode 100644 index 0000000..fd9e4bb --- /dev/null +++ b/handlers/sshd_config/fields/match-parser/error-listener.go @@ -0,0 +1,45 @@ +package match_parser + +import ( + "config-lsp/common" + + "github.com/antlr4-go/antlr/v4" +) + +type errorListenerContext struct { + line uint32 +} + +func createErrorListener( + line uint32, +) errorListener { + return errorListener{ + Errors: make([]common.LSPError, 0), + context: errorListenerContext{ + line: line, + }, + } +} + +type errorListener struct { + *antlr.DefaultErrorListener + Errors []common.LSPError + context errorListenerContext +} + +func (d *errorListener) SyntaxError( + recognizer antlr.Recognizer, + offendingSymbol interface{}, + _ int, + character int, + message string, + error antlr.RecognitionException, +) { + line := d.context.line + d.Errors = append(d.Errors, common.LSPError{ + Range: common.CreateSingleCharRange(uint32(line), uint32(character)), + Err: common.SyntaxError{ + Message: message, + }, + }) +} diff --git a/handlers/sshd_config/fields/match-parser/listener.go b/handlers/sshd_config/fields/match-parser/listener.go new file mode 100644 index 0000000..a7ca5ac --- /dev/null +++ b/handlers/sshd_config/fields/match-parser/listener.go @@ -0,0 +1,99 @@ +package match_parser + +import ( + "config-lsp/common" + "config-lsp/handlers/sshd_config/fields/match-parser/parser" + "config-lsp/utils" + "errors" + "fmt" + "strings" +) + +func createMatchListenerContext( + line uint32, +) *matchListenerContext { + return &matchListenerContext{ + currentEntry: nil, + line: line, + } +} + +type matchListenerContext struct { + currentEntry *MatchEntry + line uint32 +} + +func createListener( + match *Match, + context *matchListenerContext, +) matchParserListener { + return matchParserListener{ + match: match, + Errors: make([]common.LSPError, 0), + matchContext: context, + } +} + +type matchParserListener struct { + *parser.BaseMatchListener + match *Match + Errors []common.LSPError + matchContext *matchListenerContext +} + +func (s *matchParserListener) EnterMatchEntry(ctx *parser.MatchEntryContext) { + location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext) + location.ChangeBothLines(s.matchContext.line) + + entry := &MatchEntry{ + LocationRange: location, + Value: ctx.GetText(), + Values: make([]*MatchValue, 0), + } + + s.match.Entries = append(s.match.Entries, entry) + s.matchContext.currentEntry = entry +} + +func (s *matchParserListener) ExitMatchEntry(ctx *parser.MatchEntryContext) { + s.matchContext.currentEntry = nil +} + +var availableCriteria = map[string]MatchCriteriaType{ + string(MatchCriteriaTypeUser): MatchCriteriaTypeUser, + string(MatchCriteriaTypeGroup): MatchCriteriaTypeGroup, + string(MatchCriteriaTypeHost): MatchCriteriaTypeHost, + string(MatchCriteriaTypeLocalAddress): MatchCriteriaTypeLocalAddress, + string(MatchCriteriaTypeLocalPort): MatchCriteriaTypeLocalPort, + string(MatchCriteriaTypeRDomain): MatchCriteriaTypeRDomain, + string(MatchCriteriaTypeAddress): MatchCriteriaTypeAddress, +} + +func (s *matchParserListener) EnterCriteria(ctx *parser.CriteriaContext) { + location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext) + location.ChangeBothLines(s.matchContext.line) + + criteria, found := availableCriteria[ctx.GetText()] + + if !found { + s.Errors = append(s.Errors, common.LSPError{ + Range: location, + Err: errors.New(fmt.Sprintf("Unknown criteria: %s; It must be one of: %s", ctx.GetText(), strings.Join(utils.KeysOfMap(availableCriteria), ", "))), + }) + return + } + + s.matchContext.currentEntry.Criteria = criteria +} + +func (s *matchParserListener) EnterValue(ctx *parser.ValueContext) { + location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext) + location.ChangeBothLines(s.matchContext.line) + + value := &MatchValue{ + LocationRange: location, + Value: ctx.GetText(), + } + + s.matchContext.currentEntry.Values = append(s.matchContext.currentEntry.Values, value) +} diff --git a/handlers/sshd_config/fields/match-parser/match_ast.go b/handlers/sshd_config/fields/match-parser/match_ast.go new file mode 100644 index 0000000..2f97f1f --- /dev/null +++ b/handlers/sshd_config/fields/match-parser/match_ast.go @@ -0,0 +1,40 @@ +package match_parser + +import ( + "config-lsp/common" +) + +type Match struct { + Entries []*MatchEntry +} + +type MatchCriteriaType string + +const ( + MatchCriteriaTypeUser MatchCriteriaType = "User" + MatchCriteriaTypeGroup MatchCriteriaType = "Group" + MatchCriteriaTypeHost MatchCriteriaType = "Host" + MatchCriteriaTypeLocalAddress MatchCriteriaType = "LocalAddress" + MatchCriteriaTypeLocalPort MatchCriteriaType = "LocalPort" + MatchCriteriaTypeRDomain MatchCriteriaType = "RDomain" + MatchCriteriaTypeAddress MatchCriteriaType = "Address" +) + +type MatchCriteria struct { + common.LocationRange + + Type MatchCriteriaType +} + +type MatchEntry struct { + common.LocationRange + Value string + + Criteria MatchCriteriaType + Values []*MatchValue +} + +type MatchValue struct { + common.LocationRange + Value string +} diff --git a/handlers/sshd_config/fields/match-parser/parser.go b/handlers/sshd_config/fields/match-parser/parser.go new file mode 100644 index 0000000..96fe394 --- /dev/null +++ b/handlers/sshd_config/fields/match-parser/parser.go @@ -0,0 +1,52 @@ +package match_parser + +import ( + "config-lsp/common" + "config-lsp/handlers/sshd_config/fields/match-parser/parser" + "github.com/antlr4-go/antlr/v4" +) + +func NewMatch() *Match { + match := new(Match) + match.Clear() + + return match +} + +func (m *Match) Clear() { + m.Entries = make([]*MatchEntry, 0) +} + +func (m *Match) Parse( + input string, + line uint32, +) []common.LSPError { + context := createMatchListenerContext(line) + + stream := antlr.NewInputStream(input) + + lexerErrorListener := createErrorListener(context.line) + lexer := parser.NewMatchLexer(stream) + lexer.RemoveErrorListeners() + lexer.AddErrorListener(&lexerErrorListener) + + tokenStream := antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel) + + parserErrorListener := createErrorListener(context.line) + antlrParser := parser.NewMatchParser(tokenStream) + antlrParser.RemoveErrorListeners() + antlrParser.AddErrorListener(&parserErrorListener) + + listener := createListener(m, context) + antlr.ParseTreeWalkerDefault.Walk( + &listener, + antlrParser.Root(), + ) + + errors := lexerErrorListener.Errors + errors = append(errors, parserErrorListener.Errors...) + errors = append(errors, listener.Errors...) + + return errors + +} diff --git a/handlers/sshd_config/fields/match-parser/parser/Match.interp b/handlers/sshd_config/fields/match-parser/parser/Match.interp new file mode 100644 index 0000000..274d459 --- /dev/null +++ b/handlers/sshd_config/fields/match-parser/parser/Match.interp @@ -0,0 +1,36 @@ +token literal names: +null +null +null +null +null +null +null +null +',' +null +null + +token symbolic names: +null +USER +GROUP +HOST +LOCALADDRESS +LOCALPORT +RDOMAIN +ADDRESS +COMMA +STRING +WHITESPACE + +rule names: +root +matchEntry +criteria +values +value + + +atn: +[4, 1, 10, 46, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 1, 0, 3, 0, 12, 8, 0, 1, 0, 1, 0, 5, 0, 16, 8, 0, 10, 0, 12, 0, 19, 9, 0, 1, 0, 1, 0, 1, 1, 1, 1, 3, 1, 25, 8, 1, 1, 1, 3, 1, 28, 8, 1, 1, 2, 1, 2, 1, 3, 3, 3, 33, 8, 3, 1, 3, 1, 3, 3, 3, 37, 8, 3, 5, 3, 39, 8, 3, 10, 3, 12, 3, 42, 9, 3, 1, 4, 1, 4, 1, 4, 0, 0, 5, 0, 2, 4, 6, 8, 0, 1, 1, 0, 1, 7, 47, 0, 11, 1, 0, 0, 0, 2, 22, 1, 0, 0, 0, 4, 29, 1, 0, 0, 0, 6, 32, 1, 0, 0, 0, 8, 43, 1, 0, 0, 0, 10, 12, 3, 2, 1, 0, 11, 10, 1, 0, 0, 0, 11, 12, 1, 0, 0, 0, 12, 17, 1, 0, 0, 0, 13, 14, 5, 10, 0, 0, 14, 16, 3, 2, 1, 0, 15, 13, 1, 0, 0, 0, 16, 19, 1, 0, 0, 0, 17, 15, 1, 0, 0, 0, 17, 18, 1, 0, 0, 0, 18, 20, 1, 0, 0, 0, 19, 17, 1, 0, 0, 0, 20, 21, 5, 0, 0, 1, 21, 1, 1, 0, 0, 0, 22, 24, 3, 4, 2, 0, 23, 25, 5, 10, 0, 0, 24, 23, 1, 0, 0, 0, 24, 25, 1, 0, 0, 0, 25, 27, 1, 0, 0, 0, 26, 28, 3, 6, 3, 0, 27, 26, 1, 0, 0, 0, 27, 28, 1, 0, 0, 0, 28, 3, 1, 0, 0, 0, 29, 30, 7, 0, 0, 0, 30, 5, 1, 0, 0, 0, 31, 33, 3, 8, 4, 0, 32, 31, 1, 0, 0, 0, 32, 33, 1, 0, 0, 0, 33, 40, 1, 0, 0, 0, 34, 36, 5, 8, 0, 0, 35, 37, 3, 8, 4, 0, 36, 35, 1, 0, 0, 0, 36, 37, 1, 0, 0, 0, 37, 39, 1, 0, 0, 0, 38, 34, 1, 0, 0, 0, 39, 42, 1, 0, 0, 0, 40, 38, 1, 0, 0, 0, 40, 41, 1, 0, 0, 0, 41, 7, 1, 0, 0, 0, 42, 40, 1, 0, 0, 0, 43, 44, 5, 9, 0, 0, 44, 9, 1, 0, 0, 0, 7, 11, 17, 24, 27, 32, 36, 40] \ No newline at end of file diff --git a/handlers/sshd_config/fields/match-parser/parser/Match.tokens b/handlers/sshd_config/fields/match-parser/parser/Match.tokens new file mode 100644 index 0000000..21f2b73 --- /dev/null +++ b/handlers/sshd_config/fields/match-parser/parser/Match.tokens @@ -0,0 +1,11 @@ +USER=1 +GROUP=2 +HOST=3 +LOCALADDRESS=4 +LOCALPORT=5 +RDOMAIN=6 +ADDRESS=7 +COMMA=8 +STRING=9 +WHITESPACE=10 +','=8 diff --git a/handlers/sshd_config/fields/match-parser/parser/MatchLexer.interp b/handlers/sshd_config/fields/match-parser/parser/MatchLexer.interp new file mode 100644 index 0000000..590b1bb --- /dev/null +++ b/handlers/sshd_config/fields/match-parser/parser/MatchLexer.interp @@ -0,0 +1,47 @@ +token literal names: +null +null +null +null +null +null +null +null +',' +null +null + +token symbolic names: +null +USER +GROUP +HOST +LOCALADDRESS +LOCALPORT +RDOMAIN +ADDRESS +COMMA +STRING +WHITESPACE + +rule names: +USER +GROUP +HOST +LOCALADDRESS +LOCALPORT +RDOMAIN +ADDRESS +COMMA +STRING +WHITESPACE + +channel names: +DEFAULT_TOKEN_CHANNEL +HIDDEN + +mode names: +DEFAULT_MODE + +atn: +[4, 0, 10, 88, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 2, 5, 7, 5, 2, 6, 7, 6, 2, 7, 7, 7, 2, 8, 7, 8, 2, 9, 7, 9, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 7, 1, 7, 1, 8, 4, 8, 80, 8, 8, 11, 8, 12, 8, 81, 1, 9, 4, 9, 85, 8, 9, 11, 9, 12, 9, 86, 0, 0, 10, 1, 1, 3, 2, 5, 3, 7, 4, 9, 5, 11, 6, 13, 7, 15, 8, 17, 9, 19, 10, 1, 0, 18, 2, 0, 85, 85, 117, 117, 2, 0, 83, 83, 115, 115, 2, 0, 69, 69, 101, 101, 2, 0, 82, 82, 114, 114, 2, 0, 71, 71, 103, 103, 2, 0, 79, 79, 111, 111, 2, 0, 80, 80, 112, 112, 2, 0, 72, 72, 104, 104, 2, 0, 84, 84, 116, 116, 2, 0, 76, 76, 108, 108, 2, 0, 67, 67, 99, 99, 2, 0, 65, 65, 97, 97, 2, 0, 68, 68, 100, 100, 2, 0, 77, 77, 109, 109, 2, 0, 73, 73, 105, 105, 2, 0, 78, 78, 110, 110, 5, 0, 9, 10, 13, 13, 32, 32, 35, 35, 44, 44, 2, 0, 9, 9, 32, 32, 89, 0, 1, 1, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, 5, 1, 0, 0, 0, 0, 7, 1, 0, 0, 0, 0, 9, 1, 0, 0, 0, 0, 11, 1, 0, 0, 0, 0, 13, 1, 0, 0, 0, 0, 15, 1, 0, 0, 0, 0, 17, 1, 0, 0, 0, 0, 19, 1, 0, 0, 0, 1, 21, 1, 0, 0, 0, 3, 26, 1, 0, 0, 0, 5, 32, 1, 0, 0, 0, 7, 37, 1, 0, 0, 0, 9, 50, 1, 0, 0, 0, 11, 60, 1, 0, 0, 0, 13, 68, 1, 0, 0, 0, 15, 76, 1, 0, 0, 0, 17, 79, 1, 0, 0, 0, 19, 84, 1, 0, 0, 0, 21, 22, 7, 0, 0, 0, 22, 23, 7, 1, 0, 0, 23, 24, 7, 2, 0, 0, 24, 25, 7, 3, 0, 0, 25, 2, 1, 0, 0, 0, 26, 27, 7, 4, 0, 0, 27, 28, 7, 3, 0, 0, 28, 29, 7, 5, 0, 0, 29, 30, 7, 0, 0, 0, 30, 31, 7, 6, 0, 0, 31, 4, 1, 0, 0, 0, 32, 33, 7, 7, 0, 0, 33, 34, 7, 5, 0, 0, 34, 35, 7, 1, 0, 0, 35, 36, 7, 8, 0, 0, 36, 6, 1, 0, 0, 0, 37, 38, 7, 9, 0, 0, 38, 39, 7, 5, 0, 0, 39, 40, 7, 10, 0, 0, 40, 41, 7, 11, 0, 0, 41, 42, 7, 9, 0, 0, 42, 43, 7, 11, 0, 0, 43, 44, 7, 12, 0, 0, 44, 45, 7, 12, 0, 0, 45, 46, 7, 3, 0, 0, 46, 47, 7, 2, 0, 0, 47, 48, 7, 1, 0, 0, 48, 49, 7, 1, 0, 0, 49, 8, 1, 0, 0, 0, 50, 51, 7, 9, 0, 0, 51, 52, 7, 5, 0, 0, 52, 53, 7, 10, 0, 0, 53, 54, 7, 11, 0, 0, 54, 55, 7, 9, 0, 0, 55, 56, 7, 6, 0, 0, 56, 57, 7, 5, 0, 0, 57, 58, 7, 3, 0, 0, 58, 59, 7, 8, 0, 0, 59, 10, 1, 0, 0, 0, 60, 61, 7, 3, 0, 0, 61, 62, 7, 12, 0, 0, 62, 63, 7, 5, 0, 0, 63, 64, 7, 13, 0, 0, 64, 65, 7, 11, 0, 0, 65, 66, 7, 14, 0, 0, 66, 67, 7, 15, 0, 0, 67, 12, 1, 0, 0, 0, 68, 69, 7, 11, 0, 0, 69, 70, 7, 12, 0, 0, 70, 71, 7, 12, 0, 0, 71, 72, 7, 3, 0, 0, 72, 73, 7, 2, 0, 0, 73, 74, 7, 1, 0, 0, 74, 75, 7, 1, 0, 0, 75, 14, 1, 0, 0, 0, 76, 77, 5, 44, 0, 0, 77, 16, 1, 0, 0, 0, 78, 80, 8, 16, 0, 0, 79, 78, 1, 0, 0, 0, 80, 81, 1, 0, 0, 0, 81, 79, 1, 0, 0, 0, 81, 82, 1, 0, 0, 0, 82, 18, 1, 0, 0, 0, 83, 85, 7, 17, 0, 0, 84, 83, 1, 0, 0, 0, 85, 86, 1, 0, 0, 0, 86, 84, 1, 0, 0, 0, 86, 87, 1, 0, 0, 0, 87, 20, 1, 0, 0, 0, 3, 0, 81, 86, 0] \ No newline at end of file diff --git a/handlers/sshd_config/fields/match-parser/parser/MatchLexer.tokens b/handlers/sshd_config/fields/match-parser/parser/MatchLexer.tokens new file mode 100644 index 0000000..21f2b73 --- /dev/null +++ b/handlers/sshd_config/fields/match-parser/parser/MatchLexer.tokens @@ -0,0 +1,11 @@ +USER=1 +GROUP=2 +HOST=3 +LOCALADDRESS=4 +LOCALPORT=5 +RDOMAIN=6 +ADDRESS=7 +COMMA=8 +STRING=9 +WHITESPACE=10 +','=8 diff --git a/handlers/sshd_config/fields/match-parser/parser/match_base_listener.go b/handlers/sshd_config/fields/match-parser/parser/match_base_listener.go new file mode 100644 index 0000000..2190a4a --- /dev/null +++ b/handlers/sshd_config/fields/match-parser/parser/match_base_listener.go @@ -0,0 +1,52 @@ +// Code generated from Match.g4 by ANTLR 4.13.0. DO NOT EDIT. + +package parser // Match + +import "github.com/antlr4-go/antlr/v4" + +// BaseMatchListener is a complete listener for a parse tree produced by MatchParser. +type BaseMatchListener struct{} + +var _ MatchListener = &BaseMatchListener{} + +// VisitTerminal is called when a terminal node is visited. +func (s *BaseMatchListener) VisitTerminal(node antlr.TerminalNode) {} + +// VisitErrorNode is called when an error node is visited. +func (s *BaseMatchListener) VisitErrorNode(node antlr.ErrorNode) {} + +// EnterEveryRule is called when any rule is entered. +func (s *BaseMatchListener) EnterEveryRule(ctx antlr.ParserRuleContext) {} + +// ExitEveryRule is called when any rule is exited. +func (s *BaseMatchListener) ExitEveryRule(ctx antlr.ParserRuleContext) {} + +// EnterRoot is called when production root is entered. +func (s *BaseMatchListener) EnterRoot(ctx *RootContext) {} + +// ExitRoot is called when production root is exited. +func (s *BaseMatchListener) ExitRoot(ctx *RootContext) {} + +// EnterMatchEntry is called when production matchEntry is entered. +func (s *BaseMatchListener) EnterMatchEntry(ctx *MatchEntryContext) {} + +// ExitMatchEntry is called when production matchEntry is exited. +func (s *BaseMatchListener) ExitMatchEntry(ctx *MatchEntryContext) {} + +// EnterCriteria is called when production criteria is entered. +func (s *BaseMatchListener) EnterCriteria(ctx *CriteriaContext) {} + +// ExitCriteria is called when production criteria is exited. +func (s *BaseMatchListener) ExitCriteria(ctx *CriteriaContext) {} + +// EnterValues is called when production values is entered. +func (s *BaseMatchListener) EnterValues(ctx *ValuesContext) {} + +// ExitValues is called when production values is exited. +func (s *BaseMatchListener) ExitValues(ctx *ValuesContext) {} + +// EnterValue is called when production value is entered. +func (s *BaseMatchListener) EnterValue(ctx *ValueContext) {} + +// ExitValue is called when production value is exited. +func (s *BaseMatchListener) ExitValue(ctx *ValueContext) {} diff --git a/handlers/sshd_config/fields/match-parser/parser/match_lexer.go b/handlers/sshd_config/fields/match-parser/parser/match_lexer.go new file mode 100644 index 0000000..0c61e79 --- /dev/null +++ b/handlers/sshd_config/fields/match-parser/parser/match_lexer.go @@ -0,0 +1,148 @@ +// Code generated from Match.g4 by ANTLR 4.13.0. DO NOT EDIT. + +package parser + +import ( + "fmt" + "github.com/antlr4-go/antlr/v4" + "sync" + "unicode" +) + +// Suppress unused import error +var _ = fmt.Printf +var _ = sync.Once{} +var _ = unicode.IsLetter + +type MatchLexer struct { + *antlr.BaseLexer + channelNames []string + modeNames []string + // TODO: EOF string +} + +var MatchLexerLexerStaticData struct { + once sync.Once + serializedATN []int32 + ChannelNames []string + ModeNames []string + LiteralNames []string + SymbolicNames []string + RuleNames []string + PredictionContextCache *antlr.PredictionContextCache + atn *antlr.ATN + decisionToDFA []*antlr.DFA +} + +func matchlexerLexerInit() { + staticData := &MatchLexerLexerStaticData + staticData.ChannelNames = []string{ + "DEFAULT_TOKEN_CHANNEL", "HIDDEN", + } + staticData.ModeNames = []string{ + "DEFAULT_MODE", + } + staticData.LiteralNames = []string{ + "", "", "", "", "", "", "", "", "','", + } + staticData.SymbolicNames = []string{ + "", "USER", "GROUP", "HOST", "LOCALADDRESS", "LOCALPORT", "RDOMAIN", + "ADDRESS", "COMMA", "STRING", "WHITESPACE", + } + staticData.RuleNames = []string{ + "USER", "GROUP", "HOST", "LOCALADDRESS", "LOCALPORT", "RDOMAIN", "ADDRESS", + "COMMA", "STRING", "WHITESPACE", + } + staticData.PredictionContextCache = antlr.NewPredictionContextCache() + staticData.serializedATN = []int32{ + 4, 0, 10, 88, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, + 4, 7, 4, 2, 5, 7, 5, 2, 6, 7, 6, 2, 7, 7, 7, 2, 8, 7, 8, 2, 9, 7, 9, 1, + 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, + 2, 1, 2, 1, 2, 1, 2, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, + 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, + 4, 1, 4, 1, 4, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 6, 1, + 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 7, 1, 7, 1, 8, 4, 8, 80, 8, 8, + 11, 8, 12, 8, 81, 1, 9, 4, 9, 85, 8, 9, 11, 9, 12, 9, 86, 0, 0, 10, 1, + 1, 3, 2, 5, 3, 7, 4, 9, 5, 11, 6, 13, 7, 15, 8, 17, 9, 19, 10, 1, 0, 18, + 2, 0, 85, 85, 117, 117, 2, 0, 83, 83, 115, 115, 2, 0, 69, 69, 101, 101, + 2, 0, 82, 82, 114, 114, 2, 0, 71, 71, 103, 103, 2, 0, 79, 79, 111, 111, + 2, 0, 80, 80, 112, 112, 2, 0, 72, 72, 104, 104, 2, 0, 84, 84, 116, 116, + 2, 0, 76, 76, 108, 108, 2, 0, 67, 67, 99, 99, 2, 0, 65, 65, 97, 97, 2, + 0, 68, 68, 100, 100, 2, 0, 77, 77, 109, 109, 2, 0, 73, 73, 105, 105, 2, + 0, 78, 78, 110, 110, 5, 0, 9, 10, 13, 13, 32, 32, 35, 35, 44, 44, 2, 0, + 9, 9, 32, 32, 89, 0, 1, 1, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, 5, 1, 0, 0, 0, + 0, 7, 1, 0, 0, 0, 0, 9, 1, 0, 0, 0, 0, 11, 1, 0, 0, 0, 0, 13, 1, 0, 0, + 0, 0, 15, 1, 0, 0, 0, 0, 17, 1, 0, 0, 0, 0, 19, 1, 0, 0, 0, 1, 21, 1, 0, + 0, 0, 3, 26, 1, 0, 0, 0, 5, 32, 1, 0, 0, 0, 7, 37, 1, 0, 0, 0, 9, 50, 1, + 0, 0, 0, 11, 60, 1, 0, 0, 0, 13, 68, 1, 0, 0, 0, 15, 76, 1, 0, 0, 0, 17, + 79, 1, 0, 0, 0, 19, 84, 1, 0, 0, 0, 21, 22, 7, 0, 0, 0, 22, 23, 7, 1, 0, + 0, 23, 24, 7, 2, 0, 0, 24, 25, 7, 3, 0, 0, 25, 2, 1, 0, 0, 0, 26, 27, 7, + 4, 0, 0, 27, 28, 7, 3, 0, 0, 28, 29, 7, 5, 0, 0, 29, 30, 7, 0, 0, 0, 30, + 31, 7, 6, 0, 0, 31, 4, 1, 0, 0, 0, 32, 33, 7, 7, 0, 0, 33, 34, 7, 5, 0, + 0, 34, 35, 7, 1, 0, 0, 35, 36, 7, 8, 0, 0, 36, 6, 1, 0, 0, 0, 37, 38, 7, + 9, 0, 0, 38, 39, 7, 5, 0, 0, 39, 40, 7, 10, 0, 0, 40, 41, 7, 11, 0, 0, + 41, 42, 7, 9, 0, 0, 42, 43, 7, 11, 0, 0, 43, 44, 7, 12, 0, 0, 44, 45, 7, + 12, 0, 0, 45, 46, 7, 3, 0, 0, 46, 47, 7, 2, 0, 0, 47, 48, 7, 1, 0, 0, 48, + 49, 7, 1, 0, 0, 49, 8, 1, 0, 0, 0, 50, 51, 7, 9, 0, 0, 51, 52, 7, 5, 0, + 0, 52, 53, 7, 10, 0, 0, 53, 54, 7, 11, 0, 0, 54, 55, 7, 9, 0, 0, 55, 56, + 7, 6, 0, 0, 56, 57, 7, 5, 0, 0, 57, 58, 7, 3, 0, 0, 58, 59, 7, 8, 0, 0, + 59, 10, 1, 0, 0, 0, 60, 61, 7, 3, 0, 0, 61, 62, 7, 12, 0, 0, 62, 63, 7, + 5, 0, 0, 63, 64, 7, 13, 0, 0, 64, 65, 7, 11, 0, 0, 65, 66, 7, 14, 0, 0, + 66, 67, 7, 15, 0, 0, 67, 12, 1, 0, 0, 0, 68, 69, 7, 11, 0, 0, 69, 70, 7, + 12, 0, 0, 70, 71, 7, 12, 0, 0, 71, 72, 7, 3, 0, 0, 72, 73, 7, 2, 0, 0, + 73, 74, 7, 1, 0, 0, 74, 75, 7, 1, 0, 0, 75, 14, 1, 0, 0, 0, 76, 77, 5, + 44, 0, 0, 77, 16, 1, 0, 0, 0, 78, 80, 8, 16, 0, 0, 79, 78, 1, 0, 0, 0, + 80, 81, 1, 0, 0, 0, 81, 79, 1, 0, 0, 0, 81, 82, 1, 0, 0, 0, 82, 18, 1, + 0, 0, 0, 83, 85, 7, 17, 0, 0, 84, 83, 1, 0, 0, 0, 85, 86, 1, 0, 0, 0, 86, + 84, 1, 0, 0, 0, 86, 87, 1, 0, 0, 0, 87, 20, 1, 0, 0, 0, 3, 0, 81, 86, 0, + } + deserializer := antlr.NewATNDeserializer(nil) + staticData.atn = deserializer.Deserialize(staticData.serializedATN) + atn := staticData.atn + staticData.decisionToDFA = make([]*antlr.DFA, len(atn.DecisionToState)) + decisionToDFA := staticData.decisionToDFA + for index, state := range atn.DecisionToState { + decisionToDFA[index] = antlr.NewDFA(state, index) + } +} + +// MatchLexerInit initializes any static state used to implement MatchLexer. By default the +// static state used to implement the lexer is lazily initialized during the first call to +// NewMatchLexer(). You can call this function if you wish to initialize the static state ahead +// of time. +func MatchLexerInit() { + staticData := &MatchLexerLexerStaticData + staticData.once.Do(matchlexerLexerInit) +} + +// NewMatchLexer produces a new lexer instance for the optional input antlr.CharStream. +func NewMatchLexer(input antlr.CharStream) *MatchLexer { + MatchLexerInit() + l := new(MatchLexer) + l.BaseLexer = antlr.NewBaseLexer(input) + staticData := &MatchLexerLexerStaticData + l.Interpreter = antlr.NewLexerATNSimulator(l, staticData.atn, staticData.decisionToDFA, staticData.PredictionContextCache) + l.channelNames = staticData.ChannelNames + l.modeNames = staticData.ModeNames + l.RuleNames = staticData.RuleNames + l.LiteralNames = staticData.LiteralNames + l.SymbolicNames = staticData.SymbolicNames + l.GrammarFileName = "Match.g4" + // TODO: l.EOF = antlr.TokenEOF + + return l +} + +// MatchLexer tokens. +const ( + MatchLexerUSER = 1 + MatchLexerGROUP = 2 + MatchLexerHOST = 3 + MatchLexerLOCALADDRESS = 4 + MatchLexerLOCALPORT = 5 + MatchLexerRDOMAIN = 6 + MatchLexerADDRESS = 7 + MatchLexerCOMMA = 8 + MatchLexerSTRING = 9 + MatchLexerWHITESPACE = 10 +) diff --git a/handlers/sshd_config/fields/match-parser/parser/match_listener.go b/handlers/sshd_config/fields/match-parser/parser/match_listener.go new file mode 100644 index 0000000..8db9553 --- /dev/null +++ b/handlers/sshd_config/fields/match-parser/parser/match_listener.go @@ -0,0 +1,40 @@ +// Code generated from Match.g4 by ANTLR 4.13.0. DO NOT EDIT. + +package parser // Match + +import "github.com/antlr4-go/antlr/v4" + +// MatchListener is a complete listener for a parse tree produced by MatchParser. +type MatchListener interface { + antlr.ParseTreeListener + + // EnterRoot is called when entering the root production. + EnterRoot(c *RootContext) + + // EnterMatchEntry is called when entering the matchEntry production. + EnterMatchEntry(c *MatchEntryContext) + + // EnterCriteria is called when entering the criteria production. + EnterCriteria(c *CriteriaContext) + + // EnterValues is called when entering the values production. + EnterValues(c *ValuesContext) + + // EnterValue is called when entering the value production. + EnterValue(c *ValueContext) + + // ExitRoot is called when exiting the root production. + ExitRoot(c *RootContext) + + // ExitMatchEntry is called when exiting the matchEntry production. + ExitMatchEntry(c *MatchEntryContext) + + // ExitCriteria is called when exiting the criteria production. + ExitCriteria(c *CriteriaContext) + + // ExitValues is called when exiting the values production. + ExitValues(c *ValuesContext) + + // ExitValue is called when exiting the value production. + ExitValue(c *ValueContext) +} diff --git a/handlers/sshd_config/fields/match-parser/parser/match_parser.go b/handlers/sshd_config/fields/match-parser/parser/match_parser.go new file mode 100644 index 0000000..79a4ea4 --- /dev/null +++ b/handlers/sshd_config/fields/match-parser/parser/match_parser.go @@ -0,0 +1,887 @@ +// Code generated from Match.g4 by ANTLR 4.13.0. DO NOT EDIT. + +package parser // Match + +import ( + "fmt" + "strconv" + "sync" + + "github.com/antlr4-go/antlr/v4" +) + +// Suppress unused import errors +var _ = fmt.Printf +var _ = strconv.Itoa +var _ = sync.Once{} + +type MatchParser struct { + *antlr.BaseParser +} + +var MatchParserStaticData struct { + once sync.Once + serializedATN []int32 + LiteralNames []string + SymbolicNames []string + RuleNames []string + PredictionContextCache *antlr.PredictionContextCache + atn *antlr.ATN + decisionToDFA []*antlr.DFA +} + +func matchParserInit() { + staticData := &MatchParserStaticData + staticData.LiteralNames = []string{ + "", "", "", "", "", "", "", "", "','", + } + staticData.SymbolicNames = []string{ + "", "USER", "GROUP", "HOST", "LOCALADDRESS", "LOCALPORT", "RDOMAIN", + "ADDRESS", "COMMA", "STRING", "WHITESPACE", + } + staticData.RuleNames = []string{ + "root", "matchEntry", "criteria", "values", "value", + } + staticData.PredictionContextCache = antlr.NewPredictionContextCache() + staticData.serializedATN = []int32{ + 4, 1, 10, 46, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, + 4, 1, 0, 3, 0, 12, 8, 0, 1, 0, 1, 0, 5, 0, 16, 8, 0, 10, 0, 12, 0, 19, + 9, 0, 1, 0, 1, 0, 1, 1, 1, 1, 3, 1, 25, 8, 1, 1, 1, 3, 1, 28, 8, 1, 1, + 2, 1, 2, 1, 3, 3, 3, 33, 8, 3, 1, 3, 1, 3, 3, 3, 37, 8, 3, 5, 3, 39, 8, + 3, 10, 3, 12, 3, 42, 9, 3, 1, 4, 1, 4, 1, 4, 0, 0, 5, 0, 2, 4, 6, 8, 0, + 1, 1, 0, 1, 7, 47, 0, 11, 1, 0, 0, 0, 2, 22, 1, 0, 0, 0, 4, 29, 1, 0, 0, + 0, 6, 32, 1, 0, 0, 0, 8, 43, 1, 0, 0, 0, 10, 12, 3, 2, 1, 0, 11, 10, 1, + 0, 0, 0, 11, 12, 1, 0, 0, 0, 12, 17, 1, 0, 0, 0, 13, 14, 5, 10, 0, 0, 14, + 16, 3, 2, 1, 0, 15, 13, 1, 0, 0, 0, 16, 19, 1, 0, 0, 0, 17, 15, 1, 0, 0, + 0, 17, 18, 1, 0, 0, 0, 18, 20, 1, 0, 0, 0, 19, 17, 1, 0, 0, 0, 20, 21, + 5, 0, 0, 1, 21, 1, 1, 0, 0, 0, 22, 24, 3, 4, 2, 0, 23, 25, 5, 10, 0, 0, + 24, 23, 1, 0, 0, 0, 24, 25, 1, 0, 0, 0, 25, 27, 1, 0, 0, 0, 26, 28, 3, + 6, 3, 0, 27, 26, 1, 0, 0, 0, 27, 28, 1, 0, 0, 0, 28, 3, 1, 0, 0, 0, 29, + 30, 7, 0, 0, 0, 30, 5, 1, 0, 0, 0, 31, 33, 3, 8, 4, 0, 32, 31, 1, 0, 0, + 0, 32, 33, 1, 0, 0, 0, 33, 40, 1, 0, 0, 0, 34, 36, 5, 8, 0, 0, 35, 37, + 3, 8, 4, 0, 36, 35, 1, 0, 0, 0, 36, 37, 1, 0, 0, 0, 37, 39, 1, 0, 0, 0, + 38, 34, 1, 0, 0, 0, 39, 42, 1, 0, 0, 0, 40, 38, 1, 0, 0, 0, 40, 41, 1, + 0, 0, 0, 41, 7, 1, 0, 0, 0, 42, 40, 1, 0, 0, 0, 43, 44, 5, 9, 0, 0, 44, + 9, 1, 0, 0, 0, 7, 11, 17, 24, 27, 32, 36, 40, + } + deserializer := antlr.NewATNDeserializer(nil) + staticData.atn = deserializer.Deserialize(staticData.serializedATN) + atn := staticData.atn + staticData.decisionToDFA = make([]*antlr.DFA, len(atn.DecisionToState)) + decisionToDFA := staticData.decisionToDFA + for index, state := range atn.DecisionToState { + decisionToDFA[index] = antlr.NewDFA(state, index) + } +} + +// MatchParserInit initializes any static state used to implement MatchParser. By default the +// static state used to implement the parser is lazily initialized during the first call to +// NewMatchParser(). You can call this function if you wish to initialize the static state ahead +// of time. +func MatchParserInit() { + staticData := &MatchParserStaticData + staticData.once.Do(matchParserInit) +} + +// NewMatchParser produces a new parser instance for the optional input antlr.TokenStream. +func NewMatchParser(input antlr.TokenStream) *MatchParser { + MatchParserInit() + this := new(MatchParser) + this.BaseParser = antlr.NewBaseParser(input) + staticData := &MatchParserStaticData + this.Interpreter = antlr.NewParserATNSimulator(this, staticData.atn, staticData.decisionToDFA, staticData.PredictionContextCache) + this.RuleNames = staticData.RuleNames + this.LiteralNames = staticData.LiteralNames + this.SymbolicNames = staticData.SymbolicNames + this.GrammarFileName = "Match.g4" + + return this +} + +// MatchParser tokens. +const ( + MatchParserEOF = antlr.TokenEOF + MatchParserUSER = 1 + MatchParserGROUP = 2 + MatchParserHOST = 3 + MatchParserLOCALADDRESS = 4 + MatchParserLOCALPORT = 5 + MatchParserRDOMAIN = 6 + MatchParserADDRESS = 7 + MatchParserCOMMA = 8 + MatchParserSTRING = 9 + MatchParserWHITESPACE = 10 +) + +// MatchParser rules. +const ( + MatchParserRULE_root = 0 + MatchParserRULE_matchEntry = 1 + MatchParserRULE_criteria = 2 + MatchParserRULE_values = 3 + MatchParserRULE_value = 4 +) + +// IRootContext is an interface to support dynamic dispatch. +type IRootContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + + // Getter signatures + EOF() antlr.TerminalNode + AllMatchEntry() []IMatchEntryContext + MatchEntry(i int) IMatchEntryContext + AllWHITESPACE() []antlr.TerminalNode + WHITESPACE(i int) antlr.TerminalNode + + // IsRootContext differentiates from other interfaces. + IsRootContext() +} + +type RootContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptyRootContext() *RootContext { + var p = new(RootContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = MatchParserRULE_root + return p +} + +func InitEmptyRootContext(p *RootContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = MatchParserRULE_root +} + +func (*RootContext) IsRootContext() {} + +func NewRootContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *RootContext { + var p = new(RootContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = MatchParserRULE_root + + return p +} + +func (s *RootContext) GetParser() antlr.Parser { return s.parser } + +func (s *RootContext) EOF() antlr.TerminalNode { + return s.GetToken(MatchParserEOF, 0) +} + +func (s *RootContext) AllMatchEntry() []IMatchEntryContext { + children := s.GetChildren() + len := 0 + for _, ctx := range children { + if _, ok := ctx.(IMatchEntryContext); ok { + len++ + } + } + + tst := make([]IMatchEntryContext, len) + i := 0 + for _, ctx := range children { + if t, ok := ctx.(IMatchEntryContext); ok { + tst[i] = t.(IMatchEntryContext) + i++ + } + } + + return tst +} + +func (s *RootContext) MatchEntry(i int) IMatchEntryContext { + var t antlr.RuleContext + j := 0 + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(IMatchEntryContext); ok { + if j == i { + t = ctx.(antlr.RuleContext) + break + } + j++ + } + } + + if t == nil { + return nil + } + + return t.(IMatchEntryContext) +} + +func (s *RootContext) AllWHITESPACE() []antlr.TerminalNode { + return s.GetTokens(MatchParserWHITESPACE) +} + +func (s *RootContext) WHITESPACE(i int) antlr.TerminalNode { + return s.GetToken(MatchParserWHITESPACE, i) +} + +func (s *RootContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *RootContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +func (s *RootContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(MatchListener); ok { + listenerT.EnterRoot(s) + } +} + +func (s *RootContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(MatchListener); ok { + listenerT.ExitRoot(s) + } +} + +func (p *MatchParser) Root() (localctx IRootContext) { + localctx = NewRootContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 0, MatchParserRULE_root) + var _la int + + p.EnterOuterAlt(localctx, 1) + p.SetState(11) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + if (int64(_la) & ^0x3f) == 0 && ((int64(1)<<_la)&254) != 0 { + { + p.SetState(10) + p.MatchEntry() + } + + } + p.SetState(17) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + for _la == MatchParserWHITESPACE { + { + p.SetState(13) + p.Match(MatchParserWHITESPACE) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + { + p.SetState(14) + p.MatchEntry() + } + + p.SetState(19) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + } + { + p.SetState(20) + p.Match(MatchParserEOF) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} + +// IMatchEntryContext is an interface to support dynamic dispatch. +type IMatchEntryContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + + // Getter signatures + Criteria() ICriteriaContext + WHITESPACE() antlr.TerminalNode + Values() IValuesContext + + // IsMatchEntryContext differentiates from other interfaces. + IsMatchEntryContext() +} + +type MatchEntryContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptyMatchEntryContext() *MatchEntryContext { + var p = new(MatchEntryContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = MatchParserRULE_matchEntry + return p +} + +func InitEmptyMatchEntryContext(p *MatchEntryContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = MatchParserRULE_matchEntry +} + +func (*MatchEntryContext) IsMatchEntryContext() {} + +func NewMatchEntryContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *MatchEntryContext { + var p = new(MatchEntryContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = MatchParserRULE_matchEntry + + return p +} + +func (s *MatchEntryContext) GetParser() antlr.Parser { return s.parser } + +func (s *MatchEntryContext) Criteria() ICriteriaContext { + var t antlr.RuleContext + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(ICriteriaContext); ok { + t = ctx.(antlr.RuleContext) + break + } + } + + if t == nil { + return nil + } + + return t.(ICriteriaContext) +} + +func (s *MatchEntryContext) WHITESPACE() antlr.TerminalNode { + return s.GetToken(MatchParserWHITESPACE, 0) +} + +func (s *MatchEntryContext) Values() IValuesContext { + var t antlr.RuleContext + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(IValuesContext); ok { + t = ctx.(antlr.RuleContext) + break + } + } + + if t == nil { + return nil + } + + return t.(IValuesContext) +} + +func (s *MatchEntryContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *MatchEntryContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +func (s *MatchEntryContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(MatchListener); ok { + listenerT.EnterMatchEntry(s) + } +} + +func (s *MatchEntryContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(MatchListener); ok { + listenerT.ExitMatchEntry(s) + } +} + +func (p *MatchParser) MatchEntry() (localctx IMatchEntryContext) { + localctx = NewMatchEntryContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 2, MatchParserRULE_matchEntry) + p.EnterOuterAlt(localctx, 1) + { + p.SetState(22) + p.Criteria() + } + p.SetState(24) + p.GetErrorHandler().Sync(p) + + if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 2, p.GetParserRuleContext()) == 1 { + { + p.SetState(23) + p.Match(MatchParserWHITESPACE) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + + } else if p.HasError() { // JIM + goto errorExit + } + p.SetState(27) + p.GetErrorHandler().Sync(p) + + if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 3, p.GetParserRuleContext()) == 1 { + { + p.SetState(26) + p.Values() + } + + } else if p.HasError() { // JIM + goto errorExit + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} + +// ICriteriaContext is an interface to support dynamic dispatch. +type ICriteriaContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + + // Getter signatures + USER() antlr.TerminalNode + GROUP() antlr.TerminalNode + HOST() antlr.TerminalNode + LOCALADDRESS() antlr.TerminalNode + LOCALPORT() antlr.TerminalNode + RDOMAIN() antlr.TerminalNode + ADDRESS() antlr.TerminalNode + + // IsCriteriaContext differentiates from other interfaces. + IsCriteriaContext() +} + +type CriteriaContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptyCriteriaContext() *CriteriaContext { + var p = new(CriteriaContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = MatchParserRULE_criteria + return p +} + +func InitEmptyCriteriaContext(p *CriteriaContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = MatchParserRULE_criteria +} + +func (*CriteriaContext) IsCriteriaContext() {} + +func NewCriteriaContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *CriteriaContext { + var p = new(CriteriaContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = MatchParserRULE_criteria + + return p +} + +func (s *CriteriaContext) GetParser() antlr.Parser { return s.parser } + +func (s *CriteriaContext) USER() antlr.TerminalNode { + return s.GetToken(MatchParserUSER, 0) +} + +func (s *CriteriaContext) GROUP() antlr.TerminalNode { + return s.GetToken(MatchParserGROUP, 0) +} + +func (s *CriteriaContext) HOST() antlr.TerminalNode { + return s.GetToken(MatchParserHOST, 0) +} + +func (s *CriteriaContext) LOCALADDRESS() antlr.TerminalNode { + return s.GetToken(MatchParserLOCALADDRESS, 0) +} + +func (s *CriteriaContext) LOCALPORT() antlr.TerminalNode { + return s.GetToken(MatchParserLOCALPORT, 0) +} + +func (s *CriteriaContext) RDOMAIN() antlr.TerminalNode { + return s.GetToken(MatchParserRDOMAIN, 0) +} + +func (s *CriteriaContext) ADDRESS() antlr.TerminalNode { + return s.GetToken(MatchParserADDRESS, 0) +} + +func (s *CriteriaContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *CriteriaContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +func (s *CriteriaContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(MatchListener); ok { + listenerT.EnterCriteria(s) + } +} + +func (s *CriteriaContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(MatchListener); ok { + listenerT.ExitCriteria(s) + } +} + +func (p *MatchParser) Criteria() (localctx ICriteriaContext) { + localctx = NewCriteriaContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 4, MatchParserRULE_criteria) + var _la int + + p.EnterOuterAlt(localctx, 1) + { + p.SetState(29) + _la = p.GetTokenStream().LA(1) + + if !((int64(_la) & ^0x3f) == 0 && ((int64(1)<<_la)&254) != 0) { + p.GetErrorHandler().RecoverInline(p) + } else { + p.GetErrorHandler().ReportMatch(p) + p.Consume() + } + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} + +// IValuesContext is an interface to support dynamic dispatch. +type IValuesContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + + // Getter signatures + AllValue() []IValueContext + Value(i int) IValueContext + AllCOMMA() []antlr.TerminalNode + COMMA(i int) antlr.TerminalNode + + // IsValuesContext differentiates from other interfaces. + IsValuesContext() +} + +type ValuesContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptyValuesContext() *ValuesContext { + var p = new(ValuesContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = MatchParserRULE_values + return p +} + +func InitEmptyValuesContext(p *ValuesContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = MatchParserRULE_values +} + +func (*ValuesContext) IsValuesContext() {} + +func NewValuesContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *ValuesContext { + var p = new(ValuesContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = MatchParserRULE_values + + return p +} + +func (s *ValuesContext) GetParser() antlr.Parser { return s.parser } + +func (s *ValuesContext) AllValue() []IValueContext { + children := s.GetChildren() + len := 0 + for _, ctx := range children { + if _, ok := ctx.(IValueContext); ok { + len++ + } + } + + tst := make([]IValueContext, len) + i := 0 + for _, ctx := range children { + if t, ok := ctx.(IValueContext); ok { + tst[i] = t.(IValueContext) + i++ + } + } + + return tst +} + +func (s *ValuesContext) Value(i int) IValueContext { + var t antlr.RuleContext + j := 0 + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(IValueContext); ok { + if j == i { + t = ctx.(antlr.RuleContext) + break + } + j++ + } + } + + if t == nil { + return nil + } + + return t.(IValueContext) +} + +func (s *ValuesContext) AllCOMMA() []antlr.TerminalNode { + return s.GetTokens(MatchParserCOMMA) +} + +func (s *ValuesContext) COMMA(i int) antlr.TerminalNode { + return s.GetToken(MatchParserCOMMA, i) +} + +func (s *ValuesContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *ValuesContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +func (s *ValuesContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(MatchListener); ok { + listenerT.EnterValues(s) + } +} + +func (s *ValuesContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(MatchListener); ok { + listenerT.ExitValues(s) + } +} + +func (p *MatchParser) Values() (localctx IValuesContext) { + localctx = NewValuesContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 6, MatchParserRULE_values) + var _la int + + p.EnterOuterAlt(localctx, 1) + p.SetState(32) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + if _la == MatchParserSTRING { + { + p.SetState(31) + p.Value() + } + + } + p.SetState(40) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + for _la == MatchParserCOMMA { + { + p.SetState(34) + p.Match(MatchParserCOMMA) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + p.SetState(36) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + if _la == MatchParserSTRING { + { + p.SetState(35) + p.Value() + } + + } + + p.SetState(42) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} + +// IValueContext is an interface to support dynamic dispatch. +type IValueContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + + // Getter signatures + STRING() antlr.TerminalNode + + // IsValueContext differentiates from other interfaces. + IsValueContext() +} + +type ValueContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptyValueContext() *ValueContext { + var p = new(ValueContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = MatchParserRULE_value + return p +} + +func InitEmptyValueContext(p *ValueContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = MatchParserRULE_value +} + +func (*ValueContext) IsValueContext() {} + +func NewValueContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *ValueContext { + var p = new(ValueContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = MatchParserRULE_value + + return p +} + +func (s *ValueContext) GetParser() antlr.Parser { return s.parser } + +func (s *ValueContext) STRING() antlr.TerminalNode { + return s.GetToken(MatchParserSTRING, 0) +} + +func (s *ValueContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *ValueContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +func (s *ValueContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(MatchListener); ok { + listenerT.EnterValue(s) + } +} + +func (s *ValueContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(MatchListener); ok { + listenerT.ExitValue(s) + } +} + +func (p *MatchParser) Value() (localctx IValueContext) { + localctx = NewValueContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 8, MatchParserRULE_value) + p.EnterOuterAlt(localctx, 1) + { + p.SetState(43) + p.Match(MatchParserSTRING) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} diff --git a/handlers/sshd_config/fields/match-parser/parser_test.go b/handlers/sshd_config/fields/match-parser/parser_test.go new file mode 100644 index 0000000..df9395c --- /dev/null +++ b/handlers/sshd_config/fields/match-parser/parser_test.go @@ -0,0 +1,79 @@ +package match_parser + +import ( + "testing" +) + +func TestComplexExample( + t *testing.T, +) { + input := "User root,admin,alice Address *,!192.168.0.1" + + match := NewMatch() + errors := match.Parse(input, 32) + + if len(errors) > 0 { + t.Fatalf("Expected no errors, but got %v", errors) + } + + if !(len(match.Entries) == 2) { + t.Fatalf("Expected 2 entries, but got %v", len(match.Entries)) + } + + if !(match.Entries[0].Criteria == MatchCriteriaTypeUser) { + t.Fatalf("Expected User, but got %v", match.Entries[0]) + } + + if !(match.Entries[0].Values[0].Value == "root") { + t.Fatalf("Expected root, but got %v", match.Entries[0].Values[0]) + } + + if !(match.Entries[0].Values[1].Value == "admin") { + t.Fatalf("Expected admin, but got %v", match.Entries[0].Values[1]) + } + + if !(match.Entries[0].Values[2].Value == "alice") { + t.Fatalf("Expected alice, but got %v", match.Entries[0].Values[2]) + } + + if !(match.Entries[1].Criteria == MatchCriteriaTypeAddress) { + t.Fatalf("Expected Address, but got %v", match.Entries[1]) + } + + if !(match.Entries[1].Values[0].Value == "*") { + t.Fatalf("Expected *, but got %v", match.Entries[1].Values[0]) + } + + if !(match.Entries[1].Values[1].Value == "!192.168.0.1") { + t.Fatalf("Expected !192.168.0.1, but got %v", match.Entries[1].Values[1]) + } +} + +func TestSecondComplexExample( + t *testing.T, +) { + input := "Address 172.22.100.0/24,172.22.5.0/24,127.0.0.1" + + match := NewMatch() + errors := match.Parse(input, 0) + + if len(errors) > 0 { + t.Fatalf("Expected no errors, but got %v", errors) + } + + if !(len(match.Entries) == 1) { + t.Fatalf("Expected 1 entries, but got %v", len(match.Entries)) + } + + if !(match.Entries[0].Criteria == MatchCriteriaTypeAddress) { + t.Fatalf("Expected Address, but got %v", match.Entries[0]) + } + + if !(len(match.Entries[0].Values) == 3) { + t.Fatalf("Expected 3 values, but got %v", len(match.Entries[0].Values)) + } + + if !(match.Entries[0].Values[0].Value == "172.22.100.0/24") { + t.Fatalf("Expected 172.22.100.0/24, but got %v", match.Entries[0].Values[0]) + } +} From 8118cf8092bd51849ca7f5157dc047e750f84dfc Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Sat, 14 Sep 2024 22:24:34 +0200 Subject: [PATCH 033/133] fix(sshd_config): Fix tests --- handlers/sshd_config/indexes/indexes_test.go | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/handlers/sshd_config/indexes/indexes_test.go b/handlers/sshd_config/indexes/indexes_test.go index 7271dc6..9d69b92 100644 --- a/handlers/sshd_config/indexes/indexes_test.go +++ b/handlers/sshd_config/indexes/indexes_test.go @@ -107,12 +107,12 @@ Match Address 192.168.0.1/24 indexes.AllOptionsPerName["PermitRootLogin"][0].Option.Value == "PermitRootLogin yes" && indexes.AllOptionsPerName["PermitRootLogin"][0].Option.Start.Line == 0 && indexes.AllOptionsPerName["PermitRootLogin"][0].MatchBlock == nil && - indexes.AllOptionsPerName["PermitRootLogin"][1].Option.Value == "\tPermitRootLogin no" && - indexes.AllOptionsPerName["PermitRootLogin"][1].Option.Start.Line == 6 && - indexes.AllOptionsPerName["PermitRootLogin"][1].MatchBlock == firstMatchBlock && - indexes.AllOptionsPerName["PermitRootLogin"][2].Option.Value == "\tPermitRootLogin yes" && - indexes.AllOptionsPerName["PermitRootLogin"][2].Option.Start.Line == 8 && - indexes.AllOptionsPerName["PermitRootLogin"][2].MatchBlock == firstMatchBlock) { + indexes.AllOptionsPerName["PermitRootLogin"][6].Option.Value == "\tPermitRootLogin no" && + indexes.AllOptionsPerName["PermitRootLogin"][6].Option.Start.Line == 6 && + indexes.AllOptionsPerName["PermitRootLogin"][6].MatchBlock == firstMatchBlock && + indexes.AllOptionsPerName["PermitRootLogin"][8].Option.Value == "\tPermitRootLogin yes" && + indexes.AllOptionsPerName["PermitRootLogin"][8].Option.Start.Line == 8 && + indexes.AllOptionsPerName["PermitRootLogin"][8].MatchBlock == firstMatchBlock) { t.Errorf("Expected 3 PermitRootLogin options, but got %v", indexes.AllOptionsPerName["PermitRootLogin"]) } } From 6911511b51721ea2eef69f75dda4057c2c847ace Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Sat, 14 Sep 2024 22:37:56 +0200 Subject: [PATCH 034/133] feat(sshd_config): Parse match blocks inside the sshd_config parser --- handlers/sshd_config/ast/listener.go | 38 ++++++++++++++++++------- handlers/sshd_config/ast/parser_test.go | 34 +++++++++++++++------- handlers/sshd_config/ast/sshd_config.go | 2 ++ 3 files changed, 52 insertions(+), 22 deletions(-) diff --git a/handlers/sshd_config/ast/listener.go b/handlers/sshd_config/ast/listener.go index 2b3583c..be9b529 100644 --- a/handlers/sshd_config/ast/listener.go +++ b/handlers/sshd_config/ast/listener.go @@ -3,9 +3,11 @@ package ast import ( "config-lsp/common" "config-lsp/handlers/sshd_config/ast/parser" + match_parser "config-lsp/handlers/sshd_config/fields/match-parser" + "strings" + "github.com/emirpasic/gods/maps/treemap" gods "github.com/emirpasic/gods/utils" - "strings" ) type sshListenerContext struct { @@ -93,17 +95,31 @@ func (s *sshParserListener) ExitEntry(ctx *parser.EntryContext) { if s.sshContext.isKeyAMatchBlock { // Add new match block - matchBlock := &SSHMatchBlock{ - LocationRange: location, - MatchEntry: s.sshContext.currentOption, - Options: treemap.NewWith(gods.UInt32Comparator), - } - s.Config.Options.Put( - location.Start.Line, - matchBlock, - ) + match := match_parser.NewMatch() + errors := match.Parse(s.sshContext.currentOption.OptionValue.Value, location.Start.Line) + + if len(errors) > 0 { + for _, err := range errors { + s.Errors = append(s.Errors, common.LSPError{ + Range: err.Range.ShiftHorizontal(s.sshContext.currentOption.Start.Character), + Err: err.Err, + }) + } + } else { + matchBlock := &SSHMatchBlock{ + LocationRange: location, + MatchEntry: s.sshContext.currentOption, + MatchValue: match, + Options: treemap.NewWith(gods.UInt32Comparator), + } + s.Config.Options.Put( + location.Start.Line, + matchBlock, + ) + + s.sshContext.currentMatchBlock = matchBlock + } - s.sshContext.currentMatchBlock = matchBlock s.sshContext.isKeyAMatchBlock = false } else if s.sshContext.currentMatchBlock != nil { s.sshContext.currentMatchBlock.Options.Put( diff --git a/handlers/sshd_config/ast/parser_test.go b/handlers/sshd_config/ast/parser_test.go index 5077ac6..0061807 100644 --- a/handlers/sshd_config/ast/parser_test.go +++ b/handlers/sshd_config/ast/parser_test.go @@ -65,7 +65,7 @@ func TestMatchSimpleBlock( input := utils.Dedent(` PermitRootLogin no -Match 192.168.0.1 +Match Address 192.168.0.1 PasswordAuthentication yes `) p := NewSSHConfig() @@ -88,8 +88,12 @@ Match 192.168.0.1 rawSecondEntry, _ := p.Options.Get(uint32(2)) secondEntry := rawSecondEntry.(*SSHMatchBlock) - if !(secondEntry.MatchEntry.Value == "Match 192.168.0.1") { - t.Errorf("Expected second entry to be 'Match 192.168.0.1', but got: %v", secondEntry.MatchEntry.Value) + if !(secondEntry.MatchEntry.Value == "Match Address 192.168.0.1") { + t.Errorf("Expected second entry to be 'Match Address 192.168.0.1', but got: %v", secondEntry.MatchEntry.Value) + } + + if !(secondEntry.MatchValue.Entries[0].Criteria == "Address" && secondEntry.MatchValue.Entries[0].Values[0].Value == "192.168.0.1") { + t.Errorf("Expected second entry to be 'Match Address 192.168.0.1', but got: %v", secondEntry.MatchValue) } if !(secondEntry.Options.Size() == 1) { @@ -109,11 +113,11 @@ func TestMultipleMatchBlocks( input := utils.Dedent(` PermitRootLogin no -Match 192.168.0.1 +Match User lena PasswordAuthentication yes AllowUsers root user -Match 192.168.0.2 +Match Address 192.168.0.2 MaxAuthTries 3 `) p := NewSSHConfig() @@ -159,18 +163,18 @@ Match 192.168.0.2 } firstOption, firstMatchBlock := p.FindOption(uint32(3)) - if !(firstOption.Key.Value == "PasswordAuthentication" && firstOption.OptionValue.Value == "yes" && firstMatchBlock.MatchEntry.Value == "Match 192.168.0.1") { - t.Errorf("Expected first option to be 'PasswordAuthentication yes' and first match block to be 'Match 192.168.0.1', but got: %v, %v", firstOption, firstMatchBlock) + if !(firstOption.Key.Value == "PasswordAuthentication" && firstOption.OptionValue.Value == "yes") { + t.Errorf("Expected first option to be 'PasswordAuthentication yes' and first match block to be 'Match Address 192.168.0.1', but got: %v, %v", firstOption, firstMatchBlock) } emptyOption, matchBlock := p.FindOption(uint32(5)) - if !(emptyOption == nil && matchBlock.MatchEntry.Value == "Match 192.168.0.1") { - t.Errorf("Expected empty option and match block to be 'Match 192.168.0.1', but got: %v, %v", emptyOption, matchBlock) + if !(emptyOption == nil && matchBlock.MatchEntry.Value == "Match User lena" && matchBlock.MatchValue.Entries[0].Values[0].Value == "lena") { + t.Errorf("Expected empty option and match block to be 'Match User lena', but got: %v, %v", emptyOption, matchBlock) } matchOption, matchBlock := p.FindOption(uint32(2)) - if !(matchOption.Value == "Match 192.168.0.1" && matchBlock.MatchEntry.Value == "Match 192.168.0.1") { - t.Errorf("Expected match option to be 'Match 192.160.0.1' and match block to be 'Match 192.168.0.1', but got: %v, %v", matchOption, matchBlock) + if !(matchOption.Value == "Match User lena" && matchBlock.MatchEntry.Value == "Match User lena" && matchBlock.MatchValue.Entries[0].Values[0].Value == "lena") { + t.Errorf("Expected match option to be 'Match User lena', but got: %v, %v", matchOption, matchBlock) } } @@ -412,6 +416,10 @@ Match Address 172.22.100.0/24,172.22.5.0/24,127.0.0.1 t.Errorf("Expected fourth entry to be 'Match User anoncvs', but got: %v", fourthEntry.MatchEntry.Value) } + if !(fourthEntry.MatchValue.Entries[0].Criteria == "User" && fourthEntry.MatchValue.Entries[0].Values[0].Value == "anoncvs") { + t.Errorf("Expected fourth entry to be 'Match User anoncvs', but got: %v", fourthEntry.MatchValue) + } + if !(fourthEntry.Options.Size() == 3) { t.Errorf("Expected 3 options in fourth match block, but got: %v", fourthEntry.Options) } @@ -432,6 +440,10 @@ Match Address 172.22.100.0/24,172.22.5.0/24,127.0.0.1 t.Errorf("Expected sixth entry to be 'Match Address 172.22.100.0/24,172.22.5.0/24,127.0.0.1', but got: %v", sixthEntry.MatchEntry.Value) } + if !(sixthEntry.MatchValue.Entries[0].Criteria == "Address" && len(sixthEntry.MatchValue.Entries[0].Values) == 3) { + t.Errorf("Expected sixth entry to contain 3 values, but got: %v", sixthEntry.MatchValue) + } + if !(sixthEntry.Options.Size() == 2) { t.Errorf("Expected 2 options in sixth match block, but got: %v", sixthEntry.Options) } diff --git a/handlers/sshd_config/ast/sshd_config.go b/handlers/sshd_config/ast/sshd_config.go index f28c5d6..b448f63 100644 --- a/handlers/sshd_config/ast/sshd_config.go +++ b/handlers/sshd_config/ast/sshd_config.go @@ -2,6 +2,7 @@ package ast import ( "config-lsp/common" + match_parser "config-lsp/handlers/sshd_config/fields/match-parser" "github.com/emirpasic/gods/maps/treemap" ) @@ -52,6 +53,7 @@ func (o SSHOption) GetOption() SSHOption { type SSHMatchBlock struct { common.LocationRange MatchEntry *SSHOption + MatchValue *match_parser.Match // [uint32]*SSHOption -> line number -> *SSHOption Options *treemap.Map From 9b1a5af2d017bafe469ecdbc30358bef1600415f Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Sun, 15 Sep 2024 15:33:54 +0200 Subject: [PATCH 035/133] feat(sshd_config): Add match completions; Bugfixes --- handlers/sshd_config/Config.g4 | 4 +- handlers/sshd_config/ast/listener.go | 48 ++-- handlers/sshd_config/ast/parser/Config.interp | 2 +- .../sshd_config/ast/parser/config_parser.go | 234 +++++++-------- handlers/sshd_config/ast/parser_test.go | 69 ++++- handlers/sshd_config/ast/sshd_config.go | 65 ----- .../sshd_config/ast/sshd_config_fields.go | 66 +++++ handlers/sshd_config/fields/fields.go | 22 +- .../sshd_config/fields/match-parser/Match.g4 | 18 +- .../fields/match-parser/listener.go | 44 ++- .../fields/match-parser/match_ast.go | 15 +- .../fields/match-parser/match_fields.go | 67 +++++ .../sshd_config/fields/match-parser/parser.go | 3 +- .../fields/match-parser/parser/Match.interp | 3 +- .../parser/match_base_listener.go | 6 + .../match-parser/parser/match_listener.go | 6 + .../match-parser/parser/match_parser.go | 266 +++++++++++++----- .../fields/match-parser/parser_test.go | 95 +++++-- handlers/sshd_config/fields/match.go | 14 + handlers/sshd_config/handlers/completions.go | 16 +- .../sshd_config/handlers/completions_match.go | 111 ++++++++ .../lsp/text-document-completion.go | 7 +- 22 files changed, 825 insertions(+), 356 deletions(-) create mode 100644 handlers/sshd_config/ast/sshd_config_fields.go create mode 100644 handlers/sshd_config/fields/match-parser/match_fields.go create mode 100644 handlers/sshd_config/handlers/completions_match.go diff --git a/handlers/sshd_config/Config.g4 b/handlers/sshd_config/Config.g4 index 376950e..569a6a8 100644 --- a/handlers/sshd_config/Config.g4 +++ b/handlers/sshd_config/Config.g4 @@ -1,7 +1,7 @@ grammar Config; lineStatement - : (entry | (WHITESPACE? leadingComment) | WHITESPACE?) EOF + : (entry | (leadingComment) | WHITESPACE?) EOF ; entry @@ -17,7 +17,7 @@ key ; value - : (STRING WHITESPACE)? STRING WHITESPACE? + : (STRING WHITESPACE)* STRING? WHITESPACE? ; leadingComment diff --git a/handlers/sshd_config/ast/listener.go b/handlers/sshd_config/ast/listener.go index be9b529..b5c81b2 100644 --- a/handlers/sshd_config/ast/listener.go +++ b/handlers/sshd_config/ast/listener.go @@ -95,31 +95,41 @@ func (s *sshParserListener) ExitEntry(ctx *parser.EntryContext) { if s.sshContext.isKeyAMatchBlock { // Add new match block - match := match_parser.NewMatch() - errors := match.Parse(s.sshContext.currentOption.OptionValue.Value, location.Start.Line) + var match *match_parser.Match - if len(errors) > 0 { - for _, err := range errors { - s.Errors = append(s.Errors, common.LSPError{ - Range: err.Range.ShiftHorizontal(s.sshContext.currentOption.Start.Character), - Err: err.Err, - }) - } - } else { - matchBlock := &SSHMatchBlock{ - LocationRange: location, - MatchEntry: s.sshContext.currentOption, - MatchValue: match, - Options: treemap.NewWith(gods.UInt32Comparator), - } - s.Config.Options.Put( + if s.sshContext.currentOption.OptionValue != nil { + matchParser := match_parser.NewMatch() + errors := matchParser.Parse( + s.sshContext.currentOption.OptionValue.Value, location.Start.Line, - matchBlock, + s.sshContext.currentOption.OptionValue.Start.Character, ) - s.sshContext.currentMatchBlock = matchBlock + if len(errors) > 0 { + for _, err := range errors { + s.Errors = append(s.Errors, common.LSPError{ + Range: err.Range.ShiftHorizontal(s.sshContext.currentOption.Start.Character), + Err: err.Err, + }) + } + } else { + match = matchParser + } } + matchBlock := &SSHMatchBlock{ + LocationRange: location, + MatchEntry: s.sshContext.currentOption, + MatchValue: match, + Options: treemap.NewWith(gods.UInt32Comparator), + } + s.Config.Options.Put( + location.Start.Line, + matchBlock, + ) + + s.sshContext.currentMatchBlock = matchBlock + s.sshContext.isKeyAMatchBlock = false } else if s.sshContext.currentMatchBlock != nil { s.sshContext.currentMatchBlock.Options.Put( diff --git a/handlers/sshd_config/ast/parser/Config.interp b/handlers/sshd_config/ast/parser/Config.interp index b286373..2832f42 100644 --- a/handlers/sshd_config/ast/parser/Config.interp +++ b/handlers/sshd_config/ast/parser/Config.interp @@ -22,4 +22,4 @@ leadingComment atn: -[4, 1, 4, 64, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 2, 5, 7, 5, 1, 0, 1, 0, 3, 0, 15, 8, 0, 1, 0, 1, 0, 3, 0, 19, 8, 0, 3, 0, 21, 8, 0, 1, 0, 1, 0, 1, 1, 3, 1, 26, 8, 1, 1, 1, 3, 1, 29, 8, 1, 1, 1, 3, 1, 32, 8, 1, 1, 1, 3, 1, 35, 8, 1, 1, 1, 3, 1, 38, 8, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, 1, 4, 3, 4, 46, 8, 4, 1, 4, 1, 4, 3, 4, 50, 8, 4, 1, 5, 1, 5, 3, 5, 54, 8, 5, 1, 5, 1, 5, 3, 5, 58, 8, 5, 4, 5, 60, 8, 5, 11, 5, 12, 5, 61, 1, 5, 0, 0, 6, 0, 2, 4, 6, 8, 10, 0, 0, 71, 0, 20, 1, 0, 0, 0, 2, 25, 1, 0, 0, 0, 4, 39, 1, 0, 0, 0, 6, 41, 1, 0, 0, 0, 8, 45, 1, 0, 0, 0, 10, 51, 1, 0, 0, 0, 12, 21, 3, 2, 1, 0, 13, 15, 5, 2, 0, 0, 14, 13, 1, 0, 0, 0, 14, 15, 1, 0, 0, 0, 15, 16, 1, 0, 0, 0, 16, 21, 3, 10, 5, 0, 17, 19, 5, 2, 0, 0, 18, 17, 1, 0, 0, 0, 18, 19, 1, 0, 0, 0, 19, 21, 1, 0, 0, 0, 20, 12, 1, 0, 0, 0, 20, 14, 1, 0, 0, 0, 20, 18, 1, 0, 0, 0, 21, 22, 1, 0, 0, 0, 22, 23, 5, 0, 0, 1, 23, 1, 1, 0, 0, 0, 24, 26, 5, 2, 0, 0, 25, 24, 1, 0, 0, 0, 25, 26, 1, 0, 0, 0, 26, 28, 1, 0, 0, 0, 27, 29, 3, 6, 3, 0, 28, 27, 1, 0, 0, 0, 28, 29, 1, 0, 0, 0, 29, 31, 1, 0, 0, 0, 30, 32, 3, 4, 2, 0, 31, 30, 1, 0, 0, 0, 31, 32, 1, 0, 0, 0, 32, 34, 1, 0, 0, 0, 33, 35, 3, 8, 4, 0, 34, 33, 1, 0, 0, 0, 34, 35, 1, 0, 0, 0, 35, 37, 1, 0, 0, 0, 36, 38, 3, 10, 5, 0, 37, 36, 1, 0, 0, 0, 37, 38, 1, 0, 0, 0, 38, 3, 1, 0, 0, 0, 39, 40, 5, 2, 0, 0, 40, 5, 1, 0, 0, 0, 41, 42, 5, 3, 0, 0, 42, 7, 1, 0, 0, 0, 43, 44, 5, 3, 0, 0, 44, 46, 5, 2, 0, 0, 45, 43, 1, 0, 0, 0, 45, 46, 1, 0, 0, 0, 46, 47, 1, 0, 0, 0, 47, 49, 5, 3, 0, 0, 48, 50, 5, 2, 0, 0, 49, 48, 1, 0, 0, 0, 49, 50, 1, 0, 0, 0, 50, 9, 1, 0, 0, 0, 51, 53, 5, 1, 0, 0, 52, 54, 5, 2, 0, 0, 53, 52, 1, 0, 0, 0, 53, 54, 1, 0, 0, 0, 54, 59, 1, 0, 0, 0, 55, 57, 5, 3, 0, 0, 56, 58, 5, 2, 0, 0, 57, 56, 1, 0, 0, 0, 57, 58, 1, 0, 0, 0, 58, 60, 1, 0, 0, 0, 59, 55, 1, 0, 0, 0, 60, 61, 1, 0, 0, 0, 61, 59, 1, 0, 0, 0, 61, 62, 1, 0, 0, 0, 62, 11, 1, 0, 0, 0, 13, 14, 18, 20, 25, 28, 31, 34, 37, 45, 49, 53, 57, 61] \ No newline at end of file +[4, 1, 4, 66, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 2, 5, 7, 5, 1, 0, 1, 0, 1, 0, 3, 0, 16, 8, 0, 3, 0, 18, 8, 0, 1, 0, 1, 0, 1, 1, 3, 1, 23, 8, 1, 1, 1, 3, 1, 26, 8, 1, 1, 1, 3, 1, 29, 8, 1, 1, 1, 3, 1, 32, 8, 1, 1, 1, 3, 1, 35, 8, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, 1, 4, 5, 4, 43, 8, 4, 10, 4, 12, 4, 46, 9, 4, 1, 4, 3, 4, 49, 8, 4, 1, 4, 3, 4, 52, 8, 4, 1, 5, 1, 5, 3, 5, 56, 8, 5, 1, 5, 1, 5, 3, 5, 60, 8, 5, 4, 5, 62, 8, 5, 11, 5, 12, 5, 63, 1, 5, 0, 0, 6, 0, 2, 4, 6, 8, 10, 0, 0, 73, 0, 17, 1, 0, 0, 0, 2, 22, 1, 0, 0, 0, 4, 36, 1, 0, 0, 0, 6, 38, 1, 0, 0, 0, 8, 44, 1, 0, 0, 0, 10, 53, 1, 0, 0, 0, 12, 18, 3, 2, 1, 0, 13, 18, 3, 10, 5, 0, 14, 16, 5, 2, 0, 0, 15, 14, 1, 0, 0, 0, 15, 16, 1, 0, 0, 0, 16, 18, 1, 0, 0, 0, 17, 12, 1, 0, 0, 0, 17, 13, 1, 0, 0, 0, 17, 15, 1, 0, 0, 0, 18, 19, 1, 0, 0, 0, 19, 20, 5, 0, 0, 1, 20, 1, 1, 0, 0, 0, 21, 23, 5, 2, 0, 0, 22, 21, 1, 0, 0, 0, 22, 23, 1, 0, 0, 0, 23, 25, 1, 0, 0, 0, 24, 26, 3, 6, 3, 0, 25, 24, 1, 0, 0, 0, 25, 26, 1, 0, 0, 0, 26, 28, 1, 0, 0, 0, 27, 29, 3, 4, 2, 0, 28, 27, 1, 0, 0, 0, 28, 29, 1, 0, 0, 0, 29, 31, 1, 0, 0, 0, 30, 32, 3, 8, 4, 0, 31, 30, 1, 0, 0, 0, 31, 32, 1, 0, 0, 0, 32, 34, 1, 0, 0, 0, 33, 35, 3, 10, 5, 0, 34, 33, 1, 0, 0, 0, 34, 35, 1, 0, 0, 0, 35, 3, 1, 0, 0, 0, 36, 37, 5, 2, 0, 0, 37, 5, 1, 0, 0, 0, 38, 39, 5, 3, 0, 0, 39, 7, 1, 0, 0, 0, 40, 41, 5, 3, 0, 0, 41, 43, 5, 2, 0, 0, 42, 40, 1, 0, 0, 0, 43, 46, 1, 0, 0, 0, 44, 42, 1, 0, 0, 0, 44, 45, 1, 0, 0, 0, 45, 48, 1, 0, 0, 0, 46, 44, 1, 0, 0, 0, 47, 49, 5, 3, 0, 0, 48, 47, 1, 0, 0, 0, 48, 49, 1, 0, 0, 0, 49, 51, 1, 0, 0, 0, 50, 52, 5, 2, 0, 0, 51, 50, 1, 0, 0, 0, 51, 52, 1, 0, 0, 0, 52, 9, 1, 0, 0, 0, 53, 55, 5, 1, 0, 0, 54, 56, 5, 2, 0, 0, 55, 54, 1, 0, 0, 0, 55, 56, 1, 0, 0, 0, 56, 61, 1, 0, 0, 0, 57, 59, 5, 3, 0, 0, 58, 60, 5, 2, 0, 0, 59, 58, 1, 0, 0, 0, 59, 60, 1, 0, 0, 0, 60, 62, 1, 0, 0, 0, 61, 57, 1, 0, 0, 0, 62, 63, 1, 0, 0, 0, 63, 61, 1, 0, 0, 0, 63, 64, 1, 0, 0, 0, 64, 11, 1, 0, 0, 0, 13, 15, 17, 22, 25, 28, 31, 34, 44, 48, 51, 55, 59, 63] \ No newline at end of file diff --git a/handlers/sshd_config/ast/parser/config_parser.go b/handlers/sshd_config/ast/parser/config_parser.go index 79e7cfd..018bbb8 100644 --- a/handlers/sshd_config/ast/parser/config_parser.go +++ b/handlers/sshd_config/ast/parser/config_parser.go @@ -43,34 +43,35 @@ func configParserInit() { } staticData.PredictionContextCache = antlr.NewPredictionContextCache() staticData.serializedATN = []int32{ - 4, 1, 4, 64, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, - 2, 5, 7, 5, 1, 0, 1, 0, 3, 0, 15, 8, 0, 1, 0, 1, 0, 3, 0, 19, 8, 0, 3, - 0, 21, 8, 0, 1, 0, 1, 0, 1, 1, 3, 1, 26, 8, 1, 1, 1, 3, 1, 29, 8, 1, 1, - 1, 3, 1, 32, 8, 1, 1, 1, 3, 1, 35, 8, 1, 1, 1, 3, 1, 38, 8, 1, 1, 2, 1, - 2, 1, 3, 1, 3, 1, 4, 1, 4, 3, 4, 46, 8, 4, 1, 4, 1, 4, 3, 4, 50, 8, 4, - 1, 5, 1, 5, 3, 5, 54, 8, 5, 1, 5, 1, 5, 3, 5, 58, 8, 5, 4, 5, 60, 8, 5, - 11, 5, 12, 5, 61, 1, 5, 0, 0, 6, 0, 2, 4, 6, 8, 10, 0, 0, 71, 0, 20, 1, - 0, 0, 0, 2, 25, 1, 0, 0, 0, 4, 39, 1, 0, 0, 0, 6, 41, 1, 0, 0, 0, 8, 45, - 1, 0, 0, 0, 10, 51, 1, 0, 0, 0, 12, 21, 3, 2, 1, 0, 13, 15, 5, 2, 0, 0, - 14, 13, 1, 0, 0, 0, 14, 15, 1, 0, 0, 0, 15, 16, 1, 0, 0, 0, 16, 21, 3, - 10, 5, 0, 17, 19, 5, 2, 0, 0, 18, 17, 1, 0, 0, 0, 18, 19, 1, 0, 0, 0, 19, - 21, 1, 0, 0, 0, 20, 12, 1, 0, 0, 0, 20, 14, 1, 0, 0, 0, 20, 18, 1, 0, 0, - 0, 21, 22, 1, 0, 0, 0, 22, 23, 5, 0, 0, 1, 23, 1, 1, 0, 0, 0, 24, 26, 5, - 2, 0, 0, 25, 24, 1, 0, 0, 0, 25, 26, 1, 0, 0, 0, 26, 28, 1, 0, 0, 0, 27, - 29, 3, 6, 3, 0, 28, 27, 1, 0, 0, 0, 28, 29, 1, 0, 0, 0, 29, 31, 1, 0, 0, - 0, 30, 32, 3, 4, 2, 0, 31, 30, 1, 0, 0, 0, 31, 32, 1, 0, 0, 0, 32, 34, - 1, 0, 0, 0, 33, 35, 3, 8, 4, 0, 34, 33, 1, 0, 0, 0, 34, 35, 1, 0, 0, 0, - 35, 37, 1, 0, 0, 0, 36, 38, 3, 10, 5, 0, 37, 36, 1, 0, 0, 0, 37, 38, 1, - 0, 0, 0, 38, 3, 1, 0, 0, 0, 39, 40, 5, 2, 0, 0, 40, 5, 1, 0, 0, 0, 41, - 42, 5, 3, 0, 0, 42, 7, 1, 0, 0, 0, 43, 44, 5, 3, 0, 0, 44, 46, 5, 2, 0, - 0, 45, 43, 1, 0, 0, 0, 45, 46, 1, 0, 0, 0, 46, 47, 1, 0, 0, 0, 47, 49, - 5, 3, 0, 0, 48, 50, 5, 2, 0, 0, 49, 48, 1, 0, 0, 0, 49, 50, 1, 0, 0, 0, - 50, 9, 1, 0, 0, 0, 51, 53, 5, 1, 0, 0, 52, 54, 5, 2, 0, 0, 53, 52, 1, 0, - 0, 0, 53, 54, 1, 0, 0, 0, 54, 59, 1, 0, 0, 0, 55, 57, 5, 3, 0, 0, 56, 58, - 5, 2, 0, 0, 57, 56, 1, 0, 0, 0, 57, 58, 1, 0, 0, 0, 58, 60, 1, 0, 0, 0, - 59, 55, 1, 0, 0, 0, 60, 61, 1, 0, 0, 0, 61, 59, 1, 0, 0, 0, 61, 62, 1, - 0, 0, 0, 62, 11, 1, 0, 0, 0, 13, 14, 18, 20, 25, 28, 31, 34, 37, 45, 49, - 53, 57, 61, + 4, 1, 4, 66, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, + 2, 5, 7, 5, 1, 0, 1, 0, 1, 0, 3, 0, 16, 8, 0, 3, 0, 18, 8, 0, 1, 0, 1, + 0, 1, 1, 3, 1, 23, 8, 1, 1, 1, 3, 1, 26, 8, 1, 1, 1, 3, 1, 29, 8, 1, 1, + 1, 3, 1, 32, 8, 1, 1, 1, 3, 1, 35, 8, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, + 1, 4, 5, 4, 43, 8, 4, 10, 4, 12, 4, 46, 9, 4, 1, 4, 3, 4, 49, 8, 4, 1, + 4, 3, 4, 52, 8, 4, 1, 5, 1, 5, 3, 5, 56, 8, 5, 1, 5, 1, 5, 3, 5, 60, 8, + 5, 4, 5, 62, 8, 5, 11, 5, 12, 5, 63, 1, 5, 0, 0, 6, 0, 2, 4, 6, 8, 10, + 0, 0, 73, 0, 17, 1, 0, 0, 0, 2, 22, 1, 0, 0, 0, 4, 36, 1, 0, 0, 0, 6, 38, + 1, 0, 0, 0, 8, 44, 1, 0, 0, 0, 10, 53, 1, 0, 0, 0, 12, 18, 3, 2, 1, 0, + 13, 18, 3, 10, 5, 0, 14, 16, 5, 2, 0, 0, 15, 14, 1, 0, 0, 0, 15, 16, 1, + 0, 0, 0, 16, 18, 1, 0, 0, 0, 17, 12, 1, 0, 0, 0, 17, 13, 1, 0, 0, 0, 17, + 15, 1, 0, 0, 0, 18, 19, 1, 0, 0, 0, 19, 20, 5, 0, 0, 1, 20, 1, 1, 0, 0, + 0, 21, 23, 5, 2, 0, 0, 22, 21, 1, 0, 0, 0, 22, 23, 1, 0, 0, 0, 23, 25, + 1, 0, 0, 0, 24, 26, 3, 6, 3, 0, 25, 24, 1, 0, 0, 0, 25, 26, 1, 0, 0, 0, + 26, 28, 1, 0, 0, 0, 27, 29, 3, 4, 2, 0, 28, 27, 1, 0, 0, 0, 28, 29, 1, + 0, 0, 0, 29, 31, 1, 0, 0, 0, 30, 32, 3, 8, 4, 0, 31, 30, 1, 0, 0, 0, 31, + 32, 1, 0, 0, 0, 32, 34, 1, 0, 0, 0, 33, 35, 3, 10, 5, 0, 34, 33, 1, 0, + 0, 0, 34, 35, 1, 0, 0, 0, 35, 3, 1, 0, 0, 0, 36, 37, 5, 2, 0, 0, 37, 5, + 1, 0, 0, 0, 38, 39, 5, 3, 0, 0, 39, 7, 1, 0, 0, 0, 40, 41, 5, 3, 0, 0, + 41, 43, 5, 2, 0, 0, 42, 40, 1, 0, 0, 0, 43, 46, 1, 0, 0, 0, 44, 42, 1, + 0, 0, 0, 44, 45, 1, 0, 0, 0, 45, 48, 1, 0, 0, 0, 46, 44, 1, 0, 0, 0, 47, + 49, 5, 3, 0, 0, 48, 47, 1, 0, 0, 0, 48, 49, 1, 0, 0, 0, 49, 51, 1, 0, 0, + 0, 50, 52, 5, 2, 0, 0, 51, 50, 1, 0, 0, 0, 51, 52, 1, 0, 0, 0, 52, 9, 1, + 0, 0, 0, 53, 55, 5, 1, 0, 0, 54, 56, 5, 2, 0, 0, 55, 54, 1, 0, 0, 0, 55, + 56, 1, 0, 0, 0, 56, 61, 1, 0, 0, 0, 57, 59, 5, 3, 0, 0, 58, 60, 5, 2, 0, + 0, 59, 58, 1, 0, 0, 0, 59, 60, 1, 0, 0, 0, 60, 62, 1, 0, 0, 0, 61, 57, + 1, 0, 0, 0, 62, 63, 1, 0, 0, 0, 63, 61, 1, 0, 0, 0, 63, 64, 1, 0, 0, 0, + 64, 11, 1, 0, 0, 0, 13, 15, 17, 22, 25, 28, 31, 34, 44, 48, 51, 55, 59, + 63, } deserializer := antlr.NewATNDeserializer(nil) staticData.atn = deserializer.Deserialize(staticData.serializedATN) @@ -240,13 +241,13 @@ func (p *ConfigParser) LineStatement() (localctx ILineStatementContext) { var _la int p.EnterOuterAlt(localctx, 1) - p.SetState(20) + p.SetState(17) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit } - switch p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 2, p.GetParserRuleContext()) { + switch p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 1, p.GetParserRuleContext()) { case 1: { p.SetState(12) @@ -254,31 +255,13 @@ func (p *ConfigParser) LineStatement() (localctx ILineStatementContext) { } case 2: - p.SetState(14) - p.GetErrorHandler().Sync(p) - if p.HasError() { - goto errorExit - } - _la = p.GetTokenStream().LA(1) - - if _la == ConfigParserWHITESPACE { - { - p.SetState(13) - p.Match(ConfigParserWHITESPACE) - if p.HasError() { - // Recognition error - abort rule - goto errorExit - } - } - - } { - p.SetState(16) + p.SetState(13) p.LeadingComment() } case 3: - p.SetState(18) + p.SetState(15) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -287,7 +270,7 @@ func (p *ConfigParser) LineStatement() (localctx ILineStatementContext) { if _la == ConfigParserWHITESPACE { { - p.SetState(17) + p.SetState(14) p.Match(ConfigParserWHITESPACE) if p.HasError() { // Recognition error - abort rule @@ -301,7 +284,7 @@ func (p *ConfigParser) LineStatement() (localctx ILineStatementContext) { goto errorExit } { - p.SetState(22) + p.SetState(19) p.Match(ConfigParserEOF) if p.HasError() { // Recognition error - abort rule @@ -466,17 +449,29 @@ func (p *ConfigParser) Entry() (localctx IEntryContext) { var _la int p.EnterOuterAlt(localctx, 1) + p.SetState(22) + p.GetErrorHandler().Sync(p) + + if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 2, p.GetParserRuleContext()) == 1 { + { + p.SetState(21) + p.Match(ConfigParserWHITESPACE) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + + } else if p.HasError() { // JIM + goto errorExit + } p.SetState(25) p.GetErrorHandler().Sync(p) if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 3, p.GetParserRuleContext()) == 1 { { p.SetState(24) - p.Match(ConfigParserWHITESPACE) - if p.HasError() { - // Recognition error - abort rule - goto errorExit - } + p.Key() } } else if p.HasError() { // JIM @@ -488,7 +483,7 @@ func (p *ConfigParser) Entry() (localctx IEntryContext) { if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 4, p.GetParserRuleContext()) == 1 { { p.SetState(27) - p.Key() + p.Separator() } } else if p.HasError() { // JIM @@ -496,17 +491,15 @@ func (p *ConfigParser) Entry() (localctx IEntryContext) { } p.SetState(31) p.GetErrorHandler().Sync(p) - if p.HasError() { - goto errorExit - } - _la = p.GetTokenStream().LA(1) - if _la == ConfigParserWHITESPACE { + if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 5, p.GetParserRuleContext()) == 1 { { p.SetState(30) - p.Separator() + p.Value() } + } else if p.HasError() { // JIM + goto errorExit } p.SetState(34) p.GetErrorHandler().Sync(p) @@ -515,23 +508,9 @@ func (p *ConfigParser) Entry() (localctx IEntryContext) { } _la = p.GetTokenStream().LA(1) - if _la == ConfigParserSTRING { - { - p.SetState(33) - p.Value() - } - - } - p.SetState(37) - p.GetErrorHandler().Sync(p) - if p.HasError() { - goto errorExit - } - _la = p.GetTokenStream().LA(1) - if _la == ConfigParserHASH { { - p.SetState(36) + p.SetState(33) p.LeadingComment() } @@ -625,7 +604,7 @@ func (p *ConfigParser) Separator() (localctx ISeparatorContext) { p.EnterRule(localctx, 4, ConfigParserRULE_separator) p.EnterOuterAlt(localctx, 1) { - p.SetState(39) + p.SetState(36) p.Match(ConfigParserWHITESPACE) if p.HasError() { // Recognition error - abort rule @@ -721,7 +700,7 @@ func (p *ConfigParser) Key() (localctx IKeyContext) { p.EnterRule(localctx, 6, ConfigParserRULE_key) p.EnterOuterAlt(localctx, 1) { - p.SetState(41) + p.SetState(38) p.Match(ConfigParserSTRING) if p.HasError() { // Recognition error - abort rule @@ -832,40 +811,67 @@ func (p *ConfigParser) Value() (localctx IValueContext) { p.EnterRule(localctx, 8, ConfigParserRULE_value) var _la int - p.EnterOuterAlt(localctx, 1) - p.SetState(45) - p.GetErrorHandler().Sync(p) + var _alt int - if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 8, p.GetParserRuleContext()) == 1 { + p.EnterOuterAlt(localctx, 1) + p.SetState(44) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _alt = p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 7, p.GetParserRuleContext()) + if p.HasError() { + goto errorExit + } + for _alt != 2 && _alt != antlr.ATNInvalidAltNumber { + if _alt == 1 { + { + p.SetState(40) + p.Match(ConfigParserSTRING) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + { + p.SetState(41) + p.Match(ConfigParserWHITESPACE) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + + } + p.SetState(46) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _alt = p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 7, p.GetParserRuleContext()) + if p.HasError() { + goto errorExit + } + } + p.SetState(48) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + if _la == ConfigParserSTRING { { - p.SetState(43) + p.SetState(47) p.Match(ConfigParserSTRING) if p.HasError() { // Recognition error - abort rule goto errorExit } } - { - p.SetState(44) - p.Match(ConfigParserWHITESPACE) - if p.HasError() { - // Recognition error - abort rule - goto errorExit - } - } - } else if p.HasError() { // JIM - goto errorExit } - { - p.SetState(47) - p.Match(ConfigParserSTRING) - if p.HasError() { - // Recognition error - abort rule - goto errorExit - } - } - p.SetState(49) + p.SetState(51) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -874,7 +880,7 @@ func (p *ConfigParser) Value() (localctx IValueContext) { if _la == ConfigParserWHITESPACE { { - p.SetState(48) + p.SetState(50) p.Match(ConfigParserWHITESPACE) if p.HasError() { // Recognition error - abort rule @@ -994,14 +1000,14 @@ func (p *ConfigParser) LeadingComment() (localctx ILeadingCommentContext) { p.EnterOuterAlt(localctx, 1) { - p.SetState(51) + p.SetState(53) p.Match(ConfigParserHASH) if p.HasError() { // Recognition error - abort rule goto errorExit } } - p.SetState(53) + p.SetState(55) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -1010,7 +1016,7 @@ func (p *ConfigParser) LeadingComment() (localctx ILeadingCommentContext) { if _la == ConfigParserWHITESPACE { { - p.SetState(52) + p.SetState(54) p.Match(ConfigParserWHITESPACE) if p.HasError() { // Recognition error - abort rule @@ -1019,7 +1025,7 @@ func (p *ConfigParser) LeadingComment() (localctx ILeadingCommentContext) { } } - p.SetState(59) + p.SetState(61) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -1028,14 +1034,14 @@ func (p *ConfigParser) LeadingComment() (localctx ILeadingCommentContext) { for ok := true; ok; ok = _la == ConfigParserSTRING { { - p.SetState(55) + p.SetState(57) p.Match(ConfigParserSTRING) if p.HasError() { // Recognition error - abort rule goto errorExit } } - p.SetState(57) + p.SetState(59) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -1044,7 +1050,7 @@ func (p *ConfigParser) LeadingComment() (localctx ILeadingCommentContext) { if _la == ConfigParserWHITESPACE { { - p.SetState(56) + p.SetState(58) p.Match(ConfigParserWHITESPACE) if p.HasError() { // Recognition error - abort rule @@ -1054,7 +1060,7 @@ func (p *ConfigParser) LeadingComment() (localctx ILeadingCommentContext) { } - p.SetState(61) + p.SetState(63) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit diff --git a/handlers/sshd_config/ast/parser_test.go b/handlers/sshd_config/ast/parser_test.go index 0061807..e883966 100644 --- a/handlers/sshd_config/ast/parser_test.go +++ b/handlers/sshd_config/ast/parser_test.go @@ -92,7 +92,7 @@ Match Address 192.168.0.1 t.Errorf("Expected second entry to be 'Match Address 192.168.0.1', but got: %v", secondEntry.MatchEntry.Value) } - if !(secondEntry.MatchValue.Entries[0].Criteria == "Address" && secondEntry.MatchValue.Entries[0].Values[0].Value == "192.168.0.1") { + if !(secondEntry.MatchValue.Entries[0].Criteria.Type == "Address" && secondEntry.MatchValue.Entries[0].Values.Values[0].Value == "192.168.0.1" && secondEntry.MatchEntry.OptionValue.Start.Character == 6) { t.Errorf("Expected second entry to be 'Match Address 192.168.0.1', but got: %v", secondEntry.MatchValue) } @@ -107,6 +107,65 @@ Match Address 192.168.0.1 } } +func TestMultipleEntriesInMatchBlock( + t *testing.T, +) { + input := utils.Dedent(` +Match User lena User root +`) + p := NewSSHConfig() + errors := p.Parse(input) + + if len(errors) != 0 { + t.Fatalf("Expected no errors, got %v", errors) + } + + _, matchBlock := p.FindOption(uint32(0)) + + if !(matchBlock.MatchEntry.Value == "Match User lena User root") { + t.Errorf("Expected match block to be 'Match User lena User root', but got: %v", matchBlock.MatchEntry.Value) + } + + if !(len(matchBlock.MatchValue.Entries) == 2) { + t.Errorf("Expected 2 entries in match block, but got: %v", matchBlock.MatchValue.Entries) + } + + if !(matchBlock.MatchValue.Entries[0].Criteria.Type == "User" && matchBlock.MatchValue.Entries[0].Values.Values[0].Value == "lena") { + t.Errorf("Expected first entry to be 'User lena', but got: %v", matchBlock.MatchValue.Entries[0]) + } + + if !(matchBlock.MatchValue.Entries[1].Criteria.Type == "User" && matchBlock.MatchValue.Entries[1].Values.Values[0].Value == "root") { + t.Errorf("Expected second entry to be 'User root', but got: %v", matchBlock.MatchValue.Entries[1]) + } +} + +func TestIncompleteMatchBlock( + t *testing.T, +) { + input := "Match User lena User " + + p := NewSSHConfig() + errors := p.Parse(input) + + if !(len(errors) == 0) { + t.Errorf("Expected 0 error, got %v", errors) + } + + _, matchBlock := p.FindOption(uint32(0)) + + if !(matchBlock.MatchEntry.Value == "Match User lena User ") { + t.Errorf("Expected match block to be 'Match User lena User ', but got: %v", matchBlock.MatchEntry.Value) + } + + if !(matchBlock.MatchValue.Entries[0].Criteria.Type == "User" && matchBlock.MatchValue.Entries[0].Values.Values[0].Value == "lena") { + t.Errorf("Expected first entry to be 'User lena', but got: %v", matchBlock.MatchValue.Entries[0]) + } + + if !(matchBlock.MatchValue.Entries[1].Value == "User " && matchBlock.MatchValue.Entries[1].Criteria.Type == "User" && matchBlock.MatchValue.Entries[1].Values == nil) { + t.Errorf("Expected second entry to be 'User ', but got: %v", matchBlock.MatchValue.Entries[1]) + } +} + func TestMultipleMatchBlocks( t *testing.T, ) { @@ -168,12 +227,12 @@ Match Address 192.168.0.2 } emptyOption, matchBlock := p.FindOption(uint32(5)) - if !(emptyOption == nil && matchBlock.MatchEntry.Value == "Match User lena" && matchBlock.MatchValue.Entries[0].Values[0].Value == "lena") { + if !(emptyOption == nil && matchBlock.MatchEntry.Value == "Match User lena" && matchBlock.MatchValue.Entries[0].Values.Values[0].Value == "lena") { t.Errorf("Expected empty option and match block to be 'Match User lena', but got: %v, %v", emptyOption, matchBlock) } matchOption, matchBlock := p.FindOption(uint32(2)) - if !(matchOption.Value == "Match User lena" && matchBlock.MatchEntry.Value == "Match User lena" && matchBlock.MatchValue.Entries[0].Values[0].Value == "lena") { + if !(matchOption.Value == "Match User lena" && matchBlock.MatchEntry.Value == "Match User lena" && matchBlock.MatchValue.Entries[0].Values.Values[0].Value == "lena" && matchBlock.MatchEntry.OptionValue.Start.Character == 6) { t.Errorf("Expected match option to be 'Match User lena', but got: %v, %v", matchOption, matchBlock) } } @@ -416,7 +475,7 @@ Match Address 172.22.100.0/24,172.22.5.0/24,127.0.0.1 t.Errorf("Expected fourth entry to be 'Match User anoncvs', but got: %v", fourthEntry.MatchEntry.Value) } - if !(fourthEntry.MatchValue.Entries[0].Criteria == "User" && fourthEntry.MatchValue.Entries[0].Values[0].Value == "anoncvs") { + if !(fourthEntry.MatchValue.Entries[0].Criteria.Type == "User" && fourthEntry.MatchValue.Entries[0].Values.Values[0].Value == "anoncvs") { t.Errorf("Expected fourth entry to be 'Match User anoncvs', but got: %v", fourthEntry.MatchValue) } @@ -440,7 +499,7 @@ Match Address 172.22.100.0/24,172.22.5.0/24,127.0.0.1 t.Errorf("Expected sixth entry to be 'Match Address 172.22.100.0/24,172.22.5.0/24,127.0.0.1', but got: %v", sixthEntry.MatchEntry.Value) } - if !(sixthEntry.MatchValue.Entries[0].Criteria == "Address" && len(sixthEntry.MatchValue.Entries[0].Values) == 3) { + if !(sixthEntry.MatchValue.Entries[0].Criteria.Type == "Address" && len(sixthEntry.MatchValue.Entries[0].Values.Values) == 3) { t.Errorf("Expected sixth entry to contain 3 values, but got: %v", sixthEntry.MatchValue) } diff --git a/handlers/sshd_config/ast/sshd_config.go b/handlers/sshd_config/ast/sshd_config.go index b448f63..fb2edee 100644 --- a/handlers/sshd_config/ast/sshd_config.go +++ b/handlers/sshd_config/ast/sshd_config.go @@ -42,14 +42,6 @@ type SSHOption struct { OptionValue *SSHValue } -func (o SSHOption) GetType() SSHEntryType { - return SSHEntryTypeOption -} - -func (o SSHOption) GetOption() SSHOption { - return o -} - type SSHMatchBlock struct { common.LocationRange MatchEntry *SSHOption @@ -59,66 +51,9 @@ type SSHMatchBlock struct { Options *treemap.Map } -func (m SSHMatchBlock) GetType() SSHEntryType { - return SSHEntryTypeMatchBlock -} - -func (m SSHMatchBlock) GetOption() SSHOption { - return *m.MatchEntry -} - type SSHConfig struct { // [uint32]SSHOption -> line number -> *SSHEntry Options *treemap.Map // [uint32]{} -> line number -> {} CommentLines map[uint32]struct{} } - -func (c SSHConfig) FindMatchBlock(line uint32) *SSHMatchBlock { - for currentLine := line; currentLine > 0; currentLine-- { - rawEntry, found := c.Options.Get(currentLine) - - if !found { - continue - } - - switch entry := rawEntry.(type) { - case *SSHMatchBlock: - return entry - } - } - - return nil -} - -func (c SSHConfig) FindOption(line uint32) (*SSHOption, *SSHMatchBlock) { - matchBlock := c.FindMatchBlock(line) - - if matchBlock != nil { - if line == matchBlock.MatchEntry.Start.Line { - return matchBlock.MatchEntry, matchBlock - } - - rawEntry, found := matchBlock.Options.Get(line) - - if found { - return rawEntry.(*SSHOption), matchBlock - } else { - return nil, matchBlock - } - } - - rawEntry, found := c.Options.Get(line) - - if found { - switch rawEntry.(type) { - case *SSHMatchBlock: - return rawEntry.(*SSHMatchBlock).MatchEntry, rawEntry.(*SSHMatchBlock) - case *SSHOption: - return rawEntry.(*SSHOption), nil - } - } - - return nil, nil - -} diff --git a/handlers/sshd_config/ast/sshd_config_fields.go b/handlers/sshd_config/ast/sshd_config_fields.go new file mode 100644 index 0000000..f82d49c --- /dev/null +++ b/handlers/sshd_config/ast/sshd_config_fields.go @@ -0,0 +1,66 @@ +package ast + +func (o SSHOption) GetType() SSHEntryType { + return SSHEntryTypeOption +} + +func (o SSHOption) GetOption() SSHOption { + return o +} + +func (m SSHMatchBlock) GetType() SSHEntryType { + return SSHEntryTypeMatchBlock +} + +func (m SSHMatchBlock) GetOption() SSHOption { + return *m.MatchEntry +} + +func (c SSHConfig) FindMatchBlock(line uint32) *SSHMatchBlock { + for currentLine := line; currentLine > 0; currentLine-- { + rawEntry, found := c.Options.Get(currentLine) + + if !found { + continue + } + + switch entry := rawEntry.(type) { + case *SSHMatchBlock: + return entry + } + } + + return nil +} + +func (c SSHConfig) FindOption(line uint32) (*SSHOption, *SSHMatchBlock) { + matchBlock := c.FindMatchBlock(line) + + if matchBlock != nil { + if line == matchBlock.MatchEntry.Start.Line { + return matchBlock.MatchEntry, matchBlock + } + + rawEntry, found := matchBlock.Options.Get(line) + + if found { + return rawEntry.(*SSHOption), matchBlock + } else { + return nil, matchBlock + } + } + + rawEntry, found := c.Options.Get(line) + + if found { + switch rawEntry.(type) { + case *SSHMatchBlock: + return rawEntry.(*SSHMatchBlock).MatchEntry, rawEntry.(*SSHMatchBlock) + case *SSHOption: + return rawEntry.(*SSHOption), nil + } + } + + return nil, nil + +} diff --git a/handlers/sshd_config/fields/fields.go b/handlers/sshd_config/fields/fields.go index b58c6f3..be277c3 100644 --- a/handlers/sshd_config/fields/fields.go +++ b/handlers/sshd_config/fields/fields.go @@ -563,27 +563,7 @@ The arguments to Match are one or more criteria-pattern pairs or the single toke The match patterns may consist of single entries or comma-separated lists and may use the wildcard and negation operators described in the “PATTERNS” section of ssh_config(5). The patterns in an Address criteria may additionally contain addresses to match in CIDR address/masklen format, such as 192.0.2.0/24 or 2001:db8::/32. Note that the mask length provided must be consistent with the address - it is an error to specify a mask length that is too long for the address or one with bits set in this host portion of the address. For example, 192.0.2.0/33 and 192.0.2.0/8, respectively. Only a subset of keywords may be used on the lines following a Match keyword. Available keywords are AcceptEnv, AllowAgentForwarding, AllowGroups, AllowStreamLocalForwarding, AllowTcpForwarding, AllowUsers, AuthenticationMethods, AuthorizedKeysCommand, AuthorizedKeysCommandUser, AuthorizedKeysFile, AuthorizedPrincipalsCommand, AuthorizedPrincipalsCommandUser, AuthorizedPrincipalsFile, Banner, CASignatureAlgorithms, ChannelTimeout, ChrootDirectory, ClientAliveCountMax, ClientAliveInterval, DenyGroups, DenyUsers, DisableForwarding, ExposeAuthInfo, ForceCommand, GatewayPorts, GSSAPIAuthentication, HostbasedAcceptedAlgorithms, HostbasedAuthentication, HostbasedUsesNameFromPacketOnly, IgnoreRhosts, Include, IPQoS, KbdInteractiveAuthentication, KerberosAuthentication, LogLevel, MaxAuthTries, MaxSessions, PasswordAuthentication, PermitEmptyPasswords, PermitListen, PermitOpen, PermitRootLogin, PermitTTY, PermitTunnel, PermitUserRC, PubkeyAcceptedAlgorithms, PubkeyAuthentication, PubkeyAuthOptions, RekeyLimit, RevokedKeys, RDomain, SetEnv, StreamLocalBindMask, StreamLocalBindUnlink, TrustedUserCAKeys, UnusedConnectionTimeout, X11DisplayOffset, X11Forwarding and X11UseLocalhost.`, - Value: docvalues.OrValue{ - Values: []docvalues.Value{ - docvalues.SingleEnumValue("All"), - docvalues.ArrayValue{ - Separator: ",", - DuplicatesExtractor: &docvalues.SimpleDuplicatesExtractor, - SubValue: docvalues.KeyEnumAssignmentValue{ - Separator: " ", - Values: map[docvalues.EnumString]docvalues.Value{ - docvalues.CreateEnumString("User"): docvalues.UserValue("", false), - docvalues.CreateEnumString("Group"): docvalues.GroupValue("", false), - docvalues.CreateEnumString("Host"): docvalues.StringValue{}, - docvalues.CreateEnumString("LocalAddress"): docvalues.StringValue{}, - docvalues.CreateEnumString("LocalPort"): docvalues.NumberValue{Min: &ZERO, Max: &MAX_PORT}, - docvalues.CreateEnumString("RDomain"): docvalues.StringValue{}, - docvalues.CreateEnumString("Address"): docvalues.StringValue{}, - }, - }, - }, - }, - }, + Value: docvalues.StringValue{}, }, "MaxAuthTries": { Documentation: `Specifies the maximum number of authentication attempts permitted per connection. Once the number of failures reaches half this value, additional failures are logged. The default is 6.`, diff --git a/handlers/sshd_config/fields/match-parser/Match.g4 b/handlers/sshd_config/fields/match-parser/Match.g4 index 9c2c54b..d7b77a4 100644 --- a/handlers/sshd_config/fields/match-parser/Match.g4 +++ b/handlers/sshd_config/fields/match-parser/Match.g4 @@ -1,25 +1,23 @@ grammar Match; root - : matchEntry? (WHITESPACE matchEntry)* EOF + : matchEntry? (WHITESPACE matchEntry?)* EOF ; matchEntry - : criteria WHITESPACE? values? + : criteria separator? values? + ; + +separator + : WHITESPACE ; criteria - : USER - | GROUP - | HOST - | LOCALADDRESS - | LOCALPORT - | RDOMAIN - | ADDRESS + : (USER | GROUP | HOST| LOCALADDRESS | LOCALPORT | RDOMAIN | ADDRESS) ; values - : value? (COMMA value?)* + : value (COMMA value?)* ; value diff --git a/handlers/sshd_config/fields/match-parser/listener.go b/handlers/sshd_config/fields/match-parser/listener.go index a7ca5ac..31bc0cb 100644 --- a/handlers/sshd_config/fields/match-parser/listener.go +++ b/handlers/sshd_config/fields/match-parser/listener.go @@ -11,16 +11,19 @@ import ( func createMatchListenerContext( line uint32, + startCharacter uint32, ) *matchListenerContext { return &matchListenerContext{ - currentEntry: nil, - line: line, + currentEntry: nil, + line: line, + startCharacter: startCharacter, } } type matchListenerContext struct { - currentEntry *MatchEntry - line uint32 + currentEntry *MatchEntry + line uint32 + startCharacter uint32 } func createListener( @@ -42,13 +45,12 @@ type matchParserListener struct { } func (s *matchParserListener) EnterMatchEntry(ctx *parser.MatchEntryContext) { - location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext) + location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext).ShiftHorizontal(s.matchContext.startCharacter) location.ChangeBothLines(s.matchContext.line) entry := &MatchEntry{ LocationRange: location, Value: ctx.GetText(), - Values: make([]*MatchValue, 0), } s.match.Entries = append(s.match.Entries, entry) @@ -70,7 +72,7 @@ var availableCriteria = map[string]MatchCriteriaType{ } func (s *matchParserListener) EnterCriteria(ctx *parser.CriteriaContext) { - location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext) + location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext).ShiftHorizontal(s.matchContext.startCharacter) location.ChangeBothLines(s.matchContext.line) criteria, found := availableCriteria[ctx.GetText()] @@ -83,11 +85,33 @@ func (s *matchParserListener) EnterCriteria(ctx *parser.CriteriaContext) { return } - s.matchContext.currentEntry.Criteria = criteria + s.matchContext.currentEntry.Criteria = MatchCriteria{ + LocationRange: location, + Type: criteria, + } +} + +func (s *matchParserListener) EnterSeparator(ctx *parser.SeparatorContext) { + location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext).ShiftHorizontal(s.matchContext.startCharacter) + location.ChangeBothLines(s.matchContext.line) + + s.matchContext.currentEntry.Separator = &MatchSeparator{ + LocationRange: location, + } +} + +func (s *matchParserListener) EnterValues(ctx *parser.ValuesContext) { + location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext).ShiftHorizontal(s.matchContext.startCharacter) + location.ChangeBothLines(s.matchContext.line) + + s.matchContext.currentEntry.Values = &MatchValues{ + LocationRange: location, + Values: make([]*MatchValue, 0), + } } func (s *matchParserListener) EnterValue(ctx *parser.ValueContext) { - location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext) + location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext).ShiftHorizontal(s.matchContext.startCharacter) location.ChangeBothLines(s.matchContext.line) value := &MatchValue{ @@ -95,5 +119,5 @@ func (s *matchParserListener) EnterValue(ctx *parser.ValueContext) { Value: ctx.GetText(), } - s.matchContext.currentEntry.Values = append(s.matchContext.currentEntry.Values, value) + s.matchContext.currentEntry.Values.Values = append(s.matchContext.currentEntry.Values.Values, value) } diff --git a/handlers/sshd_config/fields/match-parser/match_ast.go b/handlers/sshd_config/fields/match-parser/match_ast.go index 2f97f1f..d02a693 100644 --- a/handlers/sshd_config/fields/match-parser/match_ast.go +++ b/handlers/sshd_config/fields/match-parser/match_ast.go @@ -26,12 +26,23 @@ type MatchCriteria struct { Type MatchCriteriaType } +type MatchSeparator struct { + common.LocationRange +} + +type MatchValues struct { + common.LocationRange + + Values []*MatchValue +} + type MatchEntry struct { common.LocationRange Value string - Criteria MatchCriteriaType - Values []*MatchValue + Criteria MatchCriteria + Separator *MatchSeparator + Values *MatchValues } type MatchValue struct { diff --git a/handlers/sshd_config/fields/match-parser/match_fields.go b/handlers/sshd_config/fields/match-parser/match_fields.go new file mode 100644 index 0000000..dca690d --- /dev/null +++ b/handlers/sshd_config/fields/match-parser/match_fields.go @@ -0,0 +1,67 @@ +package match_parser + +import "slices" + +func (m Match) GetEntryByCursor(cursor uint32) *MatchEntry { + index, found := slices.BinarySearchFunc( + m.Entries, + cursor, + func(entry *MatchEntry, cursor uint32) int { + if cursor < entry.Start.Character { + return 1 + } + + if cursor > entry.End.Character { + return -1 + } + + return 0 + }, + ) + + if !found { + return nil + } + + entry := m.Entries[index] + + return entry +} + +func (c MatchCriteria) IsCursorBetween(cursor uint32) bool { + return cursor >= c.Start.Character && cursor <= c.End.Character +} + +func (e MatchEntry) GetValueByCursor(cursor uint32) *MatchValue { + if e.Values == nil { + return nil + } + + index, found := slices.BinarySearchFunc( + e.Values.Values, + cursor, + func(value *MatchValue, cursor uint32) int { + if cursor < value.Start.Character { + return 1 + } + + if cursor > value.End.Character { + return -1 + } + + return 0 + }, + ) + + if !found { + return nil + } + + value := e.Values.Values[index] + + return value +} + +func (v MatchValues) IsCursorBetween(cursor uint32) bool { + return cursor >= v.Start.Character && cursor <= v.End.Character +} diff --git a/handlers/sshd_config/fields/match-parser/parser.go b/handlers/sshd_config/fields/match-parser/parser.go index 96fe394..abbc2f7 100644 --- a/handlers/sshd_config/fields/match-parser/parser.go +++ b/handlers/sshd_config/fields/match-parser/parser.go @@ -20,8 +20,9 @@ func (m *Match) Clear() { func (m *Match) Parse( input string, line uint32, + startCharacter uint32, ) []common.LSPError { - context := createMatchListenerContext(line) + context := createMatchListenerContext(line, startCharacter) stream := antlr.NewInputStream(input) diff --git a/handlers/sshd_config/fields/match-parser/parser/Match.interp b/handlers/sshd_config/fields/match-parser/parser/Match.interp index 274d459..1291067 100644 --- a/handlers/sshd_config/fields/match-parser/parser/Match.interp +++ b/handlers/sshd_config/fields/match-parser/parser/Match.interp @@ -27,10 +27,11 @@ WHITESPACE rule names: root matchEntry +separator criteria values value atn: -[4, 1, 10, 46, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 1, 0, 3, 0, 12, 8, 0, 1, 0, 1, 0, 5, 0, 16, 8, 0, 10, 0, 12, 0, 19, 9, 0, 1, 0, 1, 0, 1, 1, 1, 1, 3, 1, 25, 8, 1, 1, 1, 3, 1, 28, 8, 1, 1, 2, 1, 2, 1, 3, 3, 3, 33, 8, 3, 1, 3, 1, 3, 3, 3, 37, 8, 3, 5, 3, 39, 8, 3, 10, 3, 12, 3, 42, 9, 3, 1, 4, 1, 4, 1, 4, 0, 0, 5, 0, 2, 4, 6, 8, 0, 1, 1, 0, 1, 7, 47, 0, 11, 1, 0, 0, 0, 2, 22, 1, 0, 0, 0, 4, 29, 1, 0, 0, 0, 6, 32, 1, 0, 0, 0, 8, 43, 1, 0, 0, 0, 10, 12, 3, 2, 1, 0, 11, 10, 1, 0, 0, 0, 11, 12, 1, 0, 0, 0, 12, 17, 1, 0, 0, 0, 13, 14, 5, 10, 0, 0, 14, 16, 3, 2, 1, 0, 15, 13, 1, 0, 0, 0, 16, 19, 1, 0, 0, 0, 17, 15, 1, 0, 0, 0, 17, 18, 1, 0, 0, 0, 18, 20, 1, 0, 0, 0, 19, 17, 1, 0, 0, 0, 20, 21, 5, 0, 0, 1, 21, 1, 1, 0, 0, 0, 22, 24, 3, 4, 2, 0, 23, 25, 5, 10, 0, 0, 24, 23, 1, 0, 0, 0, 24, 25, 1, 0, 0, 0, 25, 27, 1, 0, 0, 0, 26, 28, 3, 6, 3, 0, 27, 26, 1, 0, 0, 0, 27, 28, 1, 0, 0, 0, 28, 3, 1, 0, 0, 0, 29, 30, 7, 0, 0, 0, 30, 5, 1, 0, 0, 0, 31, 33, 3, 8, 4, 0, 32, 31, 1, 0, 0, 0, 32, 33, 1, 0, 0, 0, 33, 40, 1, 0, 0, 0, 34, 36, 5, 8, 0, 0, 35, 37, 3, 8, 4, 0, 36, 35, 1, 0, 0, 0, 36, 37, 1, 0, 0, 0, 37, 39, 1, 0, 0, 0, 38, 34, 1, 0, 0, 0, 39, 42, 1, 0, 0, 0, 40, 38, 1, 0, 0, 0, 40, 41, 1, 0, 0, 0, 41, 7, 1, 0, 0, 0, 42, 40, 1, 0, 0, 0, 43, 44, 5, 9, 0, 0, 44, 9, 1, 0, 0, 0, 7, 11, 17, 24, 27, 32, 36, 40] \ No newline at end of file +[4, 1, 10, 50, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 2, 5, 7, 5, 1, 0, 3, 0, 14, 8, 0, 1, 0, 1, 0, 3, 0, 18, 8, 0, 5, 0, 20, 8, 0, 10, 0, 12, 0, 23, 9, 0, 1, 0, 1, 0, 1, 1, 1, 1, 3, 1, 29, 8, 1, 1, 1, 3, 1, 32, 8, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, 1, 4, 1, 4, 3, 4, 41, 8, 4, 5, 4, 43, 8, 4, 10, 4, 12, 4, 46, 9, 4, 1, 5, 1, 5, 1, 5, 0, 0, 6, 0, 2, 4, 6, 8, 10, 0, 1, 1, 0, 1, 7, 50, 0, 13, 1, 0, 0, 0, 2, 26, 1, 0, 0, 0, 4, 33, 1, 0, 0, 0, 6, 35, 1, 0, 0, 0, 8, 37, 1, 0, 0, 0, 10, 47, 1, 0, 0, 0, 12, 14, 3, 2, 1, 0, 13, 12, 1, 0, 0, 0, 13, 14, 1, 0, 0, 0, 14, 21, 1, 0, 0, 0, 15, 17, 5, 10, 0, 0, 16, 18, 3, 2, 1, 0, 17, 16, 1, 0, 0, 0, 17, 18, 1, 0, 0, 0, 18, 20, 1, 0, 0, 0, 19, 15, 1, 0, 0, 0, 20, 23, 1, 0, 0, 0, 21, 19, 1, 0, 0, 0, 21, 22, 1, 0, 0, 0, 22, 24, 1, 0, 0, 0, 23, 21, 1, 0, 0, 0, 24, 25, 5, 0, 0, 1, 25, 1, 1, 0, 0, 0, 26, 28, 3, 6, 3, 0, 27, 29, 3, 4, 2, 0, 28, 27, 1, 0, 0, 0, 28, 29, 1, 0, 0, 0, 29, 31, 1, 0, 0, 0, 30, 32, 3, 8, 4, 0, 31, 30, 1, 0, 0, 0, 31, 32, 1, 0, 0, 0, 32, 3, 1, 0, 0, 0, 33, 34, 5, 10, 0, 0, 34, 5, 1, 0, 0, 0, 35, 36, 7, 0, 0, 0, 36, 7, 1, 0, 0, 0, 37, 44, 3, 10, 5, 0, 38, 40, 5, 8, 0, 0, 39, 41, 3, 10, 5, 0, 40, 39, 1, 0, 0, 0, 40, 41, 1, 0, 0, 0, 41, 43, 1, 0, 0, 0, 42, 38, 1, 0, 0, 0, 43, 46, 1, 0, 0, 0, 44, 42, 1, 0, 0, 0, 44, 45, 1, 0, 0, 0, 45, 9, 1, 0, 0, 0, 46, 44, 1, 0, 0, 0, 47, 48, 5, 9, 0, 0, 48, 11, 1, 0, 0, 0, 7, 13, 17, 21, 28, 31, 40, 44] \ No newline at end of file diff --git a/handlers/sshd_config/fields/match-parser/parser/match_base_listener.go b/handlers/sshd_config/fields/match-parser/parser/match_base_listener.go index 2190a4a..85a1a79 100644 --- a/handlers/sshd_config/fields/match-parser/parser/match_base_listener.go +++ b/handlers/sshd_config/fields/match-parser/parser/match_base_listener.go @@ -33,6 +33,12 @@ func (s *BaseMatchListener) EnterMatchEntry(ctx *MatchEntryContext) {} // ExitMatchEntry is called when production matchEntry is exited. func (s *BaseMatchListener) ExitMatchEntry(ctx *MatchEntryContext) {} +// EnterSeparator is called when production separator is entered. +func (s *BaseMatchListener) EnterSeparator(ctx *SeparatorContext) {} + +// ExitSeparator is called when production separator is exited. +func (s *BaseMatchListener) ExitSeparator(ctx *SeparatorContext) {} + // EnterCriteria is called when production criteria is entered. func (s *BaseMatchListener) EnterCriteria(ctx *CriteriaContext) {} diff --git a/handlers/sshd_config/fields/match-parser/parser/match_listener.go b/handlers/sshd_config/fields/match-parser/parser/match_listener.go index 8db9553..4adb71d 100644 --- a/handlers/sshd_config/fields/match-parser/parser/match_listener.go +++ b/handlers/sshd_config/fields/match-parser/parser/match_listener.go @@ -14,6 +14,9 @@ type MatchListener interface { // EnterMatchEntry is called when entering the matchEntry production. EnterMatchEntry(c *MatchEntryContext) + // EnterSeparator is called when entering the separator production. + EnterSeparator(c *SeparatorContext) + // EnterCriteria is called when entering the criteria production. EnterCriteria(c *CriteriaContext) @@ -29,6 +32,9 @@ type MatchListener interface { // ExitMatchEntry is called when exiting the matchEntry production. ExitMatchEntry(c *MatchEntryContext) + // ExitSeparator is called when exiting the separator production. + ExitSeparator(c *SeparatorContext) + // ExitCriteria is called when exiting the criteria production. ExitCriteria(c *CriteriaContext) diff --git a/handlers/sshd_config/fields/match-parser/parser/match_parser.go b/handlers/sshd_config/fields/match-parser/parser/match_parser.go index 79a4ea4..79f54ba 100644 --- a/handlers/sshd_config/fields/match-parser/parser/match_parser.go +++ b/handlers/sshd_config/fields/match-parser/parser/match_parser.go @@ -40,29 +40,30 @@ func matchParserInit() { "ADDRESS", "COMMA", "STRING", "WHITESPACE", } staticData.RuleNames = []string{ - "root", "matchEntry", "criteria", "values", "value", + "root", "matchEntry", "separator", "criteria", "values", "value", } staticData.PredictionContextCache = antlr.NewPredictionContextCache() staticData.serializedATN = []int32{ - 4, 1, 10, 46, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, - 4, 1, 0, 3, 0, 12, 8, 0, 1, 0, 1, 0, 5, 0, 16, 8, 0, 10, 0, 12, 0, 19, - 9, 0, 1, 0, 1, 0, 1, 1, 1, 1, 3, 1, 25, 8, 1, 1, 1, 3, 1, 28, 8, 1, 1, - 2, 1, 2, 1, 3, 3, 3, 33, 8, 3, 1, 3, 1, 3, 3, 3, 37, 8, 3, 5, 3, 39, 8, - 3, 10, 3, 12, 3, 42, 9, 3, 1, 4, 1, 4, 1, 4, 0, 0, 5, 0, 2, 4, 6, 8, 0, - 1, 1, 0, 1, 7, 47, 0, 11, 1, 0, 0, 0, 2, 22, 1, 0, 0, 0, 4, 29, 1, 0, 0, - 0, 6, 32, 1, 0, 0, 0, 8, 43, 1, 0, 0, 0, 10, 12, 3, 2, 1, 0, 11, 10, 1, - 0, 0, 0, 11, 12, 1, 0, 0, 0, 12, 17, 1, 0, 0, 0, 13, 14, 5, 10, 0, 0, 14, - 16, 3, 2, 1, 0, 15, 13, 1, 0, 0, 0, 16, 19, 1, 0, 0, 0, 17, 15, 1, 0, 0, - 0, 17, 18, 1, 0, 0, 0, 18, 20, 1, 0, 0, 0, 19, 17, 1, 0, 0, 0, 20, 21, - 5, 0, 0, 1, 21, 1, 1, 0, 0, 0, 22, 24, 3, 4, 2, 0, 23, 25, 5, 10, 0, 0, - 24, 23, 1, 0, 0, 0, 24, 25, 1, 0, 0, 0, 25, 27, 1, 0, 0, 0, 26, 28, 3, - 6, 3, 0, 27, 26, 1, 0, 0, 0, 27, 28, 1, 0, 0, 0, 28, 3, 1, 0, 0, 0, 29, - 30, 7, 0, 0, 0, 30, 5, 1, 0, 0, 0, 31, 33, 3, 8, 4, 0, 32, 31, 1, 0, 0, - 0, 32, 33, 1, 0, 0, 0, 33, 40, 1, 0, 0, 0, 34, 36, 5, 8, 0, 0, 35, 37, - 3, 8, 4, 0, 36, 35, 1, 0, 0, 0, 36, 37, 1, 0, 0, 0, 37, 39, 1, 0, 0, 0, - 38, 34, 1, 0, 0, 0, 39, 42, 1, 0, 0, 0, 40, 38, 1, 0, 0, 0, 40, 41, 1, - 0, 0, 0, 41, 7, 1, 0, 0, 0, 42, 40, 1, 0, 0, 0, 43, 44, 5, 9, 0, 0, 44, - 9, 1, 0, 0, 0, 7, 11, 17, 24, 27, 32, 36, 40, + 4, 1, 10, 50, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, + 4, 2, 5, 7, 5, 1, 0, 3, 0, 14, 8, 0, 1, 0, 1, 0, 3, 0, 18, 8, 0, 5, 0, + 20, 8, 0, 10, 0, 12, 0, 23, 9, 0, 1, 0, 1, 0, 1, 1, 1, 1, 3, 1, 29, 8, + 1, 1, 1, 3, 1, 32, 8, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, 1, 4, 1, 4, 3, 4, + 41, 8, 4, 5, 4, 43, 8, 4, 10, 4, 12, 4, 46, 9, 4, 1, 5, 1, 5, 1, 5, 0, + 0, 6, 0, 2, 4, 6, 8, 10, 0, 1, 1, 0, 1, 7, 50, 0, 13, 1, 0, 0, 0, 2, 26, + 1, 0, 0, 0, 4, 33, 1, 0, 0, 0, 6, 35, 1, 0, 0, 0, 8, 37, 1, 0, 0, 0, 10, + 47, 1, 0, 0, 0, 12, 14, 3, 2, 1, 0, 13, 12, 1, 0, 0, 0, 13, 14, 1, 0, 0, + 0, 14, 21, 1, 0, 0, 0, 15, 17, 5, 10, 0, 0, 16, 18, 3, 2, 1, 0, 17, 16, + 1, 0, 0, 0, 17, 18, 1, 0, 0, 0, 18, 20, 1, 0, 0, 0, 19, 15, 1, 0, 0, 0, + 20, 23, 1, 0, 0, 0, 21, 19, 1, 0, 0, 0, 21, 22, 1, 0, 0, 0, 22, 24, 1, + 0, 0, 0, 23, 21, 1, 0, 0, 0, 24, 25, 5, 0, 0, 1, 25, 1, 1, 0, 0, 0, 26, + 28, 3, 6, 3, 0, 27, 29, 3, 4, 2, 0, 28, 27, 1, 0, 0, 0, 28, 29, 1, 0, 0, + 0, 29, 31, 1, 0, 0, 0, 30, 32, 3, 8, 4, 0, 31, 30, 1, 0, 0, 0, 31, 32, + 1, 0, 0, 0, 32, 3, 1, 0, 0, 0, 33, 34, 5, 10, 0, 0, 34, 5, 1, 0, 0, 0, + 35, 36, 7, 0, 0, 0, 36, 7, 1, 0, 0, 0, 37, 44, 3, 10, 5, 0, 38, 40, 5, + 8, 0, 0, 39, 41, 3, 10, 5, 0, 40, 39, 1, 0, 0, 0, 40, 41, 1, 0, 0, 0, 41, + 43, 1, 0, 0, 0, 42, 38, 1, 0, 0, 0, 43, 46, 1, 0, 0, 0, 44, 42, 1, 0, 0, + 0, 44, 45, 1, 0, 0, 0, 45, 9, 1, 0, 0, 0, 46, 44, 1, 0, 0, 0, 47, 48, 5, + 9, 0, 0, 48, 11, 1, 0, 0, 0, 7, 13, 17, 21, 28, 31, 40, 44, } deserializer := antlr.NewATNDeserializer(nil) staticData.atn = deserializer.Deserialize(staticData.serializedATN) @@ -117,9 +118,10 @@ const ( const ( MatchParserRULE_root = 0 MatchParserRULE_matchEntry = 1 - MatchParserRULE_criteria = 2 - MatchParserRULE_values = 3 - MatchParserRULE_value = 4 + MatchParserRULE_separator = 2 + MatchParserRULE_criteria = 3 + MatchParserRULE_values = 4 + MatchParserRULE_value = 5 ) // IRootContext is an interface to support dynamic dispatch. @@ -251,7 +253,7 @@ func (p *MatchParser) Root() (localctx IRootContext) { var _la int p.EnterOuterAlt(localctx, 1) - p.SetState(11) + p.SetState(13) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -260,12 +262,12 @@ func (p *MatchParser) Root() (localctx IRootContext) { if (int64(_la) & ^0x3f) == 0 && ((int64(1)<<_la)&254) != 0 { { - p.SetState(10) + p.SetState(12) p.MatchEntry() } } - p.SetState(17) + p.SetState(21) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -274,19 +276,29 @@ func (p *MatchParser) Root() (localctx IRootContext) { for _la == MatchParserWHITESPACE { { - p.SetState(13) + p.SetState(15) p.Match(MatchParserWHITESPACE) if p.HasError() { // Recognition error - abort rule goto errorExit } } - { - p.SetState(14) - p.MatchEntry() + p.SetState(17) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + if (int64(_la) & ^0x3f) == 0 && ((int64(1)<<_la)&254) != 0 { + { + p.SetState(16) + p.MatchEntry() + } + } - p.SetState(19) + p.SetState(23) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -294,7 +306,7 @@ func (p *MatchParser) Root() (localctx IRootContext) { _la = p.GetTokenStream().LA(1) } { - p.SetState(20) + p.SetState(24) p.Match(MatchParserEOF) if p.HasError() { // Recognition error - abort rule @@ -324,7 +336,7 @@ type IMatchEntryContext interface { // Getter signatures Criteria() ICriteriaContext - WHITESPACE() antlr.TerminalNode + Separator() ISeparatorContext Values() IValuesContext // IsMatchEntryContext differentiates from other interfaces. @@ -379,8 +391,20 @@ func (s *MatchEntryContext) Criteria() ICriteriaContext { return t.(ICriteriaContext) } -func (s *MatchEntryContext) WHITESPACE() antlr.TerminalNode { - return s.GetToken(MatchParserWHITESPACE, 0) +func (s *MatchEntryContext) Separator() ISeparatorContext { + var t antlr.RuleContext + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(ISeparatorContext); ok { + t = ctx.(antlr.RuleContext) + break + } + } + + if t == nil { + return nil + } + + return t.(ISeparatorContext) } func (s *MatchEntryContext) Values() IValuesContext { @@ -422,39 +446,135 @@ func (s *MatchEntryContext) ExitRule(listener antlr.ParseTreeListener) { func (p *MatchParser) MatchEntry() (localctx IMatchEntryContext) { localctx = NewMatchEntryContext(p, p.GetParserRuleContext(), p.GetState()) p.EnterRule(localctx, 2, MatchParserRULE_matchEntry) + var _la int + p.EnterOuterAlt(localctx, 1) { - p.SetState(22) + p.SetState(26) p.Criteria() } - p.SetState(24) - p.GetErrorHandler().Sync(p) - - if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 2, p.GetParserRuleContext()) == 1 { - { - p.SetState(23) - p.Match(MatchParserWHITESPACE) - if p.HasError() { - // Recognition error - abort rule - goto errorExit - } - } - - } else if p.HasError() { // JIM - goto errorExit - } - p.SetState(27) + p.SetState(28) p.GetErrorHandler().Sync(p) if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 3, p.GetParserRuleContext()) == 1 { { - p.SetState(26) - p.Values() + p.SetState(27) + p.Separator() } } else if p.HasError() { // JIM goto errorExit } + p.SetState(31) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + if _la == MatchParserSTRING { + { + p.SetState(30) + p.Values() + } + + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} + +// ISeparatorContext is an interface to support dynamic dispatch. +type ISeparatorContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + + // Getter signatures + WHITESPACE() antlr.TerminalNode + + // IsSeparatorContext differentiates from other interfaces. + IsSeparatorContext() +} + +type SeparatorContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptySeparatorContext() *SeparatorContext { + var p = new(SeparatorContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = MatchParserRULE_separator + return p +} + +func InitEmptySeparatorContext(p *SeparatorContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = MatchParserRULE_separator +} + +func (*SeparatorContext) IsSeparatorContext() {} + +func NewSeparatorContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *SeparatorContext { + var p = new(SeparatorContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = MatchParserRULE_separator + + return p +} + +func (s *SeparatorContext) GetParser() antlr.Parser { return s.parser } + +func (s *SeparatorContext) WHITESPACE() antlr.TerminalNode { + return s.GetToken(MatchParserWHITESPACE, 0) +} + +func (s *SeparatorContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *SeparatorContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +func (s *SeparatorContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(MatchListener); ok { + listenerT.EnterSeparator(s) + } +} + +func (s *SeparatorContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(MatchListener); ok { + listenerT.ExitSeparator(s) + } +} + +func (p *MatchParser) Separator() (localctx ISeparatorContext) { + localctx = NewSeparatorContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 4, MatchParserRULE_separator) + p.EnterOuterAlt(localctx, 1) + { + p.SetState(33) + p.Match(MatchParserWHITESPACE) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } errorExit: if p.HasError() { @@ -571,12 +691,12 @@ func (s *CriteriaContext) ExitRule(listener antlr.ParseTreeListener) { func (p *MatchParser) Criteria() (localctx ICriteriaContext) { localctx = NewCriteriaContext(p, p.GetParserRuleContext(), p.GetState()) - p.EnterRule(localctx, 4, MatchParserRULE_criteria) + p.EnterRule(localctx, 6, MatchParserRULE_criteria) var _la int p.EnterOuterAlt(localctx, 1) { - p.SetState(29) + p.SetState(35) _la = p.GetTokenStream().LA(1) if !((int64(_la) & ^0x3f) == 0 && ((int64(1)<<_la)&254) != 0) { @@ -720,25 +840,15 @@ func (s *ValuesContext) ExitRule(listener antlr.ParseTreeListener) { func (p *MatchParser) Values() (localctx IValuesContext) { localctx = NewValuesContext(p, p.GetParserRuleContext(), p.GetState()) - p.EnterRule(localctx, 6, MatchParserRULE_values) + p.EnterRule(localctx, 8, MatchParserRULE_values) var _la int p.EnterOuterAlt(localctx, 1) - p.SetState(32) - p.GetErrorHandler().Sync(p) - if p.HasError() { - goto errorExit + { + p.SetState(37) + p.Value() } - _la = p.GetTokenStream().LA(1) - - if _la == MatchParserSTRING { - { - p.SetState(31) - p.Value() - } - - } - p.SetState(40) + p.SetState(44) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -747,14 +857,14 @@ func (p *MatchParser) Values() (localctx IValuesContext) { for _la == MatchParserCOMMA { { - p.SetState(34) + p.SetState(38) p.Match(MatchParserCOMMA) if p.HasError() { // Recognition error - abort rule goto errorExit } } - p.SetState(36) + p.SetState(40) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -763,13 +873,13 @@ func (p *MatchParser) Values() (localctx IValuesContext) { if _la == MatchParserSTRING { { - p.SetState(35) + p.SetState(39) p.Value() } } - p.SetState(42) + p.SetState(46) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -862,10 +972,10 @@ func (s *ValueContext) ExitRule(listener antlr.ParseTreeListener) { func (p *MatchParser) Value() (localctx IValueContext) { localctx = NewValueContext(p, p.GetParserRuleContext(), p.GetState()) - p.EnterRule(localctx, 8, MatchParserRULE_value) + p.EnterRule(localctx, 10, MatchParserRULE_value) p.EnterOuterAlt(localctx, 1) { - p.SetState(43) + p.SetState(47) p.Match(MatchParserSTRING) if p.HasError() { // Recognition error - abort rule diff --git a/handlers/sshd_config/fields/match-parser/parser_test.go b/handlers/sshd_config/fields/match-parser/parser_test.go index df9395c..d24343a 100644 --- a/handlers/sshd_config/fields/match-parser/parser_test.go +++ b/handlers/sshd_config/fields/match-parser/parser_test.go @@ -7,10 +7,11 @@ import ( func TestComplexExample( t *testing.T, ) { + offset := uint32(5) input := "User root,admin,alice Address *,!192.168.0.1" match := NewMatch() - errors := match.Parse(input, 32) + errors := match.Parse(input, 32, offset) if len(errors) > 0 { t.Fatalf("Expected no errors, but got %v", errors) @@ -20,32 +21,32 @@ func TestComplexExample( t.Fatalf("Expected 2 entries, but got %v", len(match.Entries)) } - if !(match.Entries[0].Criteria == MatchCriteriaTypeUser) { + if !(match.Entries[0].Criteria.Type == MatchCriteriaTypeUser) { t.Fatalf("Expected User, but got %v", match.Entries[0]) } - if !(match.Entries[0].Values[0].Value == "root") { - t.Fatalf("Expected root, but got %v", match.Entries[0].Values[0]) + if !(match.Entries[0].Values.Values[0].Value == "root" && match.Entries[0].Values.Values[0].Start.Character == 5+offset && match.Entries[0].Values.Values[0].End.Character == 8+offset && match.Entries[0].Start.Character == 0+offset && match.Entries[0].End.Character == 20+offset) { + t.Errorf("Expected root, but got %v", match.Entries[0].Values.Values[0]) } - if !(match.Entries[0].Values[1].Value == "admin") { - t.Fatalf("Expected admin, but got %v", match.Entries[0].Values[1]) + if !(match.Entries[0].Values.Values[1].Value == "admin" && match.Entries[0].Values.Values[1].Start.Character == 10+offset && match.Entries[0].Values.Values[1].End.Character == 14+offset) { + t.Errorf("Expected admin, but got %v", match.Entries[0].Values.Values[1]) } - if !(match.Entries[0].Values[2].Value == "alice") { - t.Fatalf("Expected alice, but got %v", match.Entries[0].Values[2]) + if !(match.Entries[0].Values.Values[2].Value == "alice" && match.Entries[0].Values.Values[2].Start.Character == 16+offset && match.Entries[0].Values.Values[2].End.Character == 20+offset) { + t.Errorf("Expected alice, but got %v", match.Entries[0].Values.Values[2]) } - if !(match.Entries[1].Criteria == MatchCriteriaTypeAddress) { - t.Fatalf("Expected Address, but got %v", match.Entries[1]) + if !(match.Entries[1].Criteria.Type == MatchCriteriaTypeAddress) { + t.Errorf("Expected Address, but got %v", match.Entries[1]) } - if !(match.Entries[1].Values[0].Value == "*") { - t.Fatalf("Expected *, but got %v", match.Entries[1].Values[0]) + if !(match.Entries[1].Values.Values[0].Value == "*" && match.Entries[1].Values.Values[0].Start.Character == 30+offset && match.Entries[1].Values.Values[0].End.Character == 30+offset) { + t.Errorf("Expected *, but got %v", match.Entries[1].Values.Values[0]) } - if !(match.Entries[1].Values[1].Value == "!192.168.0.1") { - t.Fatalf("Expected !192.168.0.1, but got %v", match.Entries[1].Values[1]) + if !(match.Entries[1].Values.Values[1].Value == "!192.168.0.1" && match.Entries[1].Values.Values[1].Start.Character == 32+offset && match.Entries[1].Values.Values[1].End.Character == 43+offset) { + t.Errorf("Expected !192.168.0.1, but got %v", match.Entries[1].Values.Values[1]) } } @@ -55,7 +56,7 @@ func TestSecondComplexExample( input := "Address 172.22.100.0/24,172.22.5.0/24,127.0.0.1" match := NewMatch() - errors := match.Parse(input, 0) + errors := match.Parse(input, 0, 20) if len(errors) > 0 { t.Fatalf("Expected no errors, but got %v", errors) @@ -65,15 +66,69 @@ func TestSecondComplexExample( t.Fatalf("Expected 1 entries, but got %v", len(match.Entries)) } - if !(match.Entries[0].Criteria == MatchCriteriaTypeAddress) { + if !(match.Entries[0].Criteria.Type == MatchCriteriaTypeAddress) { t.Fatalf("Expected Address, but got %v", match.Entries[0]) } - if !(len(match.Entries[0].Values) == 3) { - t.Fatalf("Expected 3 values, but got %v", len(match.Entries[0].Values)) + if !(len(match.Entries[0].Values.Values) == 3) { + t.Fatalf("Expected 3 values, but got %v", len(match.Entries[0].Values.Values)) } - if !(match.Entries[0].Values[0].Value == "172.22.100.0/24") { - t.Fatalf("Expected 172.22.100.0/24, but got %v", match.Entries[0].Values[0]) + if !(match.Entries[0].Values.Values[0].Value == "172.22.100.0/24") { + t.Fatalf("Expected 172.22.100.0/24, but got %v", match.Entries[0].Values.Values[0]) + } +} + +func TestIncompleteBetweenEntriesExample( + t *testing.T, +) { + input := "User root,admin,alice " + + match := NewMatch() + errors := match.Parse(input, 0, 0) + + if len(errors) > 0 { + t.Fatalf("Expected no errors, but got %v", errors) + } + + if !(len(match.Entries) == 1) { + t.Errorf("Expected 1 entries, but got %v", len(match.Entries)) + } + + if !(match.Entries[0].Criteria.Type == MatchCriteriaTypeUser) { + t.Errorf("Expected User, but got %v", match.Entries[0]) + } + + if !(len(match.Entries[0].Values.Values) == 3) { + t.Errorf("Expected 3 values, but got %v", len(match.Entries[0].Values.Values)) + } + + if !(match.Entries[0].Start.Character == 0 && match.Entries[0].End.Character == 20) { + t.Errorf("Expected 0-20, but got %v", match.Entries[0]) + } +} + +func TestIncompleteBetweenValuesExample( + t *testing.T, +) { + input := "User " + + match := NewMatch() + errors := match.Parse(input, 0, 0) + + if len(errors) > 0 { + t.Fatalf("Expected no errors, but got %v", errors) + } + + if !(len(match.Entries) == 1) { + t.Errorf("Expected 1 entries, but got %v", len(match.Entries)) + } + + if !(match.Entries[0].Criteria.Type == MatchCriteriaTypeUser) { + t.Errorf("Expected User, but got %v", match.Entries[0]) + } + + if !(match.Entries[0].Values == nil) { + t.Errorf("Expected 0 values, but got %v", match.Entries[0].Values) } } diff --git a/handlers/sshd_config/fields/match.go b/handlers/sshd_config/fields/match.go index 332c699..59da836 100644 --- a/handlers/sshd_config/fields/match.go +++ b/handlers/sshd_config/fields/match.go @@ -1,5 +1,7 @@ package fields +import docvalues "config-lsp/doc-values" + var MatchAllowedOptions = map[string]struct{}{ "AcceptEnv": {}, "AllowAgentForwarding": {}, @@ -61,3 +63,15 @@ var MatchAllowedOptions = map[string]struct{}{ "X11Forwarding": {}, "X11UseLocalhos": {}, } + +var MatchUserField = docvalues.UserValue("", false) +var MatchGroupField = docvalues.GroupValue("", false) +var MatchHostField = docvalues.DomainValue() +var MatchLocalAddressField = docvalues.StringValue{} +var MatchLocalPortField = docvalues.StringValue{} +var MatchRDomainField = docvalues.StringValue{} +var MatchAddressField = docvalues.IPAddressValue{ + AllowIPv4: true, + AllowIPv6: true, + AllowRange: true, +} diff --git a/handlers/sshd_config/handlers/completions.go b/handlers/sshd_config/handlers/completions.go index ceba5e7..f415b25 100644 --- a/handlers/sshd_config/handlers/completions.go +++ b/handlers/sshd_config/handlers/completions.go @@ -55,6 +55,7 @@ func GetRootCompletions( func GetOptionCompletions( d *sshdconfig.SSHDocument, entry *ast.SSHOption, + matchBlock *ast.SSHMatchBlock, cursor uint32, ) ([]protocol.CompletionItem, error) { option, found := fields.Options[entry.Key.Value] @@ -63,12 +64,19 @@ func GetOptionCompletions( return nil, nil } + if entry.Key.Value == "Match" { + return getMatchCompletions( + d, + matchBlock.MatchValue, + cursor-matchBlock.MatchEntry.Start.Character, + ) + } + + line := entry.OptionValue.Value + if entry.OptionValue == nil { return option.FetchCompletions("", 0), nil } - relativeCursor := common.CursorToCharacterIndex(cursor - entry.OptionValue.Start.Character) - line := entry.OptionValue.Value - - return option.FetchCompletions(line, relativeCursor), nil + return option.FetchCompletions(line, common.CursorToCharacterIndex(cursor)), nil } diff --git a/handlers/sshd_config/handlers/completions_match.go b/handlers/sshd_config/handlers/completions_match.go new file mode 100644 index 0000000..4a6fa2f --- /dev/null +++ b/handlers/sshd_config/handlers/completions_match.go @@ -0,0 +1,111 @@ +package handlers + +import ( + sshdconfig "config-lsp/handlers/sshd_config" + "config-lsp/handlers/sshd_config/fields" + match_parser "config-lsp/handlers/sshd_config/fields/match-parser" + + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func getMatchCompletions( + d *sshdconfig.SSHDocument, + match *match_parser.Match, + cursor uint32, +) ([]protocol.CompletionItem, error) { + if len(match.Entries) == 0 { + completions := getMatchCriteriaCompletions() + completions = append(completions, getMatchAllKeywordCompletion()) + + return completions, nil + } + + entry := match.GetEntryByCursor(cursor) + + if entry == nil || entry.Criteria.IsCursorBetween(cursor) { + return getMatchCriteriaCompletions(), nil + } + + return getMatchValueCompletions(entry, cursor), nil +} + +func getMatchCriteriaCompletions() []protocol.CompletionItem { + kind := protocol.CompletionItemKindEnum + + return []protocol.CompletionItem{ + { + Label: string(match_parser.MatchCriteriaTypeUser), + Kind: &kind, + }, + { + Label: string(match_parser.MatchCriteriaTypeGroup), + Kind: &kind, + }, + { + Label: string(match_parser.MatchCriteriaTypeHost), + Kind: &kind, + }, + { + Label: string(match_parser.MatchCriteriaTypeAddress), + Kind: &kind, + }, + { + Label: string(match_parser.MatchCriteriaTypeLocalAddress), + Kind: &kind, + }, + { + Label: string(match_parser.MatchCriteriaTypeLocalPort), + Kind: &kind, + }, + { + Label: string(match_parser.MatchCriteriaTypeRDomain), + Kind: &kind, + }, + } +} + +func getMatchAllKeywordCompletion() protocol.CompletionItem { + kind := protocol.CompletionItemKindKeyword + + return protocol.CompletionItem{ + Label: "all", + Kind: &kind, + } +} + +func getMatchValueCompletions( + entry *match_parser.MatchEntry, + cursor uint32, +) []protocol.CompletionItem { + value := entry.GetValueByCursor(entry.End.Character) + + var line string + var relativeCursor uint32 + + if value != nil { + line = value.Value + relativeCursor = cursor - value.Start.Character + } else { + line = "" + relativeCursor = 0 + } + + switch entry.Criteria.Type { + case match_parser.MatchCriteriaTypeUser: + return fields.MatchUserField.FetchCompletions(line, relativeCursor) + case match_parser.MatchCriteriaTypeGroup: + return fields.MatchGroupField.FetchCompletions(line, relativeCursor) + case match_parser.MatchCriteriaTypeHost: + return fields.MatchHostField.FetchCompletions(line, relativeCursor) + case match_parser.MatchCriteriaTypeAddress: + return fields.MatchAddressField.FetchCompletions(line, relativeCursor) + case match_parser.MatchCriteriaTypeLocalAddress: + return fields.MatchLocalAddressField.FetchCompletions(line, relativeCursor) + case match_parser.MatchCriteriaTypeLocalPort: + return fields.MatchLocalPortField.FetchCompletions(line, relativeCursor) + case match_parser.MatchCriteriaTypeRDomain: + return fields.MatchRDomainField.FetchCompletions(line, relativeCursor) + } + + return nil +} diff --git a/handlers/sshd_config/lsp/text-document-completion.go b/handlers/sshd_config/lsp/text-document-completion.go index db7fc30..c0d3e37 100644 --- a/handlers/sshd_config/lsp/text-document-completion.go +++ b/handlers/sshd_config/lsp/text-document-completion.go @@ -14,7 +14,7 @@ var isEmptyPattern = regexp.MustCompile(`^\s*$`) func TextDocumentCompletion(context *glsp.Context, params *protocol.CompletionParams) (any, error) { line := params.Position.Line - cursor := params.Position.Character + cursor := common.CursorToCharacterIndex(params.Position.Character) d := sshdconfig.DocumentParserMap[params.TextDocument.URI] @@ -27,7 +27,7 @@ func TextDocumentCompletion(context *glsp.Context, params *protocol.CompletionPa if entry == nil || entry.Separator == nil || entry.Key == nil || - (common.CursorToCharacterIndex(cursor)) <= entry.Key.End.Character { + cursor <= entry.Key.End.Character { return handlers.GetRootCompletions( d, @@ -37,10 +37,11 @@ func TextDocumentCompletion(context *glsp.Context, params *protocol.CompletionPa ) } - if entry.Separator != nil && cursor > entry.Separator.End.Character { + if entry.Separator != nil && cursor >= entry.Separator.End.Character { return handlers.GetOptionCompletions( d, entry, + matchBlock, cursor, ) } From 1bda1f76e0cca18358c518203ec9f3dedd617cb2 Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Sun, 15 Sep 2024 15:53:16 +0200 Subject: [PATCH 036/133] fix(sshd_config): Fix hover for match blocks --- handlers/sshd_config/handlers/hover.go | 4 +++- .../sshd_config/lsp/text-document-code-action.go | 14 -------------- handlers/sshd_config/lsp/text-document-hover.go | 7 ++++++- .../sshd_config/lsp/workspace-execute-command.go | 10 ---------- root-handler/text-document-code-action.go | 3 +-- 5 files changed, 10 insertions(+), 28 deletions(-) delete mode 100644 handlers/sshd_config/lsp/text-document-code-action.go delete mode 100644 handlers/sshd_config/lsp/workspace-execute-command.go diff --git a/handlers/sshd_config/handlers/hover.go b/handlers/sshd_config/handlers/hover.go index b18efa5..56a033a 100644 --- a/handlers/sshd_config/handlers/hover.go +++ b/handlers/sshd_config/handlers/hover.go @@ -12,11 +12,13 @@ import ( func GetHoverInfoForOption( option *ast.SSHOption, matchBlock *ast.SSHMatchBlock, + line uint32, cursor uint32, ) (*protocol.Hover, error) { var docValue *docvalues.DocumentationValue - if matchBlock == nil { + // Either root level or in the line of a match block + if matchBlock == nil || matchBlock.Start.Line == line { val := fields.Options[option.Key.Value] docValue = &val } else { diff --git a/handlers/sshd_config/lsp/text-document-code-action.go b/handlers/sshd_config/lsp/text-document-code-action.go deleted file mode 100644 index 37950bd..0000000 --- a/handlers/sshd_config/lsp/text-document-code-action.go +++ /dev/null @@ -1,14 +0,0 @@ -package lsp - -import ( - "github.com/tliron/glsp" - protocol "github.com/tliron/glsp/protocol_3_16" -) - -func TextDocumentCodeAction(context *glsp.Context, params *protocol.CodeActionParams) ([]protocol.CodeAction, error) { - // document := hosts.DocumentParserMap[params.TextDocument.URI] - // - // actions := make([]protocol.CodeAction, 0, 1) - - return nil, nil -} diff --git a/handlers/sshd_config/lsp/text-document-hover.go b/handlers/sshd_config/lsp/text-document-hover.go index f6b5d96..1782116 100644 --- a/handlers/sshd_config/lsp/text-document-hover.go +++ b/handlers/sshd_config/lsp/text-document-hover.go @@ -24,5 +24,10 @@ func TextDocumentHover( return nil, nil } - return handlers.GetHoverInfoForOption(option, matchBlock, cursor) + return handlers.GetHoverInfoForOption( + option, + matchBlock, + line, + cursor, + ) } diff --git a/handlers/sshd_config/lsp/workspace-execute-command.go b/handlers/sshd_config/lsp/workspace-execute-command.go deleted file mode 100644 index f2f39d0..0000000 --- a/handlers/sshd_config/lsp/workspace-execute-command.go +++ /dev/null @@ -1,10 +0,0 @@ -package lsp - -import ( - "github.com/tliron/glsp" - protocol "github.com/tliron/glsp/protocol_3_16" -) - -func WorkspaceExecuteCommand(context *glsp.Context, params *protocol.ExecuteCommandParams) (*protocol.ApplyWorkspaceEditParams, error) { - return nil, nil -} diff --git a/root-handler/text-document-code-action.go b/root-handler/text-document-code-action.go index a9d3d33..f1da029 100644 --- a/root-handler/text-document-code-action.go +++ b/root-handler/text-document-code-action.go @@ -3,7 +3,6 @@ package roothandler import ( aliases "config-lsp/handlers/aliases/lsp" hosts "config-lsp/handlers/hosts/lsp" - sshdconfig "config-lsp/handlers/sshd_config/lsp" wireguard "config-lsp/handlers/wireguard/lsp" "github.com/tliron/glsp" @@ -29,7 +28,7 @@ func TextDocumentCodeAction(context *glsp.Context, params *protocol.CodeActionPa case LanguageHosts: return hosts.TextDocumentCodeAction(context, params) case LanguageSSHDConfig: - return sshdconfig.TextDocumentCodeAction(context, params) + return nil, nil case LanguageWireguard: return wireguard.TextDocumentCodeAction(context, params) case LanguageAliases: From e18d57074dd5a23e0e48af50a905c742ad79ff31 Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Sun, 15 Sep 2024 18:07:57 +0200 Subject: [PATCH 037/133] fix: Fix tests --- .github/workflows/pr-tests.yaml | 4 ++-- flake.nix | 2 +- handlers/wireguard/commands/wg-commands_test.go | 8 ++++++++ 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.github/workflows/pr-tests.yaml b/.github/workflows/pr-tests.yaml index 71a2213..02eee42 100644 --- a/.github/workflows/pr-tests.yaml +++ b/.github/workflows/pr-tests.yaml @@ -19,6 +19,6 @@ jobs: - name: Check Nix flake run: nix flake check - - name: Run tests - run: nix develop --command bash -c 'go test ./...' + - name: Build app + run: nix build -L diff --git a/flake.nix b/flake.nix index e0ffd36..d9d7af0 100644 --- a/flake.nix +++ b/flake.nix @@ -34,7 +34,7 @@ pname = "github.com/Myzel394/config-lsp"; version = "v0.0.1"; src = ./.; - vendorHash = "sha256-KhyqogTyb3jNrGP+0Zmn/nfx+WxzjgcrFOp2vivFgT0="; + vendorHash = "sha256-PUVmhdbmfy1FaSzLt3SIK0MtWezsjb+PL+Z5YxMMhdw="; checkPhase = '' go test -v $(pwd)/... ''; diff --git a/handlers/wireguard/commands/wg-commands_test.go b/handlers/wireguard/commands/wg-commands_test.go index 350cf91..874b840 100644 --- a/handlers/wireguard/commands/wg-commands_test.go +++ b/handlers/wireguard/commands/wg-commands_test.go @@ -13,6 +13,10 @@ func TestWireguardAvailable( func TestWireguardPrivateKey( t *testing.T, ) { + if !AreWireguardToolsAvailable() { + t.Skip("Wireguard tools not available") + } + privateKey, err := CreateNewPrivateKey() if err != nil { @@ -25,6 +29,10 @@ func TestWireguardPrivateKey( func TestWireguardPublicKey( t *testing.T, ) { + if !AreWireguardToolsAvailable() { + t.Skip("Wireguard tools not available") + } + privateKey := "UPBKR0kLF2C/+Ei5fwN5KHsAcon9xfBX+RWhebYFGWg=" publicKey, err := CreatePublicKey(privateKey) From 3983191c6e8f2307ba4a20b4a604c43205e11763 Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Sun, 15 Sep 2024 19:03:07 +0200 Subject: [PATCH 038/133] chore: Add documentation; Add GitHub issue template --- .github/ISSUE_TEMPLATE/1_new_config.yaml | 63 ++++++++++++++++++++++++ README.md | 14 ++++++ 2 files changed, 77 insertions(+) create mode 100644 .github/ISSUE_TEMPLATE/1_new_config.yaml create mode 100644 README.md diff --git a/.github/ISSUE_TEMPLATE/1_new_config.yaml b/.github/ISSUE_TEMPLATE/1_new_config.yaml new file mode 100644 index 0000000..e46b1fb --- /dev/null +++ b/.github/ISSUE_TEMPLATE/1_new_config.yaml @@ -0,0 +1,63 @@ +name: New Config Request +description: Suggest support for a new config +labels: [new-config] +body: + - type: markdown + attributes: + value: | + # Thank you for suggesting a new config! + + As implementing a new config requires a lot of work, make sure to provide as much information as possible to help understand the request. + This is not a 1-minute issue that can be done quickly without any work. We are distributing some work to you so that the maintainers can focus on implementing the actual LSP instead of spending time searching for documentation, examples, etc. If it takes you between 10 - 30 minutes to fill out this form, you are saving the maintainers hours of work. + + - type: checkboxes + attributes: + label: You must fill out all the fields + options: + - label: I understand that this issue may be closed without any notice if the template is not filled out correctly + required: true + + - label: I've checked that I'm using the latest version of config-lsp + required: true + + - type: input + attributes: + label: Program + description: Provide the URL of the program's official website + placeholder: https://www.openssh.com/ + + - type: textarea + id: description + attributes: + label: Description + description: Describe the purpose of the program and the config file and what it is used for + placeholder: Your description here + + - type: textarea + id: documentation + attributes: + label: Documentation + description: Enter the URL of the official documentation for the config. If the program provides a manpage, you may specify this as well. Do not link to the site https://linux.die.net/ - use alternatives instead. + placeholder: https://man.openbsd.org/ssh_config.5 + + - type: textarea + id: examples + attributes: + label: Examples + description: Provide *at least* 3 examples of the config file. One simple example, one (theoretical) complex example, and one real-world example. If the examples contain real data, you may anonymize the values but try to keep the structure intact. + placeholder: Your examples here + + - type: textarea + id: tutorial + attributes: + label: Tutorial + description: Provide a step-by-step tutorial on how to use the config file and get the program up and running. If there are any specific settings that are required, mention them as well. + placeholder: Your tutorial here + + - type: textarea + id: additional + attributes: + label: Additional Information + description: Provide any additional information that you think is relevant to the config file. This can be anything from specific use-cases to known issues. + placeholder: Your additional information here + diff --git a/README.md b/README.md new file mode 100644 index 0000000..17a2e9e --- /dev/null +++ b/README.md @@ -0,0 +1,14 @@ +## Supported Features + +| | diagnostics | `completion` | `hover` | `code-action` | `definition` | `rename` | `signature-help` | +|-------------|-------------|--------------|---------|---------------|--------------|----------|------------------| +| aliases | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | +| fstab | ✅ | ✅ | ✅ | ❓ | ❓ | ❓ | 🟡 | +| hosts | ✅ | ✅ | ✅ | ✅ | ❓ | ❓ | 🟡 | +| sshd_config | ✅ | ✅ | ✅ | ❓ | ✅ | ❓ | 🟡 | +| wireguard | ✅ | ✅ | ✅ | ✅ | ❓ | ❓ | 🟡 | + +✅ = Supported +🟡 = Will be supported, but not yet implemented +❓ = No idea what to implement here, please let me know if you have any ideas + From 473fca2e819f0fb445f456a94f7a2f21be7a9db4 Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Sun, 15 Sep 2024 19:03:17 +0200 Subject: [PATCH 039/133] chore: Remove unused openssh --- handlers/openssh/analyzer.go | 28 - handlers/openssh/diagnose-ssh-options.go | 67 -- handlers/openssh/diagnostics.go | 47 - handlers/openssh/documentation-common.go | 26 - handlers/openssh/documentation-utils.go | 96 -- handlers/openssh/documentation.go | 897 ------------------- handlers/openssh/parser.go | 146 --- handlers/openssh/shared.go | 19 - handlers/openssh/text-document-completion.go | 62 -- handlers/openssh/text-document-did-change.go | 24 - handlers/openssh/text-document-did-open.go | 25 - handlers/openssh/utils.go | 5 - handlers/openssh/value-data-amount-value.go | 97 -- handlers/openssh/value-time-format.go | 111 --- 14 files changed, 1650 deletions(-) delete mode 100644 handlers/openssh/analyzer.go delete mode 100644 handlers/openssh/diagnose-ssh-options.go delete mode 100644 handlers/openssh/diagnostics.go delete mode 100644 handlers/openssh/documentation-common.go delete mode 100644 handlers/openssh/documentation-utils.go delete mode 100644 handlers/openssh/documentation.go delete mode 100644 handlers/openssh/parser.go delete mode 100644 handlers/openssh/shared.go delete mode 100644 handlers/openssh/text-document-completion.go delete mode 100644 handlers/openssh/text-document-did-change.go delete mode 100644 handlers/openssh/text-document-did-open.go delete mode 100644 handlers/openssh/utils.go delete mode 100644 handlers/openssh/value-data-amount-value.go delete mode 100644 handlers/openssh/value-time-format.go diff --git a/handlers/openssh/analyzer.go b/handlers/openssh/analyzer.go deleted file mode 100644 index 52ad3d5..0000000 --- a/handlers/openssh/analyzer.go +++ /dev/null @@ -1,28 +0,0 @@ -package openssh - -import ( - docvalues "config-lsp/doc-values" -) - -func AnalyzeValues( - parser SimpleConfigParser, - availableOptions map[string]Option, -) []docvalues.ValueError { - errors := make([]docvalues.ValueError, 0) - - for optionName, line := range parser.Lines { - documentationOption := availableOptions[optionName] - - err := documentationOption.Value.CheckIsValid(line.Value) - - if err != nil { - errors = append(errors, docvalues.ValueError{ - Line: line.Position.Line, - Option: optionName, - Value: line.Value, - }) - } - } - - return errors -} diff --git a/handlers/openssh/diagnose-ssh-options.go b/handlers/openssh/diagnose-ssh-options.go deleted file mode 100644 index 3591318..0000000 --- a/handlers/openssh/diagnose-ssh-options.go +++ /dev/null @@ -1,67 +0,0 @@ -package openssh - -import ( - "github.com/tliron/glsp" - protocol "github.com/tliron/glsp/protocol_3_16" -) - -func DiagnoseSSHOptions( - context *glsp.Context, - documentURI protocol.DocumentUri, - parser *SimpleConfigParser, -) []protocol.Diagnostic { - diagnostics := make([]protocol.Diagnostic, 0) - - diagnostics = append( - diagnostics, - DiagnoseOption( - context, - documentURI, - parser, - "Port", - func(value string, position SimpleConfigPosition) []protocol.Diagnostic { - if value == "22" { - severity := protocol.DiagnosticSeverityWarning - - return []protocol.Diagnostic{ - { - Range: protocol.Range{ - Start: protocol.Position{ - Line: position.Line, - Character: uint32(len("Port ")), - }, - End: protocol.Position{ - Line: position.Line, - Character: uint32(len("Port " + value)), - }, - }, - Severity: &severity, - Message: "Port should not be 22 as it's often enumarated by attackers", - }, - } - } - - return []protocol.Diagnostic{} - }, - )..., - ) - - return diagnostics -} - -func DiagnoseOption( - context *glsp.Context, - uri protocol.DocumentUri, - parser *SimpleConfigParser, - optionName string, - checkerFunc func(string, SimpleConfigPosition) []protocol.Diagnostic, -) []protocol.Diagnostic { - option, err := parser.GetOption(optionName) - - if err != nil { - // Nothing to diagnose - return nil - } - - return checkerFunc(option.Value, option.Position) -} diff --git a/handlers/openssh/diagnostics.go b/handlers/openssh/diagnostics.go deleted file mode 100644 index 2fe3c92..0000000 --- a/handlers/openssh/diagnostics.go +++ /dev/null @@ -1,47 +0,0 @@ -package openssh - -import ( - docvalues "config-lsp/doc-values" - "config-lsp/utils" - "github.com/tliron/glsp" - protocol "github.com/tliron/glsp/protocol_3_16" -) - -func DiagnoseParser( - context *glsp.Context, - documentURI protocol.DocumentUri, - content string, -) []protocol.Diagnostic { - diagnostics := make([]protocol.Diagnostic, 0) - - diagnostics = append( - diagnostics, - utils.Map( - Parser.ParseFromFile(content), - func(err docvalues.OptionError) protocol.Diagnostic { - return err.GetPublishDiagnosticsParams() - }, - )..., - ) - - diagnostics = append( - diagnostics, - utils.Map( - AnalyzeValues(Parser, Options), - func(err docvalues.ValueError) protocol.Diagnostic { - return err.GetPublishDiagnosticsParams() - }, - )..., - ) - - diagnostics = append( - diagnostics, - DiagnoseSSHOptions( - context, - documentURI, - &Parser, - )..., - ) - - return diagnostics -} diff --git a/handlers/openssh/documentation-common.go b/handlers/openssh/documentation-common.go deleted file mode 100644 index 5158146..0000000 --- a/handlers/openssh/documentation-common.go +++ /dev/null @@ -1,26 +0,0 @@ -package openssh - -import ( - docvalues "config-lsp/doc-values" - "strings" - - protocol "github.com/tliron/glsp/protocol_3_16" -) - -type Option struct { - Documentation string - Value docvalues.Value -} - -func GetDocumentation(o *Option) protocol.MarkupContent { - typeDescription := strings.Join(o.Value.GetTypeDescription(), "\n") - - return protocol.MarkupContent{ - Kind: protocol.MarkupKindPlainText, - Value: "### Type\n" + typeDescription + "\n\n---\n\n### Documentation\n" + o.Documentation, - } -} - -func NewOption(documentation string, value docvalues.Value) Option { - return Option{documentation, value} -} diff --git a/handlers/openssh/documentation-utils.go b/handlers/openssh/documentation-utils.go deleted file mode 100644 index 687f541..0000000 --- a/handlers/openssh/documentation-utils.go +++ /dev/null @@ -1,96 +0,0 @@ -package openssh - -import ( - docvalues "config-lsp/doc-values" - "config-lsp/utils" - "os/exec" - "strings" -) - -var BooleanEnumValue = docvalues.EnumValue{ - EnforceValues: true, - Values: []docvalues.EnumString{ - docvalues.CreateEnumString("yes"), - docvalues.CreateEnumString("no"), - }, -} - -var plusMinuxCaretPrefixes = []docvalues.Prefix{ - { - Prefix: "+", - Meaning: "Append to the default set", - }, - { - Prefix: "-", - Meaning: "Remove from the default set", - }, - { - Prefix: "^", - Meaning: "Place at the head of the default set", - }, -} - -var ChannelTimeoutExtractor = docvalues.ExtractKeyDuplicatesExtractor("=") -var SetEnvExtractor = docvalues.ExtractKeyDuplicatesExtractor("=") - -func PrefixPlusMinusCaret(values []docvalues.EnumString) docvalues.PrefixWithMeaningValue { - return docvalues.PrefixWithMeaningValue{ - Prefixes: []docvalues.Prefix{ - { - Prefix: "+", - Meaning: "Append to the default set", - }, - { - Prefix: "-", - Meaning: "Remove from the default set", - }, - { - Prefix: "^", - Meaning: "Place at the head of the default set", - }, - }, - SubValue: docvalues.ArrayValue{ - Separator: ",", - DuplicatesExtractor: &docvalues.SimpleDuplicatesExtractor, - SubValue: docvalues.EnumValue{ - Values: values, - }, - }, - } -} - -var _cachedQueries map[string][]docvalues.EnumString = make(map[string][]docvalues.EnumString) - -func queryValues(query string) ([]string, error) { - cmd := exec.Command("ssh", "-Q", query) - - output, err := cmd.Output() - - if err != nil { - return []string{}, err - } - - return strings.Split(string(output), "\n"), nil -} - -func QueryOpenSSHOptions( - query string, -) ([]docvalues.EnumString, error) { - var availableQueries []docvalues.EnumString - key := query - - if _cachedQueries[key] != nil && len(_cachedQueries[key]) > 0 { - return _cachedQueries[key], nil - } else { - availableRawQueries, err := queryValues(query) - availableQueries = utils.Map(availableRawQueries, docvalues.CreateEnumString) - - if err != nil { - return []docvalues.EnumString{}, err - } - - _cachedQueries[key] = availableQueries - } - - return availableQueries, nil -} diff --git a/handlers/openssh/documentation.go b/handlers/openssh/documentation.go deleted file mode 100644 index adb61d8..0000000 --- a/handlers/openssh/documentation.go +++ /dev/null @@ -1,897 +0,0 @@ -package openssh - -import ( - docvalues "config-lsp/doc-values" - "regexp" -) - -var ZERO = 0 -var MAX_PORT = 65535 -var MAX_FILE_MODE = 0777 - -var Options = map[string]Option{ - "AcceptEnv": NewOption( - `Specifies what environment variables sent by the client will be copied into the session's environ(7). See SendEnv and SetEnv in ssh_config(5) for how to configure the client. The TERM environment variable is always accepted whenever the client requests a pseudo-terminal as it is required by the protocol. Variables are specified by name, which may contain the wildcard characters ‘*’ and ‘?’. Multiple environment variables may be separated by whitespace or spread across multiple AcceptEnv directives. Be warned that some environment variables could be used to bypass restricted user environments. For this reason, care should be taken in the use of this directive. The default is not to accept any environment variables.`, - docvalues.StringValue{}, - ), - "AddressFamily": NewOption( - `Specifies which address family should be used by sshd(8). Valid arguments are any (the default), inet (use IPv4 only), or inet6 (use IPv6 only).`, - docvalues.EnumValue{ - EnforceValues: true, - Values: []docvalues.EnumString{ - docvalues.CreateEnumString("any"), - docvalues.CreateEnumString("inet"), - docvalues.CreateEnumString("inet6"), - }, - }, - ), - "AllowAgentForwarding": NewOption( - `Specifies whether ssh-agent(1) forwarding is permitted. The default is yes. Note that disabling agent forwarding does not improve security unless users are also denied shell access, as they can always install their own forwarders.`, - BooleanEnumValue, - ), - "AllowGroups": NewOption( - `This keyword can be followed by a list of group name patterns, separated by spaces. If specified, login is allowed only for users whose primary group or supplementary group list matches one of the patterns. Only group names are valid; a numerical group ID is not recognized. By default, login is allowed for all groups. The allow/deny groups directives are processed in the following order: DenyGroups, AllowGroups. - -See PATTERNS in ssh_config(5) for more information on patterns. This keyword may appear multiple times in sshd_config with each instance appending to the list.`, - docvalues.GroupValue(" ", false), - ), - "AllowStreamLocalForwarding": NewOption( - `Specifies whether StreamLocal (Unix-domain socket) forwarding is permitted. The available options are yes (the default) or all to allow StreamLocal forwarding, no to prevent all StreamLocal forwarding, local to allow local (from the perspective of ssh(1)) forwarding only or remote to allow remote forwarding only. Note that disabling StreamLocal forwarding does not improve security unless users are also denied shell access, as they can always install their own forwarders.`, - docvalues.EnumValue{ - EnforceValues: true, - Values: []docvalues.EnumString{ - docvalues.CreateEnumString("yes"), - docvalues.CreateEnumString("all"), - docvalues.CreateEnumString("no"), - docvalues.CreateEnumString("local"), - docvalues.CreateEnumString("remote"), - }, - }, - ), - "AllowTcpForwarding": NewOption( - `Specifies whether TCP forwarding is permitted. The available options are yes (the default) or all to allow TCP forwarding, no to prevent all TCP forwarding, local to allow local (from the perspective of ssh(1)) forwarding only or remote to allow remote forwarding only. Note that disabling TCP forwarding does not improve security unless users are also denied shell access, as they can always install their own forwarders.`, - docvalues.EnumValue{ - EnforceValues: true, - Values: []docvalues.EnumString{ - docvalues.CreateEnumString("yes"), - docvalues.CreateEnumString("all"), - docvalues.CreateEnumString("no"), - docvalues.CreateEnumString("local"), - docvalues.CreateEnumString("remote"), - }, - }, - ), - "AllowUsers": NewOption( - `This keyword can be followed by a list of user name patterns, separated by spaces. If specified, login is allowed only for user names that match one of the patterns. Only user names are valid; a numerical user ID is not recognized. By default, login is allowed for all users. If the pattern takes the form USER@HOST then USER and HOST are separately checked, restricting logins to particular users from particular hosts. HOST criteria may additionally contain addresses to match in CIDR address/masklen format. The allow/deny users directives are processed in the following order: DenyUsers, AllowUsers. - See PATTERNS in ssh_config(5) for more information on patterns. This keyword may appear multiple times in sshd_config with each instance appending to the list.`, - docvalues.UserValue(" ", false), - ), - "AuthenticationMethods": NewOption( - `Specifies the authentication methods that must be successfully completed for a user to be granted access. This option must be followed by one or more lists of comma-separated authentication method names, or by the single string any to indicate the default behaviour of accepting any single authentication method. If the default is overridden, then successful authentication requires completion of every method in at least one of these lists. - For example, "publickey,password publickey,keyboard-interactive" would require the user to complete public key authentication, followed by either password or keyboard interactive authentication. Only methods that are next in one or more lists are offered at each stage, so for this example it would not be possible to attempt password or keyboard-interactive authentication before public key. - For keyboard interactive authentication it is also possible to restrict authentication to a specific device by appending a colon followed by the device identifier bsdauth or pam. depending on the server configuration. For example, "keyboard-interactive:bsdauth" would restrict keyboard interactive authentication to the bsdauth device. - If the publickey method is listed more than once, sshd(8) verifies that keys that have been used successfully are not reused for subsequent authentications. For example, "publickey,publickey" requires successful authentication using two different public keys.PATTERNS - Note that each authentication method listed should also be explicitly enabled in the configuration. - The available authentication methods are: "gssapi-with-mic", "hostbased", "keyboard-interactive", "none" (used for access to password-less accounts when PermitEmptyPasswords is enabled), "password" and "publickey".`, - docvalues.OrValue{ - Values: []docvalues.Value{ - docvalues.EnumValue{ - EnforceValues: true, - Values: []docvalues.EnumString{ - docvalues.CreateEnumString("any"), - }, - }, - docvalues.ArrayValue{ - SubValue: docvalues.EnumValue{ - EnforceValues: true, - Values: []docvalues.EnumString{ - docvalues.CreateEnumString("none"), - - docvalues.CreateEnumString("password"), - docvalues.CreateEnumString("publickey"), - docvalues.CreateEnumString("gssapi-with-mic"), - docvalues.CreateEnumString("keyboard-interactive"), - docvalues.CreateEnumString("hostbased"), - - docvalues.CreateEnumString("password:bsdauth"), - docvalues.CreateEnumString("publickey:bsdauth"), - docvalues.CreateEnumString("gssapi-with-mic:bsdauth"), - docvalues.CreateEnumString("keyboard-interactive:bsdauth"), - docvalues.CreateEnumString("hostbased:bsdauth"), - - docvalues.CreateEnumString("password:pam"), - docvalues.CreateEnumString("publickey:pam"), - docvalues.CreateEnumString("gssapi-with-mic:pam"), - docvalues.CreateEnumString("keyboard-interactive:pam"), - docvalues.CreateEnumString("hostbased:pam"), - }, - }, - }, - }, - }, - ), - "AuthorizedKeysCommand": NewOption( - `Specifies a program to be used to look up the user's public keys. The program must be owned by root, not writable by group or others and specified by an absolute path. Arguments to AuthorizedKeysCommand accept the tokens described in the “TOKENS” section. If no arguments are specified then the username of the target user is used. - The program should produce on standard output zero or more lines of authorized_keys output (see “AUTHORIZED_KEYS” in sshd(8)). AuthorizedKeysCommand is tried after the usual AuthorizedKeysFile files and will not be executed if a matching key is found there. By default, no AuthorizedKeysCommand is run.`, - docvalues.StringValue{}, - ), - - "AuthorizedKeysCommandUser": NewOption( - `Specifies the user under whose account the AuthorizedKeysCommand is run. It is recommended to use a dedicated user that has no other role on the host than running authorized keys commands. If AuthorizedKeysCommand is specified but AuthorizedKeysCommandUser is not, then sshd(8) will refuse to start.`, - docvalues.UserValue("", true), - ), - "AuthorizedKeysFile": NewOption( - `Specifies the file that contains the public keys used for user authentication. The format is described in the AUTHORIZED_KEYS FILE FORMAT section of sshd(8). Arguments to AuthorizedKeysFile accept the tokens described in the “TOKENS” section. After expansion, AuthorizedKeysFile is taken to be an absolute path or one relative to the user's home directory. Multiple files may be listed, separated by whitespace. Alternately this option may be set to none to skip checking for user keys in files. The default is ".ssh/authorized_keys .ssh/authorized_keys2".`, - docvalues.ArrayValue{ - SubValue: docvalues.StringValue{}, - Separator: " ", - DuplicatesExtractor: &docvalues.DuplicatesAllowedExtractor, - }, - ), - "AuthorizedPrincipalsCommand": NewOption( - `Specifies a program to be used to generate the list of allowed certificate principals as per AuthorizedPrincipalsFile. The program must be owned by root, not writable by group or others and specified by an absolute path. Arguments to AuthorizedPrincipalsCommand accept the tokens described in the “TOKENS” section. If no arguments are specified then the username of the target user is used. - The program should produce on standard output zero or more lines of AuthorizedPrincipalsFile output. If either AuthorizedPrincipalsCommand or AuthorizedPrincipalsFile is specified, then certificates offered by the client for authentication must contain a principal that is listed. By default, no AuthorizedPrincipalsCommand is run.`, - docvalues.StringValue{}, - ), - "AuthorizedPrincipalsCommandUser": NewOption( - `Specifies the user under whose account the AuthorizedPrincipalsCommand is run. It is recommended to use a dedicated user that has no other role on the host than running authorized principals commands. If AuthorizedPrincipalsCommand is specified but AuthorizedPrincipalsCommandUser is not, then sshd(8) will refuse to start.`, - docvalues.UserValue("", true), - ), - "AuthorizedPrincipalsFile": NewOption( - `Specifies a file that lists principal names that are accepted for certificate authentication. When using certificates signed by a key listed in TrustedUserCAKeys, this file lists names, one of which must appear in the certificate for it to be accepted for authentication. Names are listed one per line preceded by key options (as described in “AUTHORIZED_KEYS FILE FORMAT” in sshd(8)). Empty lines and comments starting with ‘#’ are ignored. - Arguments to AuthorizedPrincipalsFile accept the tokens described in the “TOKENS” section. After expansion, AuthorizedPrincipalsFile is taken to be an absolute path or one relative to the user's home directory. The default is none, i.e. not to use a principals file – in this case, the username of the user must appear in a certificate's principals list for it to be accepted. - Note that AuthorizedPrincipalsFile is only used when authentication proceeds using a CA listed in TrustedUserCAKeys and is not consulted for certification authorities trusted via ~/.ssh/authorized_keys, though the principals= key option offers a similar facility (see sshd(8) for details).`, - docvalues.PathValue{ - RequiredType: docvalues.PathTypeFile, - }, - ), - "Banner": NewOption(`The contents of the specified file are sent to the remote user before authentication is allowed. If the argument is none then no banner is displayed. By default, no banner is displayed.`, - docvalues.PathValue{ - RequiredType: docvalues.PathTypeFile, - }, - ), - "CASignatureAlgorithms": NewOption( - `Specifies which algorithms are allowed for signing of certificates by certificate authorities (CAs). The default is: - ssh-ed25519,ecdsa-sha2-nistp256, ecdsa-sha2-nistp384,ecdsa-sha2-nistp521, sk-ssh-ed25519@openssh.com, sk-ecdsa-sha2-nistp256@openssh.com, rsa-sha2-512,rsa-sha2-256 - If the specified list begins with a ‘+’ character, then the specified algorithms will be appended to the default set instead of replacing them. If the specified list begins with a ‘-’ character, then the specified algorithms (including wildcards) will be removed from the default set instead of replacing them. - Certificates signed using other algorithms will not be accepted for public key or host-based authentication.`, - docvalues.PrefixWithMeaningValue{ - Prefixes: []docvalues.Prefix{ - { - Prefix: "+", - Meaning: "Appende to the default set", - }, - { - Prefix: "-", - Meaning: "Remove from the default set", - }, - }, - SubValue: docvalues.ArrayValue{ - Separator: ",", - DuplicatesExtractor: &docvalues.DuplicatesAllowedExtractor, - // TODO: Add - SubValue: docvalues.StringValue{}, - }, - }, - ), - "ChannelTimeout": NewOption(`Specifies whether and how quickly sshd(8) should close inactive channels. Timeouts are specified as one or more “type=interval” pairs separated by whitespace, where the “type” must be the special keyword “global” or a channel type name from the list below, optionally containing wildcard characters. - The timeout value “interval” is specified in seconds or may use any of the units documented in the “TIME FORMATS” section. For example, “session=5m” would cause interactive sessions to terminate after five minutes of inactivity. Specifying a zero value disables the inactivity timeout. - The special timeout “global” applies to all active channels, taken together. Traffic on any active channel will reset the timeout, but when the timeout expires then all open channels will be closed. Note that this global timeout is not matched by wildcards and must be specified explicitly. - The available channel type names include: - - agent-connection Open connections to ssh-agent(1). - direct-tcpip, direct-streamlocal@openssh.com Open TCP or Unix socket (respectively) connections that have been established from a ssh(1) local forwarding, i.e. LocalForward or DynamicForward. - forwarded-tcpip, forwarded-streamlocal@openssh.com Open TCP or Unix socket (respectively) connections that have been established to a sshd(8) listening on behalf of a ssh(1) remote forwarding, i.e. RemoteForward. - session The interactive main session, including shell session, command execution, scp(1), sftp(1), etc. - tun-connection Open TunnelForward connections. - x11-connection Open X11 forwarding sessions. - - Note that in all the above cases, terminating an inactive session does not guarantee to remove all resources associated with the session, e.g. shell processes or X11 clients relating to the session may continue to execute. - Moreover, terminating an inactive channel or session does not necessarily close the SSH connection, nor does it prevent a client from requesting another channel of the same type. In particular, expiring an inactive forwarding session does not prevent another identical forwarding from being subsequently created. - The default is not to expire channels of any type for inactivity.`, - docvalues.ArrayValue{ - Separator: " ", - DuplicatesExtractor: &ChannelTimeoutExtractor, - SubValue: docvalues.KeyValueAssignmentValue{ - ValueIsOptional: false, - Separator: "=", - Key: docvalues.EnumValue{ - Values: []docvalues.EnumString{ - docvalues.CreateEnumString("global"), - docvalues.CreateEnumString("agent-connection"), - docvalues.CreateEnumString("direct-tcpip"), - docvalues.CreateEnumString("direct-streamlocal@openssh.com"), - docvalues.CreateEnumString("forwarded-tcpip"), - docvalues.CreateEnumString("forwarded-streamlocal@openssh.com"), - docvalues.CreateEnumString("session"), - docvalues.CreateEnumString("tun-connection"), - docvalues.CreateEnumString("x11-connection"), - }, - }, - Value: TimeFormatValue{}, - }, - }, - ), - "ChrootDirectory": NewOption(`Specifies the pathname of a directory to chroot(2) to after authentication. At session startup sshd(8) checks that all components of the pathname are root-owned directories which are not writable by group or others. After the chroot, sshd(8) changes the working directory to the user's home directory. Arguments to ChrootDirectory accept the tokens described in the “TOKENS” section. - The ChrootDirectory must contain the necessary files and directories to support the user's session. For an interactive session this requires at least a shell, typically sh(1), and basic /dev nodes such as null(4), zero(4), stdin(4), stdout(4), stderr(4), and tty(4) devices. For file transfer sessions using SFTP no additional configuration of the environment is necessary if the in-process sftp-server is used, though sessions which use logging may require /dev/log inside the chroot directory on some operating systems (see sftp-server(8) for details). - For safety, it is very important that the directory hierarchy be prevented from modification by other processes on the system (especially those outside the jail). Misconfiguration can lead to unsafe environments which sshd(8) cannot detect. - The default is none, indicating not to chroot(2).`, - docvalues.StringValue{}, - ), - "Ciphers": NewOption(`Specifies the ciphers allowed. Multiple ciphers must be comma-separated. If the specified list begins with a ‘+’ character, then the specified ciphers will be appended to the default set instead of replacing them. If the specified list begins with a ‘-’ character, then the specified ciphers (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a ‘^’ character, then the specified ciphers will be placed at the head of the default set. - The supported ciphers are: - 3des-cbc aes128-cbc aes192-cbc aes256-cbc aes128-ctr aes192-ctr aes256-ctr aes128-gcm@openssh.com aes256-gcm@openssh.com chacha20-poly1305@openssh.com - The default is: - chacha20-poly1305@openssh.com, aes128-ctr,aes192-ctr,aes256-ctr, aes128-gcm@openssh.com,aes256-gcm@openssh.com - The list of available ciphers may also be obtained using "ssh -Q cipher".`, - PrefixPlusMinusCaret([]docvalues.EnumString{ - docvalues.CreateEnumString("3des-cbc"), - docvalues.CreateEnumString("aes128-cbc"), - docvalues.CreateEnumString("aes192-cbc"), - docvalues.CreateEnumString("aes256-cbc"), - docvalues.CreateEnumString("aes128-ctr"), - docvalues.CreateEnumString("aes192-ctr"), - docvalues.CreateEnumString("aes256-ctr"), - docvalues.CreateEnumString("aes128-gcm@openssh.com"), - docvalues.CreateEnumString("aes256-gcm@openssh.com"), - docvalues.CreateEnumString("chacha20-poly1305@openssh.com"), - }), - ), - "ClientAliveCountMax": NewOption(`Sets the number of client alive messages which may be sent without sshd(8) receiving any messages back from the client. If this threshold is reached while client alive messages are being sent, sshd will disconnect the client, terminating the session. It is important to note that the use of client alive messages is very different from TCPKeepAlive. The client alive messages are sent through the encrypted channel and therefore will not be spoofable. The TCP keepalive option enabled by TCPKeepAlive is spoofable. The client alive mechanism is valuable when the client or server depend on knowing when a connection has become unresponsive. - The default value is 3. If ClientAliveInterval is set to 15, and ClientAliveCountMax is left at the default, unresponsive SSH clients will be disconnected after approximately 45 seconds. Setting a zero ClientAliveCountMax disables connection termination.`, - docvalues.NumberValue{Min: &ZERO}, - ), - "ClientAliveInterval": NewOption( - `Sets a timeout interval in seconds after which if no data has been received from the client, sshd(8) will send a message through the encrypted channel to request a response from the client. The default is 0, indicating that these messages will not be sent to the client.`, - docvalues.NumberValue{Min: &ZERO}, - ), - "Compression": NewOption( - `Specifies whether compression is enabled after the user has authenticated successfully. The argument must be yes, delayed (a legacy synonym for yes) or no. The default is yes.`, - docvalues.EnumValue{ - EnforceValues: true, - Values: []docvalues.EnumString{ - docvalues.CreateEnumString("yes"), - docvalues.CreateEnumString("delayed"), - docvalues.CreateEnumString("no"), - }, - }, - ), - "DenyGroups": NewOption(`This keyword can be followed by a list of group name patterns, separated by spaces. Login is disallowed for users whose primary group or supplementary group list matches one of the patterns. Only group names are valid; a numerical group ID is not recognized. By default, login is allowed for all groups. The allow/deny groups directives are processed in the following order: DenyGroups, AllowGroups. - See PATTERNS in ssh_config(5) for more information on patterns. This keyword may appear multiple times in sshd_config with each instance appending to the list.`, - docvalues.GroupValue(" ", false), - ), - "DenyUsers": NewOption(`This keyword can be followed by a list of user name patterns, separated by spaces. Login is disallowed for user names that match one of the patterns. Only user names are valid; a numerical user ID is not recognized. By default, login is allowed for all users. If the pattern takes the form USER@HOST then USER and HOST are separately checked, restricting logins to particular users from particular hosts. HOST criteria may additionally contain addresses to match in CIDR address/masklen format. The allow/deny users directives are processed in the following order: DenyUsers, AllowUsers. - See PATTERNS in ssh_config(5) for more information on patterns. This keyword may appear multiple times in sshd_config with each instance appending to the list.`, - docvalues.UserValue(" ", false), - ), - "DisableForwarding": NewOption( - `Disables all forwarding features, including X11, ssh-agent(1), TCP and StreamLocal. This option overrides all other forwarding-related options and may simplify restricted configurations.`, - BooleanEnumValue, - ), - "ExposeAuthInfo": NewOption( - `Writes a temporary file containing a list of authentication methods and public credentials (e.g. keys) used to authenticate the user. The location of the file is exposed to the user session through the SSH_USER_AUTH environment variable. The default is no.`, - BooleanEnumValue, - ), - "FingerprintHash": NewOption( - `Specifies the hash algorithm used when logging key fingerprints. Valid options are: md5 and sha256. The default is sha256.`, - docvalues.EnumValue{ - EnforceValues: true, - Values: []docvalues.EnumString{ - docvalues.CreateEnumString("md5"), - docvalues.CreateEnumString("sha256"), - }, - }, - ), - "ForceCommand": NewOption( - `Forces the execution of the command specified by ForceCommand, ignoring any command supplied by the client and ~/.ssh/rc if present. The command is invoked by using the user's login shell with the -c option. This applies to shell, command, or subsystem execution. It is most useful inside a Match block. The command originally supplied by the client is available in the SSH_ORIGINAL_COMMAND environment variable. Specifying a command of internal-sftp will force the use of an in- process SFTP server that requires no support files when used with ChrootDirectory. The default is none.`, - docvalues.StringValue{}, - ), - "GatewayPorts": NewOption( - `Specifies whether remote hosts are allowed to connect to ports forwarded for the client. By default, sshd(8) binds remote port forwardings to the loopback address. This prevents other remote hosts from connecting to forwarded ports. GatewayPorts can be used to specify that sshd should allow remote port forwardings to bind to non-loopback addresses, thus allowing other hosts to connect. The argument may be no to force remote port forwardings to be available to the local host only, yes to force remote port forwardings to bind to the wildcard address, or clientspecified to allow the client to select the address to which the forwarding is bound. The default is no.`, - BooleanEnumValue, - ), - "GSSAPIAuthentication": NewOption( - `Specifies whether user authentication based on GSSAPI is allowed. The default is no.`, - BooleanEnumValue, - ), - "GSSAPICleanupCredentials": NewOption( - `Specifies whether to automatically destroy the user's credentials cache on logout. The default is yes.`, - BooleanEnumValue, - ), - "GSSAPIStrictAcceptorCheck": NewOption( - `Determines whether to be strict about the identity of the GSSAPI acceptor a client authenticates against. If set to yes then the client must authenticate against the host service on the current hostname. If set to no then the client may authenticate against any service key stored in the machine's default store. This facility is provided to assist with operation on multi homed machines. The default is yes.`, - BooleanEnumValue, - ), - "HostbasedAcceptedAlgorithms": NewOption(`Specifies the signature algorithms that will be accepted for hostbased authentication as a list of comma-separated patterns. Alternately if the specified list begins with a ‘+’ character, then the specified signature algorithms will be appended to the default set instead of replacing them. If the specified list begins with a ‘-’ character, then the specified signature algorithms (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a ‘^’ character, then the specified signature algorithms will be placed at the head of the default set. The default for this option is: - ssh-ed25519-cert-v01@openssh.com, ecdsa-sha2-nistp256-cert-v01@openssh.com, ecdsa-sha2-nistp384-cert-v01@openssh.com, ecdsa-sha2-nistp521-cert-v01@openssh.com, sk-ssh-ed25519-cert-v01@openssh.com, sk-ecdsa-sha2-nistp256-cert-v01@openssh.com, rsa-sha2-512-cert-v01@openssh.com, rsa-sha2-256-cert-v01@openssh.com, ssh-ed25519, ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521, sk-ssh-ed25519@openssh.com, sk-ecdsa-sha2-nistp256@openssh.com, rsa-sha2-512,rsa-sha2-256 - The list of available signature algorithms may also be obtained using "ssh -Q HostbasedAcceptedAlgorithms". This was formerly named HostbasedAcceptedKeyTypes.`, - docvalues.CustomValue{ - FetchValue: func(_ docvalues.CustomValueContext) docvalues.Value { - options, err := QueryOpenSSHOptions("HostbasedAcceptedAlgorithms") - - if err != nil { - // Fallback - options, _ = QueryOpenSSHOptions("HostbasedAcceptedKeyTypes") - } - - return PrefixPlusMinusCaret(options) - }, - }, - ), - "HostbasedAuthentication": NewOption( - `Specifies whether rhosts or /etc/hosts.equiv authentication together with successful public key client host authentication is allowed (host-based authentication). The default is no.`, - BooleanEnumValue, - ), - "HostbasedUsesNameFromPacketOnly": NewOption( - `Specifies whether or not the server will attempt to perform a reverse name lookup when matching the name in the ~/.shosts, ~/.rhosts, and /etc/hosts.equiv files during HostbasedAuthentication. A setting of yes means that sshd(8) uses the name supplied by the client rather than attempting to resolve the name from the TCP connection itself. The default is no.`, - BooleanEnumValue, - ), - "HostCertificate": NewOption( - `Specifies a file containing a public host certificate. The certificate's public key must match a private host key already specified by HostKey. The default behaviour of sshd(8) is not to load any certificates.`, - docvalues.PathValue{}, - ), - "HostKey": NewOption(`Specifies a file containing a private host key used by SSH. The defaults are /etc/ssh/ssh_host_ecdsa_key, /etc/ssh/ssh_host_ed25519_key and /etc/ssh/ssh_host_rsa_key. - Note that sshd(8) will refuse to use a file if it is group/world-accessible and that the HostKeyAlgorithms option restricts which of the keys are actually used by sshd(8). - It is possible to have multiple host key files. It is also possible to specify public host key files instead. In this case operations on the private key will be delegated to an ssh-agent(1).`, - docvalues.PathValue{}, - ), - "HostKeyAgent": NewOption( - `Identifies the UNIX-domain socket used to communicate with an agent that has access to the private host keys. If the string "SSH_AUTH_SOCK" is specified, the location of the socket will be read from the SSH_AUTH_SOCK environment variable.`, - docvalues.OrValue{ - Values: []docvalues.Value{ - docvalues.EnumValue{ - EnforceValues: true, - Values: []docvalues.EnumString{ - docvalues.CreateEnumStringWithDoc("SSH_AUTH_SOCK", "The location of the socket will be read from the SSH_AUTH_SOCK environment variable."), - }, - }, - docvalues.StringValue{}, - }, - }, - ), - "HostKeyAlgorithms": NewOption(`Specifies the host key signature algorithms that the server offers. The default for this option is: - ssh-ed25519-cert-v01@openssh.com, ecdsa-sha2-nistp256-cert-v01@openssh.com, ecdsa-sha2-nistp384-cert-v01@openssh.com, ecdsa-sha2-nistp521-cert-v01@openssh.com, sk-ssh-ed25519-cert-v01@openssh.com, sk-ecdsa-sha2-nistp256-cert-v01@openssh.com, rsa-sha2-512-cert-v01@openssh.com, rsa-sha2-256-cert-v01@openssh.com, ssh-ed25519, ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521, sk-ssh-ed25519@openssh.com, sk-ecdsa-sha2-nistp256@openssh.com, rsa-sha2-512,rsa-sha2-256 - The list of available signature algorithms may also be obtained using "ssh -Q HostKeyAlgorithms".`, - docvalues.CustomValue{ - FetchValue: func(_ docvalues.CustomValueContext) docvalues.Value { - options, _ := QueryOpenSSHOptions("HostKeyAlgorithms") - - return PrefixPlusMinusCaret(options) - }, - }, - ), - "IgnoreRhosts": NewOption(`Specifies whether to ignore per-user .rhosts and .shosts files during HostbasedAuthentication. The system-wide /etc/hosts.equiv and /etc/shosts.equiv are still used regardless of this setting. - Accepted values are yes (the default) to ignore all per- user files, shosts-only to allow the use of .shosts but to ignore .rhosts or no to allow both .shosts and rhosts.`, - docvalues.EnumValue{ - EnforceValues: true, - Values: []docvalues.EnumString{ - docvalues.CreateEnumString("yes"), - docvalues.CreateEnumString("shosts-only"), - docvalues.CreateEnumString("no"), - }, - }, - ), - "IgnoreUserKnownHosts": NewOption( - `Specifies whether sshd(8) should ignore the user's ~/.ssh/known_hosts during HostbasedAuthentication and use only the system-wide known hosts file /etc/ssh/ssh_known_hosts. The default is “no”.`, - BooleanEnumValue, - ), - "Include": NewOption(`Include the specified configuration file(s). Multiple pathnames may be specified and each pathname may contain glob(7) wildcards that will be expanded and processed in lexical order. Files without absolute paths are assumed to be in /etc/ssh. An Include directive may appear inside a Match block to perform conditional inclusion.`, - docvalues.ArrayValue{ - Separator: " ", - DuplicatesExtractor: &docvalues.SimpleDuplicatesExtractor, - SubValue: docvalues.PathValue{ - RequiredType: docvalues.PathTypeFile, - }, - }, - // TODO: Add extra check - ), - - "IPQoS": NewOption(`Specifies the IPv4 type-of-service or DSCP class for the connection. Accepted values are af11, af12, af13, af21, af22, af23, af31, af32, af33, af41, af42, af43, cs0, cs1, cs2, cs3, cs4, cs5, cs6, cs7, ef, le, lowdelay, throughput, reliability, a numeric value, or none to use the operating system default. This option may take one or two arguments, separated by whitespace. If one argument is specified, it is used as the packet class unconditionally. If two values are specified, the first is automatically selected for interactive sessions and the second for non-interactive sessions. The default is af21 (Low-Latency Data) for interactive sessions and cs1 (Lower Effort) for non-interactive sessions.`, - docvalues.OrValue{ - Values: []docvalues.Value{ - docvalues.NumberValue{}, - docvalues.EnumValue{ - Values: []docvalues.EnumString{ - docvalues.CreateEnumString("none"), - }, - }, - docvalues.ArrayValue{ - Separator: " ", - SubValue: docvalues.EnumValue{ - EnforceValues: true, - Values: []docvalues.EnumString{ - docvalues.CreateEnumString("af11"), - docvalues.CreateEnumString("af12"), - docvalues.CreateEnumString("af13"), - docvalues.CreateEnumString("af21"), - docvalues.CreateEnumString("af22"), - docvalues.CreateEnumString("af23"), - docvalues.CreateEnumString("af31"), - docvalues.CreateEnumString("af32"), - docvalues.CreateEnumString("af33"), - docvalues.CreateEnumString("af41"), - docvalues.CreateEnumString("af42"), - docvalues.CreateEnumString("af43"), - docvalues.CreateEnumString("cs0"), - docvalues.CreateEnumString("cs1"), - docvalues.CreateEnumString("cs2"), - docvalues.CreateEnumString("cs3"), - docvalues.CreateEnumString("cs4"), - docvalues.CreateEnumString("cs5"), - docvalues.CreateEnumString("cs6"), - docvalues.CreateEnumString("cs7"), - docvalues.CreateEnumString("ef"), - docvalues.CreateEnumString("le"), - docvalues.CreateEnumString("lowdelay"), - docvalues.CreateEnumString("throughput"), - docvalues.CreateEnumString("reliability"), - docvalues.CreateEnumString("none"), - }, - }, - }, - }, - }, - ), - "KbdInteractiveAuthentication": NewOption( - `Specifies whether to allow keyboard-interactive authentication. All authentication styles from login.conf(5) are supported. The default is yes. The argument to this keyword must be yes or no. ChallengeResponseAuthentication is a deprecated alias for this.`, - BooleanEnumValue, - ), - "KerberosAuthentication": NewOption(`Specifies whether the password provided by the user for PasswordAuthentication will be validated through the Kerberos KDC. To use this option, the server needs a Kerberos servtab which allows the verification of the KDC's identity. The default is no.`, - BooleanEnumValue, - ), - "KerberosGetAFSToken": NewOption(`If AFS is active and the user has a Kerberos 5 TGT, attempt to acquire an AFS token before accessing the user's home directory. The default is no.`, - BooleanEnumValue, - ), - "KerberosOrLocalPasswd": NewOption(`If password authentication through Kerberos fails then the password will be validated via any additional local mechanism such as /etc/passwd. The default is yes.`, - BooleanEnumValue, - ), - "KerberosTicketCleanup": NewOption(`Specifies whether to automatically destroy the user's ticket cache file on logout. The default is yes.`, - BooleanEnumValue, - ), - "KexAlgorithms": NewOption(`Specifies the available KEX (Key Exchange) algorithms. Multiple algorithms must be comma-separated. Alternately if the specified list begins with a ‘+’ character, then the specified algorithms will be appended to the default set instead of replacing them. If the specified list begins with a ‘-’ character, then the specified algorithms (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a ‘^’ character, then the specified algorithms will be placed at the head of the default set. The supported algorithms are: - curve25519-sha256 curve25519-sha256@libssh.org diffie-hellman-group1-sha1 diffie-hellman-group14-sha1 diffie-hellman-group14-sha256 diffie-hellman-group16-sha512 diffie-hellman-group18-sha512 diffie-hellman-group-exchange-sha1 diffie-hellman-group-exchange-sha256 ecdh-sha2-nistp256 ecdh-sha2-nistp384 ecdh-sha2-nistp521 sntrup761x25519-sha512@openssh.com - The default is: - sntrup761x25519-sha512@openssh.com, curve25519-sha256,curve25519-sha256@libssh.org, ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521, diffie-hellman-group-exchange-sha256, diffie-hellman-group16-sha512,diffie-hellman-group18-sha512, diffie-hellman-group14-sha256 - The list of available key exchange algorithms may also be obtained using "ssh -Q KexAlgorithms".`, - PrefixPlusMinusCaret([]docvalues.EnumString{ - docvalues.CreateEnumString("curve25519-sha256"), - docvalues.CreateEnumString("curve25519-sha256@libssh.org"), - docvalues.CreateEnumString("diffie-hellman-group1-sha1"), - docvalues.CreateEnumString("diffie-hellman-group14-sha1"), - docvalues.CreateEnumString("diffie-hellman-group14-sha256"), - docvalues.CreateEnumString("diffie-hellman-group16-sha512"), - docvalues.CreateEnumString("diffie-hellman-group18-sha512"), - docvalues.CreateEnumString("diffie-hellman-group-exchange-sha1"), - docvalues.CreateEnumString("diffie-hellman-group-exchange-sha256"), - docvalues.CreateEnumString("ecdh-sha2-nistp256"), - docvalues.CreateEnumString("ecdh-sha2-nistp384"), - docvalues.CreateEnumString("ecdh-sha2-nistp521"), - docvalues.CreateEnumString("sntrup761x25519-sha512@openssh.com"), - }), - ), - "ListenAddress": NewOption(`Specifies the local addresses sshd(8) should listen on. The following forms may be used: - ListenAddress hostname|address [rdomain domain] ListenAddress hostname:port [rdomain domain] ListenAddress IPv4_address:port [rdomain domain] ListenAddress [hostname|address]:port [rdomain domain] - The optional rdomain qualifier requests sshd(8) listen in an explicit routing domain. If port is not specified, sshd will listen on the address and all Port options specified. The default is to listen on all local addresses on the current default routing domain. Multiple ListenAddress options are permitted. For more information on routing domains, see rdomain(4).`, - docvalues.KeyValueAssignmentValue{ - ValueIsOptional: true, - Key: docvalues.IPAddressValue{ - AllowIPv4: true, - AllowIPv6: true, - AllowRange: false, - DisallowedIPs: &docvalues.NonRoutableNetworks, - }, - Separator: ":", - Value: docvalues.NumberValue{Min: &ZERO, Max: &MAX_PORT}, - }, - ), - "LoginGraceTime": NewOption(`The server disconnects after this time if the user has not successfully logged in. If the value is 0, there is no time limit. The default is 120 seconds.`, - TimeFormatValue{}, - ), - "LogLevel": NewOption(`Gives the verbosity level that is used when logging messages from sshd(8). The possible values are: QUIET, FATAL, ERROR, INFO, VERBOSE, DEBUG, DEBUG1, DEBUG2, and DEBUG3. The default is INFO. DEBUG and DEBUG1 are equivalent. DEBUG2 and DEBUG3 each specify higher levels of debugging output. Logging with a DEBUG level violates the privacy of users and is not recommended.`, - docvalues.EnumValue{ - EnforceValues: true, - Values: []docvalues.EnumString{ - docvalues.CreateEnumString("QUIET"), - docvalues.CreateEnumString("FATAL"), - docvalues.CreateEnumString("ERROR"), - docvalues.CreateEnumString("INFO"), - docvalues.CreateEnumString("VERBOSE"), - docvalues.CreateEnumString("DEBUG"), - docvalues.CreateEnumString("DEBUG1"), - docvalues.CreateEnumString("DEBUG2"), - docvalues.CreateEnumString("DEBUG3"), - }, - }, - ), - "LogVerbose": NewOption(`Specify one or more overrides to LogLevel. An override consists of a pattern lists that matches the source file, function and line number to force detailed logging for. For example, an override pattern of: - kex.c:*:1000,*:kex_exchange_identification():*,packet.c:* - would enable detailed logging for line 1000 of kex.c, everything in the kex_exchange_identification() function, and all code in the packet.c file. This option is intended for debugging and no overrides are enabled by default.`, - docvalues.StringValue{}, - ), - - "MACs": NewOption(`Specifies the available MAC (message authentication code) algorithms. The MAC algorithm is used for data integrity protection. Multiple algorithms must be comma-separated. If the specified list begins with a ‘+’ character, then the specified algorithms will be appended to the default set instead of replacing them. If the specified list begins with a ‘-’ character, then the specified algorithms (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a ‘^’ character, then the specified algorithms will be placed at the head of the default set. - The algorithms that contain "-etm" calculate the MAC after encryption (encrypt-then-mac). These are considered safer and their use recommended. The supported MACs are: - hmac-md5 hmac-md5-96 hmac-sha1 hmac-sha1-96 hmac-sha2-256 hmac-sha2-512 umac-64@openssh.com umac-128@openssh.com hmac-md5-etm@openssh.com hmac-md5-96-etm@openssh.com hmac-sha1-etm@openssh.com hmac-sha1-96-etm@openssh.com hmac-sha2-256-etm@openssh.com hmac-sha2-512-etm@openssh.com umac-64-etm@openssh.com umac-128-etm@openssh.com - The default is: - umac-64-etm@openssh.com,umac-128-etm@openssh.com, hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com, hmac-sha1-etm@openssh.com, umac-64@openssh.com,umac-128@openssh.com, hmac-sha2-256,hmac-sha2-512,hmac-sha1 - The list of available MAC algorithms may also be obtained using "ssh -Q mac".`, - PrefixPlusMinusCaret([]docvalues.EnumString{ - docvalues.CreateEnumString("hmac-md5"), - docvalues.CreateEnumString("hmac-md5-96"), - docvalues.CreateEnumString("hmac-sha1"), - docvalues.CreateEnumString("hmac-sha1-96"), - docvalues.CreateEnumString("hmac-sha2-256"), - docvalues.CreateEnumString("hmac-sha2-256"), - docvalues.CreateEnumString("hmac-sha2-512"), - docvalues.CreateEnumString("umac-64@openssh.com"), - docvalues.CreateEnumString("umac-128@openssh.com"), - docvalues.CreateEnumString("hmac-md5-etm@openssh.com"), - docvalues.CreateEnumString("hmac-md5-96-etm@openssh.com"), - docvalues.CreateEnumString("hmac-sha1-etm@openssh.com"), - docvalues.CreateEnumString("hmac-sha1-96-etm@openssh.com"), - docvalues.CreateEnumString("hmac-sha2-256-etm@openssh.com"), - docvalues.CreateEnumString("hmac-sha2-512-etm@openssh.com"), - docvalues.CreateEnumString("umac-64-etm@openssh.com"), - docvalues.CreateEnumString("umac-128-etm@openssh.com"), - }), - ), - - // Match Introduces a conditional block. If all of the criteria on the Match line are satisfied, the keywords on the following lines override those set in the global section of the config file, until either another Match line or the end of the file. If a keyword appears in multiple Match blocks that are satisfied, only the first instance of the keyword is applied. - // The arguments to Match are one or more criteria-pattern pairs or the single token All which matches all criteria. The available criteria are User, Group, Host, LocalAddress, LocalPort, RDomain, and Address (with RDomain representing the rdomain(4) on which the connection was received). - // The match patterns may consist of single entries or comma-separated lists and may use the wildcard and negation operators described in the “PATTERNS” section of ssh_config(5). - // The patterns in an Address criteria may additionally contain addresses to match in CIDR address/masklen format, such as 192.0.2.0/24 or 2001:db8::/32. Note that the mask length provided must be consistent with the address - it is an error to specify a mask length that is too long for the address or one with bits set in this host portion of the address. For example, 192.0.2.0/33 and 192.0.2.0/8, respectively. - // Only a subset of keywords may be used on the lines following a Match keyword. Available keywords are AcceptEnv, AllowAgentForwarding, AllowGroups, AllowStreamLocalForwarding, AllowTcpForwarding, AllowUsers, AuthenticationMethods, AuthorizedKeysCommand, AuthorizedKeysCommandUser, AuthorizedKeysFile, AuthorizedPrincipalsCommand, AuthorizedPrincipalsCommandUser, AuthorizedPrincipalsFile, Banner, CASignatureAlgorithms, ChannelTimeout, ChrootDirectory, ClientAliveCountMax, ClientAliveInterval, DenyGroups, DenyUsers, DisableForwarding, ExposeAuthInfo, ForceCommand, GatewayPorts, GSSAPIAuthentication, HostbasedAcceptedAlgorithms, HostbasedAuthentication, HostbasedUsesNameFromPacketOnly, IgnoreRhosts, Include, IPQoS, KbdInteractiveAuthentication, KerberosAuthentication, LogLevel, MaxAuthTries, MaxSessions, PasswordAuthentication, PermitEmptyPasswords, PermitListen, PermitOpen, PermitRootLogin, PermitTTY, PermitTunnel, PermitUserRC, PubkeyAcceptedAlgorithms, PubkeyAuthentication, PubkeyAuthOptions, RekeyLimit, RevokedKeys, RDomain, SetEnv, StreamLocalBindMask, StreamLocalBindUnlink, TrustedUserCAKeys, UnusedConnectionTimeout, X11DisplayOffset, X11Forwarding and X11UseLocalhost.`, - "MaxAuthTries": NewOption(`Specifies the maximum number of authentication attempts permitted per connection. Once the number of failures reaches half this value, additional failures are logged. The default is 6.`, - docvalues.NumberValue{Min: &ZERO}, - ), - "MaxSessions": NewOption(`Specifies the maximum number of open shell, login or subsystem (e.g. sftp) sessions permitted per network connection. Multiple sessions may be established by clients that support connection multiplexing. Setting MaxSessions to 1 will effectively disable session multiplexing, whereas setting it to 0 will prevent all shell, login and subsystem sessions while still permitting forwarding. The default is 10.`, - docvalues.NumberValue{Min: &ZERO}, - ), - "MaxStartups": NewOption(`Specifies the maximum number of concurrent unauthenticated connections to the SSH daemon. Additional connections will be dropped until authentication succeeds or the LoginGraceTime expires for a connection. The default is 10:30:100. - Alternatively, random early drop can be enabled by specifying the three colon separated values start:rate:full (e.g. "10:30:60"). sshd(8) will refuse connection attempts with a probability of rate/100 (30%) if there are currently start (10) unauthenticated connections. The probability increases linearly and all connection attempts are refused if the number of unauthenticated connections reaches full (60).`, - // TODO: Add custom value `SeapartorValue` that takes an array of values and separators - docvalues.RegexValue{ - Regex: *regexp.MustCompile(`^(\d+):(\d+):(\d+)$`), - }, - ), - "ModuliFile": NewOption(`Specifies the moduli(5) file that contains the Diffie- Hellman groups used for the “diffie-hellman-group-exchange-sha1” and “diffie-hellman-group-exchange-sha256” key exchange methods. The default is /etc/moduli.`, - docvalues.PathValue{ - RequiredType: docvalues.PathTypeFile, - }, - ), - "PasswordAuthentication": NewOption(`Specifies whether password authentication is allowed. The default is yes.`, - BooleanEnumValue, - ), - "PermitEmptyPasswords": NewOption(`When password authentication is allowed, it specifies whether the server allows login to accounts with empty password strings. The default is no.`, - BooleanEnumValue, - ), - "PermitListen": NewOption(`Specifies the addresses/ports on which a remote TCP port forwarding may listen. The listen specification must be one of the following forms: - PermitListen port PermitListen host:port - Multiple permissions may be specified by separating them with whitespace. An argument of any can be used to remove all restrictions and permit any listen requests. An argument of none can be used to prohibit all listen requests. The host name may contain wildcards as described in the PATTERNS section in ssh_config(5). The wildcard ‘*’ can also be used in place of a port number to allow all ports. By default all port forwarding listen requests are permitted. Note that the GatewayPorts option may further restrict which addresses may be listened on. Note also that ssh(1) will request a listen host of “localhost” if no listen host was specifically requested, and this name is treated differently to explicit localhost addresses of “127.0.0.1” and “::1”.`, - docvalues.ArrayValue{ - Separator: " ", - DuplicatesExtractor: &docvalues.SimpleDuplicatesExtractor, - SubValue: docvalues.KeyValueAssignmentValue{ - ValueIsOptional: true, - Key: docvalues.IPAddressValue{ - AllowIPv4: true, - AllowIPv6: true, - AllowRange: false, - DisallowedIPs: &docvalues.NonRoutableNetworks, - }, - Separator: ":", - Value: docvalues.OrValue{ - Values: []docvalues.Value{ - docvalues.EnumValue{ - Values: []docvalues.EnumString{ - { - InsertText: "*", - DescriptionText: "\\*", - Documentation: "Allow all ports", - }, - }, - EnforceValues: true, - }, - docvalues.NumberValue{Min: &ZERO, Max: &MAX_PORT}, - }, - }, - }, - }, - ), - "PermitOpen": NewOption(`Specifies the destinations to which TCP port forwarding is permitted. The forwarding specification must be one of the following forms: - PermitOpen host:port PermitOpen IPv4_addr:port PermitOpen [IPv6_addr]:port - Multiple forwards may be specified by separating them with whitespace. An argument of any can be used to remove all restrictions and permit any forwarding requests. An argument of none can be used to prohibit all forwarding requests. The wildcard ‘*’ can be used for host or port to allow all hosts or ports respectively. Otherwise, no pattern matching or address lookups are performed on supplied names. By default all port forwarding requests are permitted.`, - docvalues.ArrayValue{ - Separator: " ", - DuplicatesExtractor: &docvalues.SimpleDuplicatesExtractor, - SubValue: docvalues.KeyValueAssignmentValue{ - ValueIsOptional: true, - Key: docvalues.OrValue{ - Values: []docvalues.Value{ - docvalues.EnumValue{ - Values: []docvalues.EnumString{ - { - InsertText: "*", - DescriptionText: "\\*", - Documentation: "Allow all hosts", - }, - }, - }, - docvalues.IPAddressValue{ - AllowIPv4: true, - AllowIPv6: true, - AllowRange: false, - DisallowedIPs: &docvalues.NonRoutableNetworks, - }, - }, - }, - Separator: ":", - Value: docvalues.OrValue{ - Values: []docvalues.Value{ - docvalues.EnumValue{ - Values: []docvalues.EnumString{ - { - InsertText: "*", - DescriptionText: "\\*", - Documentation: "Allow all ports", - }, - }, - EnforceValues: true, - }, - docvalues.NumberValue{Min: &ZERO, Max: &MAX_PORT}, - }, - }, - }, - }, - ), - "PermitRootLogin": NewOption(`Specifies whether root can log in using ssh(1). The argument must be yes, prohibit-password, forced-commands-only, or no. The default is prohibit-password. - If this option is set to prohibit-password (or its deprecated alias, without-password), password and keyboard-interactive authentication are disabled for root. - If this option is set to forced-commands-only, root login with public key authentication will be allowed, but only if the command option has been specified (which may be useful for taking remote backups even if root login is normally not allowed). All other authentication methods are disabled for root. - If this option is set to no, root is not allowed to log in.`, - docvalues.EnumValue{ - EnforceValues: true, - Values: []docvalues.EnumString{ - docvalues.CreateEnumString("yes"), - docvalues.CreateEnumString("prohibit-password"), - docvalues.CreateEnumString("forced-commands-only"), - docvalues.CreateEnumString("no"), - }, - }, - ), - "PermitTTY": NewOption(`Specifies whether pty(4) allocation is permitted. The default is yes.`, - BooleanEnumValue, - ), - "PermitTunnel": NewOption(`Specifies whether tun(4) device forwarding is allowed. The argument must be yes, point-to-point (layer 3), ethernet (layer 2), or no. Specifying yes permits both point-to-point and ethernet. The default is no. - Independent of this setting, the permissions of the selected tun(4) device must allow access to the user.`, - docvalues.EnumValue{ - EnforceValues: true, - Values: []docvalues.EnumString{ - docvalues.CreateEnumString("yes"), - docvalues.CreateEnumString("point-to-point"), - docvalues.CreateEnumString("ethernet"), - docvalues.CreateEnumString("no"), - }, - }, - ), - "PermitUserEnvironment": NewOption(`Specifies whether ~/.ssh/environment and environment= options in ~/.ssh/authorized_keys are processed by sshd(8). Valid options are yes, no or a pattern-list specifying which environment variable names to accept (for example "LANG,LC_*"). The default is no. Enabling environment processing may enable users to bypass access restrictions in some configurations using mechanisms such as LD_PRELOAD.`, - docvalues.OrValue{ - Values: []docvalues.Value{ - docvalues.EnumValue{ - Values: []docvalues.EnumString{ - docvalues.CreateEnumString("yes"), - docvalues.CreateEnumString("no"), - }, - }, - docvalues.ArrayValue{ - SubValue: docvalues.StringValue{}, - Separator: ",", - DuplicatesExtractor: &docvalues.DuplicatesAllowedExtractor, - }, - }, - }, - ), - "PermitUserRC": NewOption(`Specifies whether any ~/.ssh/rc file is executed. The default is yes.`, - BooleanEnumValue, - ), - "PerSourceMaxStartups": NewOption(`Specifies the number of unauthenticated connections allowed from a given source address, or “none” if there is no limit. This limit is applied in addition to MaxStartups, whichever is lower. The default is none.`, - docvalues.OrValue{ - Values: []docvalues.Value{ - docvalues.EnumValue{ - EnforceValues: true, - Values: []docvalues.EnumString{ - { - InsertText: "none", - DescriptionText: "none", - Documentation: "No limit", - }, - }, - }, - docvalues.NumberValue{Min: &ZERO}, - }, - }, - ), - "PerSourceNetBlockSize": NewOption(`Specifies the number of bits of source address that are grouped together for the purposes of applying PerSourceMaxStartups limits. Values for IPv4 and optionally IPv6 may be specified, separated by a colon. The default is 32:128, which means each address is considered individually.`, - docvalues.KeyValueAssignmentValue{ - Separator: ":", - ValueIsOptional: false, - Key: docvalues.NumberValue{Min: &ZERO}, - Value: docvalues.NumberValue{Min: &ZERO}, - }, - ), - "PidFile": NewOption(`Specifies the file that contains the process ID of the SSH daemon, or none to not write one. The default is /var/run/sshd.pid.`, - docvalues.StringValue{}, - ), - - "Port": NewOption(`Specifies the port number that sshd(8) listens on. The default is 22. Multiple options of this type are permitted. See also ListenAddress.`, - docvalues.NumberValue{Min: &ZERO, Max: &MAX_PORT}, - ), - "PrintLastLog": NewOption(`Specifies whether sshd(8) should print the date and time of the last user login when a user logs in interactively. The default is yes.`, - BooleanEnumValue, - ), - "PrintMotd": NewOption(`Specifies whether sshd(8) should print /etc/motd when a user logs in interactively. (On some systems it is also printed by the shell, /etc/profile, or equivalent.) The default is yes.`, - BooleanEnumValue, - ), - "PubkeyAcceptedAlgorithms": NewOption(`Specifies the signature algorithms that will be accepted for public key authentication as a list of comma- separated patterns. Alternately if the specified list begins with a ‘+’ character, then the specified algorithms will be appended to the default set instead of replacing them. If the specified list begins with a ‘-’ character, then the specified algorithms (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a ‘^’ character, then the specified algorithms will be placed at the head of the default set. The default for this option is: - ssh-ed25519-cert-v01@openssh.com, ecdsa-sha2-nistp256-cert-v01@openssh.com, ecdsa-sha2-nistp384-cert-v01@openssh.com, ecdsa-sha2-nistp521-cert-v01@openssh.com, sk-ssh-ed25519-cert-v01@openssh.com, sk-ecdsa-sha2-nistp256-cert-v01@openssh.com, rsa-sha2-512-cert-v01@openssh.com, rsa-sha2-256-cert-v01@openssh.com, ssh-ed25519, ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521, sk-ssh-ed25519@openssh.com, sk-ecdsa-sha2-nistp256@openssh.com, rsa-sha2-512,rsa-sha2-256 - The list of available signature algorithms may also be obtained using "ssh -Q PubkeyAcceptedAlgorithms".`, - docvalues.CustomValue{ - FetchValue: func(_ docvalues.CustomValueContext) docvalues.Value { - options, _ := QueryOpenSSHOptions("PubkeyAcceptedAlgorithms") - - return PrefixPlusMinusCaret(options) - }, - }, - ), - "PubkeyAuthOptions": NewOption(`Sets one or more public key authentication options. The supported keywords are: none (the default; indicating no additional options are enabled), touch-required and verify-required. - The touch-required option causes public key authentication using a FIDO authenticator algorithm (i.e. ecdsa-sk or ed25519-sk) to always require the signature to attest that a physically present user explicitly confirmed the authentication (usually by touching the authenticator). By default, sshd(8) requires user presence unless overridden with an authorized_keys option. The touch-required flag disables this override. - The verify-required option requires a FIDO key signature attest that the user was verified, e.g. via a PIN. - Neither the touch-required or verify-required options have any effect for other, non-FIDO, public key types.`, - docvalues.ArrayValue{ - Separator: ",", - SubValue: docvalues.EnumValue{ - EnforceValues: true, - Values: []docvalues.EnumString{ - docvalues.CreateEnumString("none"), - docvalues.CreateEnumString("touch-required"), - docvalues.CreateEnumString("verify-required"), - }, - }, - }, - ), - "PubkeyAuthentication": NewOption(`Specifies whether public key authentication is allowed. The default is yes.`, - BooleanEnumValue, - ), - "RekeyLimit": NewOption(`Specifies the maximum amount of data that may be transmitted or received before the session key is renegotiated, optionally followed by a maximum amount of time that may pass before the session key is renegotiated. The first argument is specified in bytes and may have a suffix of ‘K’, ‘M’, or ‘G’ to indicate Kilobytes, Megabytes, or Gigabytes, respectively. The default is between ‘1G’ and ‘4G’, depending on the cipher. The optional second value is specified in seconds and may use any of the units documented in the “TIME FORMATS” section. The default value for RekeyLimit is default none, which means that rekeying is performed after the cipher's default amount of data has been sent or received and no time based rekeying is done.`, - docvalues.KeyValueAssignmentValue{ - Separator: " ", - ValueIsOptional: true, - Key: DataAmountValue{}, - Value: TimeFormatValue{}, - }, - ), - "RequiredRSASize": NewOption(`Specifies the minimum RSA key size (in bits) that sshd(8) will accept. User and host-based authentication keys smaller than this limit will be refused. The default is 1024 bits. Note that this limit may only be raised from the default.`, - docvalues.NumberValue{Min: &ZERO}, - ), - "RevokedKeys": NewOption(`Specifies revoked public keys file, or none to not use one. Keys listed in this file will be refused for public key authentication. Note that if this file is not readable, then public key authentication will be refused for all users. Keys may be specified as a text file, listing one public key per line, or as an OpenSSH Key Revocation List (KRL) as generated by ssh-keygen(1). For more information on KRLs, see the KEY REVOCATION LISTS section in ssh-keygen(1).`, - docvalues.StringValue{}, - ), - "RDomain": NewOption(`Specifies an explicit routing domain that is applied after authentication has completed. The user session, as well as any forwarded or listening IP sockets, will be bound to this rdomain(4). If the routing domain is set to %D, then the domain in which the incoming connection was received will be applied.`, - docvalues.OrValue{ - Values: []docvalues.Value{ - docvalues.EnumValue{ - Values: []docvalues.EnumString{ - { - InsertText: "%D", - DescriptionText: "%D", - Documentation: "The domain in which the incoming connection was received", - }, - }, - }, - docvalues.StringValue{}, - }, - }, - ), - "SecurityKeyProvider": NewOption(`Specifies a path to a library that will be used when loading FIDO authenticator-hosted keys, overriding the default of using the built-in USB HID support.`, - docvalues.PathValue{ - RequiredType: docvalues.PathTypeFile, - }, - ), - - "SetEnv": NewOption(`Specifies one or more environment variables to set in child sessions started by sshd(8) as “NAME=VALUE”. The environment value may be quoted (e.g. if it contains whitespace characters). Environment variables set by SetEnv override the default environment and any variables specified by the user via AcceptEnv or PermitUserEnvironment.`, - docvalues.ArrayValue{ - Separator: " ", - DuplicatesExtractor: &SetEnvExtractor, - SubValue: docvalues.KeyValueAssignmentValue{ - ValueIsOptional: false, - Separator: "=", - Key: docvalues.StringValue{}, - Value: docvalues.StringValue{}, - }, - }, - ), - "StreamLocalBindMask": NewOption(`Sets the octal file creation mode mask (umask) used when creating a Unix-domain socket file for local or remote port forwarding. This option is only used for port forwarding to a Unix-domain socket file. - The default value is 0177, which creates a Unix-domain socket file that is readable and writable only by the owner. Note that not all operating systems honor the file mode on Unix-domain socket files.`, - docvalues.NumberValue{Min: &ZERO, Max: &MAX_FILE_MODE}, - ), - "StreamLocalBindUnlink": NewOption(`Specifies whether to remove an existing Unix-domain socket file for local or remote port forwarding before creating a new one. If the socket file already exists and StreamLocalBindUnlink is not enabled, sshd will be unable to forward the port to the Unix-domain socket file. This option is only used for port forwarding to a Unix-domain socket file. - The argument must be yes or no. The default is no.`, - BooleanEnumValue, - ), - "StrictModes": NewOption(`Specifies whether sshd(8) should check file modes and ownership of the user's files and home directory before accepting login. This is normally desirable because novices sometimes accidentally leave their directory or files world-writable. The default is yes. Note that this does not apply to ChrootDirectory, whose permissions and ownership are checked unconditionally.`, - BooleanEnumValue, - ), - "Subsystem": NewOption(`Configures an external subsystem (e.g. file transfer daemon). Arguments should be a subsystem name and a command (with optional arguments) to execute upon subsystem request. - The command sftp-server implements the SFTP file transfer subsystem. - Alternately the name internal-sftp implements an in- process SFTP server. This may simplify configurations using ChrootDirectory to force a different filesystem root on clients. It accepts the same command line arguments as sftp-server and even though it is in- process, settings such as LogLevel or SyslogFacility do not apply to it and must be set explicitly via command line arguments. - By default no subsystems are defined.`, - docvalues.StringValue{}, - ), - "SyslogFacility": NewOption(`Gives the facility code that is used when logging messages from sshd(8). The possible values are: DAEMON, USER, AUTH, LOCAL0, LOCAL1, LOCAL2, LOCAL3, LOCAL4, LOCAL5, LOCAL6, LOCAL7. The default is AUTH.`, - docvalues.EnumValue{ - EnforceValues: true, - Values: []docvalues.EnumString{ - docvalues.CreateEnumString("DAEMON"), - docvalues.CreateEnumString("USER"), - docvalues.CreateEnumString("AUTH"), - docvalues.CreateEnumString("LOCAL0"), - docvalues.CreateEnumString("LOCAL1"), - docvalues.CreateEnumString("LOCAL2"), - docvalues.CreateEnumString("LOCAL3"), - docvalues.CreateEnumString("LOCAL4"), - docvalues.CreateEnumString("LOCAL5"), - docvalues.CreateEnumString("LOCAL6"), - docvalues.CreateEnumString("LOCAL7"), - }, - }, - ), - "TCPKeepAlive": NewOption(`Specifies whether the system should send TCP keepalive messages to the other side. If they are sent, death of the connection or crash of one of the machines will be properly noticed. However, this means that connections will die if the route is down temporarily, and some people find it annoying. On the other hand, if TCP keepalives are not sent, sessions may hang indefinitely on the server, leaving "ghost" users and consuming server resources. - The default is yes (to send TCP keepalive messages), and the server will notice if the network goes down or the client host crashes. This avoids infinitely hanging sessions. - To disable TCP keepalive messages, the value should be set to no.`, - BooleanEnumValue, - ), - "TrustedUserCAKeys": NewOption(`Specifies a file containing public keys of certificate authorities that are trusted to sign user certificates for authentication, or none to not use one. Keys are listed one per line; empty lines and comments starting with ‘#’ are allowed. If a certificate is presented for authentication and has its signing CA key listed in this file, then it may be used for authentication for any user listed in the certificate's principals list. Note that certificates that lack a list of principals will not be permitted for authentication using TrustedUserCAKeys. For more details on certificates, see the CERTIFICATES section in ssh-keygen(1).`, - docvalues.StringValue{}, - ), - "UnusedConnectionTimeout": NewOption(`Specifies whether and how quickly sshd(8) should close client connections with no open channels. Open channels include active shell, command execution or subsystem sessions, connected network, socket, agent or X11 forwardings. Forwarding listeners, such as those from the ssh(1) -R flag, are not considered as open channels and do not prevent the timeout. The timeout value is specified in seconds or may use any of the units documented in the “TIME FORMATS” section. - Note that this timeout starts when the client connection completes user authentication but before the client has an opportunity to open any channels. Caution should be used when using short timeout values, as they may not provide sufficient time for the client to request and open its channels before terminating the connection. - The default none is to never expire connections for having no open channels. This option may be useful in conjunction with ChannelTimeout.`, - TimeFormatValue{}, - ), - "UseDNS": NewOption(`Specifies whether sshd(8) should look up the remote host name, and to check that the resolved host name for the remote IP address maps back to the very same IP address. - If this option is set to no (the default) then only addresses and not host names may be used in ~/.ssh/authorized_keys from and sshd_config Match Host directives.`, - BooleanEnumValue, - ), - - "UsePAM": NewOption(`Enables the Pluggable Authentication Module interface. If set to yes this will enable PAM authentication using KbdInteractiveAuthentication and PasswordAuthentication in addition to PAM account and session module processing for all authentication types. - Because PAM keyboard-interactive authentication usually serves an equivalent role to password authentication, you should disable either PasswordAuthentication or KbdInteractiveAuthentication. - If UsePAM is enabled, you will not be able to run sshd(8) as a non-root user. The default is no.`, - BooleanEnumValue, - ), - "VersionAddendum": NewOption(`Optionally specifies additional text to append to the SSH protocol banner sent by the server upon connection. The default is none.`, - docvalues.OrValue{ - Values: []docvalues.Value{ - docvalues.EnumValue{ - EnforceValues: true, - Values: []docvalues.EnumString{ - docvalues.CreateEnumString("none"), - }, - }, - docvalues.StringValue{}, - }, - }, - ), - "X11DisplayOffset": NewOption(`Specifies the first display number available for sshd(8)'s X11 forwarding. This prevents sshd from interfering with real X11 servers. The default is 10.`, - docvalues.NumberValue{Min: &ZERO}, - ), - "X11Forwarding": NewOption(`Specifies whether X11 forwarding is permitted. The argument must be yes or no. The default is no. - When X11 forwarding is enabled, there may be additional exposure to the server and to client displays if the sshd(8) proxy display is configured to listen on the wildcard address (see X11UseLocalhost), though this is not the default. Additionally, the authentication spoofing and authentication data verification and substitution occur on the client side. The security risk of using X11 forwarding is that the client's X11 display server may be exposed to attack when the SSH client requests forwarding (see the warnings for ForwardX11 in ssh_config(5)). A system administrator may have a stance in which they want to protect clients that may expose themselves to attack by unwittingly requesting X11 forwarding, which can warrant a no setting. - Note that disabling X11 forwarding does not prevent users from forwarding X11 traffic, as users can always install their own forwarders.`, - BooleanEnumValue, - ), - "X11UseLocalhost": NewOption(`Specifies whether sshd(8) should bind the X11 forwarding server to the loopback address or to the wildcard address. By default, sshd binds the forwarding server to the loopback address and sets the hostname part of the DISPLAY environment variable to localhost. This prevents remote hosts from connecting to the proxy display. However, some older X11 clients may not function with this configuration. X11UseLocalhost may be set to no to specify that the forwarding server should be bound to the wildcard address. The argument must be yes or no. The default is yes.`, - BooleanEnumValue, - ), - "XAuthLocation": NewOption(`Specifies the full pathname of the xauth(1) program, or none to not use one. The default is /usr/X11R6/bin/xauth.`, - docvalues.StringValue{}, - ), -} diff --git a/handlers/openssh/parser.go b/handlers/openssh/parser.go deleted file mode 100644 index 21a6219..0000000 --- a/handlers/openssh/parser.go +++ /dev/null @@ -1,146 +0,0 @@ -package openssh - -import ( - docvalues "config-lsp/doc-values" - "regexp" - "strings" -) - -type SimpleConfigPosition struct { - Line uint32 -} - -type SimpleConfigLine struct { - Value string - Separator string - Position SimpleConfigPosition -} - -// Get the character positions of [Option End, Separator End, Value End] -func (l SimpleConfigLine) GetCharacterPositions(optionName string) [3]int { - return [3]int{len(optionName), len(optionName + l.Separator), len(optionName + l.Separator + l.Value)} -} - -type SimpleConfigOptions struct { - Separator regexp.Regexp - IgnorePattern regexp.Regexp - // This is the separator that will be used when adding a new line - IdealSeparator string - AvailableOptions *map[string]Option -} - -type SimpleConfigParser struct { - Lines map[string]SimpleConfigLine - Options SimpleConfigOptions -} - -func (p *SimpleConfigParser) AddLine(line string, lineNumber uint32) (string, error) { - var option string - var separator string - var value string - - re := p.Options.Separator - matches := re.FindStringSubmatch(line) - - if len(matches) == 0 { - return "", docvalues.MalformedLineError{} - } - - optionIndex := re.SubexpIndex("OptionName") - if optionIndex == -1 { - return "", docvalues.MalformedLineError{} - } - option = matches[optionIndex] - - if _, exists := (*p.Options.AvailableOptions)[option]; !exists { - return option, docvalues.OptionUnknownError{} - } - - separatorIndex := re.SubexpIndex("Separator") - if separatorIndex == -1 { - return option, docvalues.MalformedLineError{} - } - separator = matches[separatorIndex] - - valueIndex := re.SubexpIndex("Value") - if valueIndex == -1 { - return option, docvalues.MalformedLineError{} - } - value = matches[valueIndex] - - if _, exists := p.Lines[option]; exists { - return option, docvalues.OptionAlreadyExistsError{ - AlreadyLine: p.Lines[option].Position.Line, - } - } - - p.Lines[option] = SimpleConfigLine{ - Value: value, - Separator: separator, - Position: SimpleConfigPosition{ - Line: lineNumber, - }, - } - - return option, nil - -} - -func (p *SimpleConfigParser) ReplaceOption(option string, value string) { - p.Lines[option] = SimpleConfigLine{ - Value: value, - Position: SimpleConfigPosition{ - Line: p.Lines[option].Position.Line, - }, - } -} - -func (p *SimpleConfigParser) RemoveOption(option string) { - delete(p.Lines, option) -} - -func (p *SimpleConfigParser) GetOption(option string) (SimpleConfigLine, error) { - if _, exists := p.Lines[option]; exists { - return p.Lines[option], nil - } - - return SimpleConfigLine{}, docvalues.OptionUnknownError{} -} - -func (p *SimpleConfigParser) ParseFromFile(content string) []docvalues.OptionError { - lines := strings.Split(content, "\n") - errors := make([]docvalues.OptionError, 0) - - for index, line := range lines { - if p.Options.IgnorePattern.MatchString(line) { - continue - } - - option, err := p.AddLine(line, uint32(index)) - - if err != nil { - errors = append(errors, docvalues.OptionError{ - Line: uint32(index), - ProvidedOption: option, - DocError: err, - }) - } - } - - return errors -} - -func (p *SimpleConfigParser) Clear() { - clear(p.Lines) -} - -// TODO: Use better approach: Store an extra array of lines in order; with references to the SimpleConfigLine -func (p *SimpleConfigParser) FindByLineNumber(lineNumber uint32) (string, SimpleConfigLine, error) { - for option, line := range p.Lines { - if line.Position.Line == lineNumber { - return option, line, nil - } - } - - return "", SimpleConfigLine{Value: "", Position: SimpleConfigPosition{Line: 0}}, docvalues.LineNotFoundError{} -} diff --git a/handlers/openssh/shared.go b/handlers/openssh/shared.go deleted file mode 100644 index 779c937..0000000 --- a/handlers/openssh/shared.go +++ /dev/null @@ -1,19 +0,0 @@ -package openssh - -import ( - "regexp" -) - -func createOpenSSHConfigParser() SimpleConfigParser { - return SimpleConfigParser{ - Lines: make(map[string]SimpleConfigLine), - Options: SimpleConfigOptions{ - Separator: *regexp.MustCompile(`(?m)^\s*(?P\w+)(?P\s*)(?P.*)\s*$`), - IgnorePattern: *regexp.MustCompile(`^(?:#|\s*$)`), - IdealSeparator: " ", - AvailableOptions: &Options, - }, - } -} - -var Parser = createOpenSSHConfigParser() diff --git a/handlers/openssh/text-document-completion.go b/handlers/openssh/text-document-completion.go deleted file mode 100644 index a6cec50..0000000 --- a/handlers/openssh/text-document-completion.go +++ /dev/null @@ -1,62 +0,0 @@ -package openssh - -import ( - docvalues "config-lsp/doc-values" - "errors" - - "github.com/tliron/glsp" - protocol "github.com/tliron/glsp/protocol_3_16" - "golang.org/x/exp/maps" - - _ "github.com/tliron/commonlog/simple" -) - -func TextDocumentCompletion(context *glsp.Context, params *protocol.CompletionParams) (interface{}, error) { - optionName, line, err := Parser.FindByLineNumber(uint32(params.Position.Line)) - - if err == nil { - if params.Position.Character < uint32(len(optionName)) { - return getRootCompletions(), nil - } else { - cursor := params.Position.Character - uint32(line.GetCharacterPositions(optionName)[1]) - - return getOptionCompletions(optionName, line.Value, cursor), nil - } - } else if errors.Is(err, docvalues.LineNotFoundError{}) { - return getRootCompletions(), nil - } - - return nil, err -} - -func getRootCompletions() []protocol.CompletionItem { - completions := make([]protocol.CompletionItem, len(Options)) - - optionsKey := maps.Keys(Options) - for index := 0; index < len(maps.Keys(Options)); index++ { - label := optionsKey[index] - option := Options[label] - insertText := label + " " + "${1:value}" - - format := protocol.InsertTextFormatSnippet - kind := protocol.CompletionItemKindField - - completions[index] = protocol.CompletionItem{ - Label: label, - Documentation: GetDocumentation(&option), - InsertText: &insertText, - InsertTextFormat: &format, - Kind: &kind, - } - } - - return completions -} - -func getOptionCompletions(optionName string, line string, cursor uint32) []protocol.CompletionItem { - option := Options[optionName] - - completions := option.Value.FetchCompletions(line, cursor) - - return completions -} diff --git a/handlers/openssh/text-document-did-change.go b/handlers/openssh/text-document-did-change.go deleted file mode 100644 index 652887c..0000000 --- a/handlers/openssh/text-document-did-change.go +++ /dev/null @@ -1,24 +0,0 @@ -package openssh - -import ( - "config-lsp/common" - - "github.com/tliron/glsp" - protocol "github.com/tliron/glsp/protocol_3_16" -) - -// Todo: Implement incremental parsing -func TextDocumentDidChange(context *glsp.Context, params *protocol.DidChangeTextDocumentParams) error { - content := params.ContentChanges[0].(protocol.TextDocumentContentChangeEventWhole).Text - - Parser.Clear() - diagnostics := DiagnoseParser(context, params.TextDocument.URI, content) - - if len(diagnostics) > 0 { - common.SendDiagnostics(context, params.TextDocument.URI, diagnostics) - } else { - common.ClearDiagnostics(context, params.TextDocument.URI) - } - - return nil -} diff --git a/handlers/openssh/text-document-did-open.go b/handlers/openssh/text-document-did-open.go deleted file mode 100644 index 7c533e3..0000000 --- a/handlers/openssh/text-document-did-open.go +++ /dev/null @@ -1,25 +0,0 @@ -package openssh - -import ( - "config-lsp/common" - "os" - - "github.com/tliron/glsp" - protocol "github.com/tliron/glsp/protocol_3_16" -) - -func TextDocumentDidOpen(context *glsp.Context, params *protocol.DidOpenTextDocumentParams) error { - readBytes, err := os.ReadFile(params.TextDocument.URI[len("file://"):]) - - if err != nil { - return err - } - - diagnostics := DiagnoseParser(context, params.TextDocument.URI, string(readBytes)) - - if len(diagnostics) > 0 { - common.SendDiagnostics(context, params.TextDocument.URI, diagnostics) - } - - return nil -} diff --git a/handlers/openssh/utils.go b/handlers/openssh/utils.go deleted file mode 100644 index 9ef0d5f..0000000 --- a/handlers/openssh/utils.go +++ /dev/null @@ -1,5 +0,0 @@ -package openssh - -import "regexp" - -var isJustDigitsPattern = regexp.MustCompile(`^\d+$`) diff --git a/handlers/openssh/value-data-amount-value.go b/handlers/openssh/value-data-amount-value.go deleted file mode 100644 index 4e90811..0000000 --- a/handlers/openssh/value-data-amount-value.go +++ /dev/null @@ -1,97 +0,0 @@ -package openssh - -import ( - docvalues "config-lsp/doc-values" - "fmt" - "regexp" - "strconv" - - protocol "github.com/tliron/glsp/protocol_3_16" -) - -var dataAmountCheckPattern = regexp.MustCompile(`(?i)^(\d+)([KMG])$`) - -type InvalidDataAmountError struct{} - -func (e InvalidDataAmountError) Error() string { - return "Data amount is invalid. It must be in the form of: [K|M|G]" -} - -type DataAmountValue struct{} - -func (v DataAmountValue) GetTypeDescription() []string { - return []string{"Data amount"} -} - -func (v DataAmountValue) CheckIsValid(value string) []*docvalues.InvalidValue { - if !dataAmountCheckPattern.MatchString(value) { - return []*docvalues.InvalidValue{ - { - Err: InvalidDataAmountError{}, - Start: 0, - End: uint32(len(value)), - }, - } - } - - return nil -} - -func calculateLineToKilobyte(value string, unit string) string { - val, err := strconv.Atoi(value) - - if err != nil { - return "" - } - - switch unit { - case "K": - return strconv.Itoa(val) - case "M": - return strconv.Itoa(val * 1000) - case "G": - return strconv.Itoa(val * 1000 * 1000) - default: - return "" - } -} - -func (v DataAmountValue) FetchCompletions(line string, cursor uint32) []protocol.CompletionItem { - completions := make([]protocol.CompletionItem, 0) - - if line != "" && !dataAmountCheckPattern.MatchString(line) { - kind := protocol.CompletionItemKindValue - - completions = append( - completions, - protocol.CompletionItem{ - Label: line + "K", - Kind: &kind, - Documentation: line + " kilobytes", - }, - protocol.CompletionItem{ - Label: line + "M", - Kind: &kind, - Documentation: fmt.Sprintf("%s megabytes (%s kilobytes)", line, calculateLineToKilobyte(line, "M")), - }, - protocol.CompletionItem{ - Label: line + "G", - Kind: &kind, - Documentation: fmt.Sprintf("%s gigabytes (%s kilobytes)", line, calculateLineToKilobyte(line, "G")), - }, - ) - } - - if line == "" || isJustDigitsPattern.MatchString(line) { - completions = append( - completions, - docvalues.GenerateBase10Completions(line)..., - ) - } - - return completions -} - -func (v DataAmountValue) FetchHoverInfo(line string, cursor uint32) []string { - return []string{} -} diff --git a/handlers/openssh/value-time-format.go b/handlers/openssh/value-time-format.go deleted file mode 100644 index b2f3554..0000000 --- a/handlers/openssh/value-time-format.go +++ /dev/null @@ -1,111 +0,0 @@ -package openssh - -import ( - docvalues "config-lsp/doc-values" - "config-lsp/utils" - "fmt" - "regexp" - "strconv" - - protocol "github.com/tliron/glsp/protocol_3_16" -) - -var timeFormatCompletionsPattern = regexp.MustCompile(`(?i)^(\d+)([smhdw])$`) -var timeFormatCheckPattern = regexp.MustCompile(`(?i)^(\d+)([smhdw]?)$`) - -type InvalidTimeFormatError struct{} - -func (e InvalidTimeFormatError) Error() string { - return "Time format is invalid. It must be in the form of: [s|m|h|d|w]" -} - -type TimeFormatValue struct{} - -func (v TimeFormatValue) GetTypeDescription() []string { - return []string{"Time value"} -} - -func (v TimeFormatValue) CheckIsValid(value string) []*docvalues.InvalidValue { - if !timeFormatCheckPattern.MatchString(value) { - return []*docvalues.InvalidValue{ - { - Err: InvalidTimeFormatError{}, - Start: 0, - End: uint32(len(value)), - }, - } - } - - return nil -} - -func calculateInSeconds(value int, unit string) int { - switch unit { - case "s": - return value - case "m": - return value * 60 - case "h": - return value * 60 * 60 - case "d": - return value * 60 * 60 * 24 - case "w": - return value * 60 * 60 * 24 * 7 - default: - return 0 - } -} - -func (v TimeFormatValue) FetchCompletions(line string, cursor uint32) []protocol.CompletionItem { - completions := make([]protocol.CompletionItem, 0) - - if line != "" && !timeFormatCompletionsPattern.MatchString(line) { - completions = append( - completions, - utils.Map( - []string{"s", "m", "h", "d", "w"}, - func(unit string) protocol.CompletionItem { - kind := protocol.CompletionItemKindValue - - unitName := map[string]string{ - "s": "seconds", - "m": "minutes", - "h": "hours", - "d": "days", - "w": "weeks", - }[unit] - - var detail string - value, err := strconv.Atoi(line) - - if err == nil { - if unit == "s" { - detail = fmt.Sprintf("%d seconds", value) - } else { - detail = fmt.Sprintf("%d %s (%d seconds)", value, unitName, calculateInSeconds(value, unit)) - } - } - - return protocol.CompletionItem{ - Label: line + unit, - Kind: &kind, - Detail: &detail, - } - }, - )..., - ) - } - - if line == "" || isJustDigitsPattern.MatchString(line) { - completions = append( - completions, - docvalues.GenerateBase10Completions(line)..., - ) - } - - return completions -} - -func (v TimeFormatValue) FetchHoverInfo(line string, cursor uint32) []string { - return []string{} -} From a577aeda4b28f18fe27eab226a6a20e1883ddfb0 Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Sun, 15 Sep 2024 19:04:05 +0200 Subject: [PATCH 040/133] fix: Fix docs --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 17a2e9e..acbcf86 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,8 @@ | wireguard | ✅ | ✅ | ✅ | ✅ | ❓ | ❓ | 🟡 | ✅ = Supported + 🟡 = Will be supported, but not yet implemented + ❓ = No idea what to implement here, please let me know if you have any ideas From 5d84e27a1fc7b994b20a3a6d25b0fc4db48808af Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Sun, 15 Sep 2024 19:13:59 +0200 Subject: [PATCH 041/133] fix: Fix issue --- .github/ISSUE_TEMPLATE/1_new_config.yaml | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/.github/ISSUE_TEMPLATE/1_new_config.yaml b/.github/ISSUE_TEMPLATE/1_new_config.yaml index e46b1fb..1af1a95 100644 --- a/.github/ISSUE_TEMPLATE/1_new_config.yaml +++ b/.github/ISSUE_TEMPLATE/1_new_config.yaml @@ -47,6 +47,13 @@ body: description: Provide *at least* 3 examples of the config file. One simple example, one (theoretical) complex example, and one real-world example. If the examples contain real data, you may anonymize the values but try to keep the structure intact. placeholder: Your examples here + - type: textarea + id: locations + attributes: + label: File locations + description: What are the usual locations for the config file? If the program supports multiple config files, mention them as well. + placeholder: /etc/ssh/sshd_config + - type: textarea id: tutorial attributes: From 6326ccb6099407f9c5917b5d2a4c775357c0bbe7 Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Sun, 15 Sep 2024 22:51:45 +0200 Subject: [PATCH 042/133] feat(sshd_config): Add match block analyzer --- .../lsp/text-document-signature-help.go | 3 +- handlers/sshd_config/Config.g4 | 2 +- handlers/sshd_config/analyzer/analyzer.go | 2 + handlers/sshd_config/analyzer/match.go | 112 ++++++++++++++++++ handlers/sshd_config/analyzer/match_test.go | 63 ++++++++++ handlers/sshd_config/ast/listener.go | 13 +- handlers/sshd_config/ast/parser_test.go | 15 +++ .../sshd_config/handlers/completions_match.go | 2 +- handlers/sshd_config/indexes/indexes.go | 2 + root-handler/handler.go | 10 +- utils/strings.go | 19 +++ 11 files changed, 228 insertions(+), 15 deletions(-) create mode 100644 handlers/sshd_config/analyzer/match.go create mode 100644 handlers/sshd_config/analyzer/match_test.go diff --git a/handlers/aliases/lsp/text-document-signature-help.go b/handlers/aliases/lsp/text-document-signature-help.go index ce3a9b0..6408f50 100644 --- a/handlers/aliases/lsp/text-document-signature-help.go +++ b/handlers/aliases/lsp/text-document-signature-help.go @@ -1,6 +1,7 @@ package lsp import ( + "config-lsp/common" "config-lsp/handlers/aliases" "config-lsp/handlers/aliases/ast" "config-lsp/handlers/aliases/handlers" @@ -13,7 +14,7 @@ func TextDocumentSignatureHelp(context *glsp.Context, params *protocol.Signature document := aliases.DocumentParserMap[params.TextDocument.URI] line := params.Position.Line - character := params.Position.Character + character := common.CursorToCharacterIndex(params.Position.Character) if _, found := document.Parser.CommentLines[line]; found { // Comment diff --git a/handlers/sshd_config/Config.g4 b/handlers/sshd_config/Config.g4 index 569a6a8..ad4cbe8 100644 --- a/handlers/sshd_config/Config.g4 +++ b/handlers/sshd_config/Config.g4 @@ -1,7 +1,7 @@ grammar Config; lineStatement - : (entry | (leadingComment) | WHITESPACE?) EOF + : (entry | leadingComment | WHITESPACE?) EOF ; entry diff --git a/handlers/sshd_config/analyzer/analyzer.go b/handlers/sshd_config/analyzer/analyzer.go index 0b661c6..36944aa 100644 --- a/handlers/sshd_config/analyzer/analyzer.go +++ b/handlers/sshd_config/analyzer/analyzer.go @@ -49,6 +49,8 @@ func Analyze( } } + errors = append(errors, analyzeMatchBlocks(d)...) + if len(errors) > 0 { return errsToDiagnostics(errors) } diff --git a/handlers/sshd_config/analyzer/match.go b/handlers/sshd_config/analyzer/match.go new file mode 100644 index 0000000..c5ad800 --- /dev/null +++ b/handlers/sshd_config/analyzer/match.go @@ -0,0 +1,112 @@ +package analyzer + +import ( + "config-lsp/common" + sshdconfig "config-lsp/handlers/sshd_config" + match_parser "config-lsp/handlers/sshd_config/fields/match-parser" + "config-lsp/utils" + "errors" + "fmt" + "strings" +) + +func analyzeMatchBlocks( + d *sshdconfig.SSHDocument, +) []common.LSPError { + errs := make([]common.LSPError, 0) + + for _, indexOption := range d.Indexes.AllOptionsPerName["Match"] { + matchBlock := indexOption.MatchBlock.MatchValue + + // Check if the match block has filled out all fields + if matchBlock == nil || len(matchBlock.Entries) == 0 { + errs = append(errs, common.LSPError{ + Range: indexOption.Option.LocationRange, + Err: errors.New("A match expression is required"), + }) + continue + } + + for _, entry := range matchBlock.Entries { + if entry.Values == nil { + errs = append(errs, common.LSPError{ + Range: entry.LocationRange, + Err: errors.New(fmt.Sprintf("A value for %s is required", entry.Criteria.Type)), + }) + } else { + errs = append(errs, analyzeMatchValuesContainsPositiveValue(entry.Values)...) + + for _, value := range entry.Values.Values { + errs = append(errs, analyzeMatchValueNegation(value)...) + } + } + } + + // Check if match blocks are not empty + if indexOption.MatchBlock.Options.Size() == 0 { + errs = append(errs, common.LSPError{ + Range: indexOption.Option.LocationRange, + Err: errors.New("This match block is empty"), + }) + } + } + + return errs +} + +func analyzeMatchValueNegation( + value *match_parser.MatchValue, +) []common.LSPError { + errs := make([]common.LSPError, 0) + + positionsAsList := utils.AllIndexes(value.Value, "!") + positions := utils.SliceToMap(positionsAsList, struct{}{}) + + delete(positions, 0) + + for position := range positions { + errs = append(errs, common.LSPError{ + Range: common.LocationRange{ + Start: common.Location{ + Line: value.Start.Line, + Character: uint32(position) + value.Start.Character, + }, + End: common.Location{ + Line: value.End.Line, + Character: uint32(position) + value.End.Character, + }, + }, + Err: errors.New("The negation operator (!) may only occur at the beginning of a value"), + }) + } + + return errs +} + +func analyzeMatchValuesContainsPositiveValue( + values *match_parser.MatchValues, +) []common.LSPError { + if len(values.Values) == 0 { + return nil + } + + containsPositive := false + + for _, value := range values.Values { + if !strings.HasPrefix(value.Value, "!") { + containsPositive = true + break + } + } + + if !containsPositive { + return []common.LSPError{ + { + Range: values.LocationRange, + Err: errors.New("At least one positive value is required. A negated match will never produce a positive result by itself"), + }, + } + } + + return nil +} diff --git a/handlers/sshd_config/analyzer/match_test.go b/handlers/sshd_config/analyzer/match_test.go new file mode 100644 index 0000000..b65b478 --- /dev/null +++ b/handlers/sshd_config/analyzer/match_test.go @@ -0,0 +1,63 @@ +package analyzer + +import ( + sshdconfig "config-lsp/handlers/sshd_config" + "config-lsp/handlers/sshd_config/ast" + "config-lsp/handlers/sshd_config/indexes" + "config-lsp/utils" + "testing" +) + +func TestEmptyMatchBlocksMakesErrors( + t *testing.T, +) { + input := utils.Dedent(` +PermitRootLogin yes +Match User root +`) + c := ast.NewSSHConfig() + errors := c.Parse(input) + + if len(errors) > 0 { + t.Fatalf("Parse error: %v", errors) + } + + indexes, errors := indexes.CreateIndexes(*c) + + if len(errors) > 0 { + t.Fatalf("Index error: %v", errors) + } + + d := &sshdconfig.SSHDocument{ + Config: c, + Indexes: indexes, + } + + errors = analyzeMatchBlocks(d) + + if !(len(errors) == 1) { + t.Errorf("Expected 1 error, got %v", len(errors)) + } +} + +func TestContainsOnlyNegativeValues( + t *testing.T, +) { + input := utils.Dedent(` +PermitRootLogin yes +Match User !root,!admin +`) + c := ast.NewSSHConfig() + errors := c.Parse(input) + + if len(errors) > 0 { + t.Fatalf("Parse error: %v", errors) + } + + _, matchBlock := c.FindOption(uint32(1)) + errors = analyzeMatchValuesContainsPositiveValue(matchBlock.MatchValue.Entries[0].Values) + + if !(len(errors) == 1) { + t.Errorf("Expected 1 error, got %v", len(errors)) + } +} diff --git a/handlers/sshd_config/ast/listener.go b/handlers/sshd_config/ast/listener.go index b5c81b2..4830005 100644 --- a/handlers/sshd_config/ast/listener.go +++ b/handlers/sshd_config/ast/listener.go @@ -93,6 +93,10 @@ func (s *sshParserListener) ExitEntry(ctx *parser.EntryContext) { location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext) location.ChangeBothLines(s.sshContext.line) + defer (func() { + s.sshContext.currentOption = nil + })() + if s.sshContext.isKeyAMatchBlock { // Add new match block var match *match_parser.Match @@ -131,17 +135,20 @@ func (s *sshParserListener) ExitEntry(ctx *parser.EntryContext) { s.sshContext.currentMatchBlock = matchBlock s.sshContext.isKeyAMatchBlock = false - } else if s.sshContext.currentMatchBlock != nil { + + return + } + + if s.sshContext.currentMatchBlock != nil { s.sshContext.currentMatchBlock.Options.Put( location.Start.Line, s.sshContext.currentOption, ) + s.sshContext.currentMatchBlock.End = s.sshContext.currentOption.End } else { s.Config.Options.Put( location.Start.Line, s.sshContext.currentOption, ) } - - s.sshContext.currentOption = nil } diff --git a/handlers/sshd_config/ast/parser_test.go b/handlers/sshd_config/ast/parser_test.go index e883966..63d5bb0 100644 --- a/handlers/sshd_config/ast/parser_test.go +++ b/handlers/sshd_config/ast/parser_test.go @@ -92,6 +92,10 @@ Match Address 192.168.0.1 t.Errorf("Expected second entry to be 'Match Address 192.168.0.1', but got: %v", secondEntry.MatchEntry.Value) } + if !(secondEntry.Start.Line == 2 && secondEntry.Start.Character == 0 && secondEntry.End.Line == 3 && secondEntry.End.Character == 26) { + t.Errorf("Expected second entry's location to be 2:0-3:25, but got: %v", secondEntry.LocationRange) + } + if !(secondEntry.MatchValue.Entries[0].Criteria.Type == "Address" && secondEntry.MatchValue.Entries[0].Values.Values[0].Value == "192.168.0.1" && secondEntry.MatchEntry.OptionValue.Start.Character == 6) { t.Errorf("Expected second entry to be 'Match Address 192.168.0.1', but got: %v", secondEntry.MatchValue) } @@ -235,6 +239,17 @@ Match Address 192.168.0.2 if !(matchOption.Value == "Match User lena" && matchBlock.MatchEntry.Value == "Match User lena" && matchBlock.MatchValue.Entries[0].Values.Values[0].Value == "lena" && matchBlock.MatchEntry.OptionValue.Start.Character == 6) { t.Errorf("Expected match option to be 'Match User lena', but got: %v, %v", matchOption, matchBlock) } + + if !(matchOption.Start.Line == 2 && matchOption.End.Line == 2 && matchOption.Start.Character == 0 && matchOption.End.Character == 14) { + t.Errorf("Expected match option to be at 2:0-14, but got: %v", matchOption.LocationRange) + } + + if !(matchBlock.Start.Line == 2 && + matchBlock.Start.Character == 0 && + matchBlock.End.Line == 4 && + matchBlock.End.Character == 20) { + t.Errorf("Expected match block to be at 2:0-4:20, but got: %v", matchBlock.LocationRange) + } } func TestSimpleExampleWithComments( diff --git a/handlers/sshd_config/handlers/completions_match.go b/handlers/sshd_config/handlers/completions_match.go index 4a6fa2f..6a10ebe 100644 --- a/handlers/sshd_config/handlers/completions_match.go +++ b/handlers/sshd_config/handlers/completions_match.go @@ -13,7 +13,7 @@ func getMatchCompletions( match *match_parser.Match, cursor uint32, ) ([]protocol.CompletionItem, error) { - if len(match.Entries) == 0 { + if match == nil || len(match.Entries) == 0 { completions := getMatchCriteriaCompletions() completions = append(completions, getMatchAllKeywordCompletion()) diff --git a/handlers/sshd_config/indexes/indexes.go b/handlers/sshd_config/indexes/indexes.go index ed56afd..ebdda30 100644 --- a/handlers/sshd_config/indexes/indexes.go +++ b/handlers/sshd_config/indexes/indexes.go @@ -82,6 +82,8 @@ func CreateIndexes(config ast.SSHConfig) (*SSHIndexes, []common.LSPError) { case *ast.SSHMatchBlock: matchBlock := entry.(*ast.SSHMatchBlock) + errs = append(errs, addOption(indexes, matchBlock.MatchEntry, matchBlock)...) + it := matchBlock.Options.Iterator() for it.Next() { option := it.Value().(*ast.SSHOption) diff --git a/root-handler/handler.go b/root-handler/handler.go index 4a7cd3c..fc59b8a 100644 --- a/root-handler/handler.go +++ b/root-handler/handler.go @@ -42,15 +42,7 @@ func SetUpRootHandler() { func initialize(context *glsp.Context, params *protocol.InitializeParams) (any, error) { capabilities := lspHandler.CreateServerCapabilities() capabilities.TextDocumentSync = protocol.TextDocumentSyncKindFull - capabilities.SignatureHelpProvider = &protocol.SignatureHelpOptions{ - TriggerCharacters: []string{ - "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", - "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", - "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", - "_", "-", ".", "/", ":", "@", "#", "!", "$", "%", "^", "&", "*", "(", ")", "+", "=", "[", "]", "{", "}", "<", ">", "?", ";", ",", "|", - " ", - }, - } + capabilities.SignatureHelpProvider = &protocol.SignatureHelpOptions{} if (*params.Capabilities.TextDocument.Rename.PrepareSupport) == true { // Client supports rename preparation diff --git a/utils/strings.go b/utils/strings.go index bc32f88..3f7f851 100644 --- a/utils/strings.go +++ b/utils/strings.go @@ -2,6 +2,7 @@ package utils import ( "regexp" + "strings" ) var trimIndexPattern = regexp.MustCompile(`^\s*(.+?)\s*$`) @@ -57,3 +58,21 @@ var emptyRegex = regexp.MustCompile(`^\s*$`) func IsEmpty(s string) bool { return emptyRegex.MatchString(s) } + +func AllIndexes(s string, sub string) []int { + indexes := make([]int, 0) + current := s + + for { + index := strings.Index(current, sub) + + if index == -1 { + break + } + + indexes = append(indexes, index) + current = current[index+1:] + } + + return indexes +} From 44da608c5ac25671fa437edc518d3da304cba9b5 Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Sun, 15 Sep 2024 23:31:43 +0200 Subject: [PATCH 043/133] chore(ci-cd): Build go directly --- .github/workflows/pr-tests.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/pr-tests.yaml b/.github/workflows/pr-tests.yaml index 02eee42..ce7b09c 100644 --- a/.github/workflows/pr-tests.yaml +++ b/.github/workflows/pr-tests.yaml @@ -20,5 +20,5 @@ jobs: run: nix flake check - name: Build app - run: nix build -L + run: nix develop --command bash -c "go build" From b97a9a5d432de687b425ef4347a18e7a69aa90ea Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Mon, 16 Sep 2024 18:21:45 +0200 Subject: [PATCH 044/133] feat(ssh_config): Add fields --- handlers/ssh_config/fields/fields.go | 630 +++++++++++++++++++++++++++ 1 file changed, 630 insertions(+) create mode 100644 handlers/ssh_config/fields/fields.go diff --git a/handlers/ssh_config/fields/fields.go b/handlers/ssh_config/fields/fields.go new file mode 100644 index 0000000..fb904dd --- /dev/null +++ b/handlers/ssh_config/fields/fields.go @@ -0,0 +1,630 @@ +package fields + +import docvalues "config-lsp/doc-values" + +var Options = map[string]docvalues.DocumentationValue{ + "Host": docvalues.DocumentationValue{ + Documentation: `Restricts the following declarations (up to the next Host or Match keyword) to be only for those hosts that match one of the patterns given after the keyword. If more than one pattern is provided, they should be separated by whitespace. A single ‘*’ as a pattern can be used to provide global defaults for all hosts. The host is usually the hostname argument given on the command line (see the CanonicalizeHostname keyword for exceptions). + A pattern entry may be negated by prefixing it with an exclamation mark (‘!’). If a negated entry is matched, then the Host entry is ignored, regardless of whether any other patterns on the line match. Negated matches are therefore useful to provide exceptions for wildcard matches. + See PATTERNS for more information on patterns.`, + Value: docvalues.StringValue{}, + }, + "Match": docvalues.DocumentationValue{ + Documentation: `Restricts the following declarations (up to the next Host or Match keyword) to be used only when the conditions following the Match keyword are satisfied. Match conditions are specified using one or more criteria or the single token all which always matches. The available criteria keywords are: canonical, final, exec, localnetwork, host, originalhost, tagged, user, and localuser. The all criteria must appear alone or immediately after canonical or final. Other criteria may be combined arbitrarily. All criteria but all, canonical, and final require an argument. Criteria may be negated by prepending an exclamation mark (‘!’). + The canonical keyword matches only when the configuration file is being re-parsed after hostname canonicalization (see the CanonicalizeHostname option). This may be useful to specify conditions that work with canonical host names only. + The final keyword requests that the configuration be re-parsed (regardless of whether CanonicalizeHostname is enabled), and matches only during this final pass. If CanonicalizeHostname is enabled, then canonical and final match during the same pass. + The exec keyword executes the specified command under the user's shell. If the command returns a zero exit status then the condition is considered true. Commands containing whitespace characters must be quoted. Arguments to exec accept the tokens described in the TOKENS section. + The localnetwork keyword matches the addresses of active local network interfaces against the supplied list of networks in CIDR format. This may be convenient for varying the effective configuration on devices that roam between networks. Note that network address is not a trustworthy criteria in many situations (e.g. when the network is automatically configured using DHCP) and so caution should be applied if using it to control security-sensitive configuration. + The other keywords' criteria must be single entries or comma-separated lists and may use the wildcard and negation operators described in the PATTERNS section. The criteria for the host keyword are matched against the target hostname, after any substitution by the Hostname or CanonicalizeHostname options. The originalhost keyword matches against the hostname as it was specified on the command-line. The tagged keyword matches a tag name specified by a prior Tag directive or on the ssh(1) command-line using the -P flag. The user keyword matches against the target username on the remote host. The localuser keyword matches against the name of the local user running ssh(1) (this keyword may be useful in system-wide ssh_config files).`, + Value: docvalues.StringValue{}, + }, + "AddKeysToAgent": docvalues.DocumentationValue{ + Documentation: `Specifies whether keys should be automatically added to a running ssh-agent(1). If this option is set to yes and a key is loaded from a file, the key and its passphrase are added to the agent with the default lifetime, as if by ssh-add(1). If this option is set to ask, ssh(1) will require confirmation using the SSH_ASKPASS program before adding a key (see ssh-add(1) for details). If this option is set to confirm, each use of the key must be confirmed, as if the -c option was specified to ssh-add(1). If this option is set to no, no keys are added to the agent. Alternately, this option may be specified as a time interval using the format described in the TIME FORMATS section of sshd_config(5) to specify the key's lifetime in ssh-agent(1), after which it will automatically be removed. The argument must be no (the default), yes, confirm (optionally followed by a time interval), ask or a time interval.`, + Value: docvalues.StringValue{}, + }, + "AddressFamily": docvalues.DocumentationValue{ + Documentation: `Specifies which address family to use when connecting. Valid arguments are any (the default), inet + (use IPv4 only), or inet6 (use IPv6 only).`, + Value: docvalues.StringValue{}, + }, + "BatchMode": docvalues.DocumentationValue{ + Documentation: `If set to yes, user interaction such as password prompts and host key confirmation requests will be disabled. This option is useful in scripts and other batch jobs where no user is present to interact with ssh(1). The argument must be yes or no (the default).`, + Value: docvalues.StringValue{}, + }, + "BindAddress": docvalues.DocumentationValue{ + Documentation: `Use the specified address on the local machine as the source address of the connection. Only useful on systems with more than one address.`, + Value: docvalues.StringValue{}, + }, + "BindInterface": docvalues.DocumentationValue{ + Documentation: `Use the address of the specified interface on the local machine as the source address of the connection.`, + Value: docvalues.StringValue{}, + }, + "CanonicalDomains": docvalues.DocumentationValue{ + Documentation: `When CanonicalizeHostname is enabled, this option specifies the list of domain suffixes in which to search for the specified destination host.`, + Value: docvalues.StringValue{}, + }, + "CanonicalizeFallbackLocal": docvalues.DocumentationValue{ + Documentation: `Specifies whether to fail with an error when hostname canonicalization fails. The default, yes, will attempt to look up the unqualified hostname using the system resolver's search rules. A value of no will cause ssh(1) to fail instantly if CanonicalizeHostname is enabled and the target hostname cannot be found in any of the domains specified by CanonicalDomains.`, + Value: docvalues.StringValue{}, + }, + "CanonicalizeHostname": docvalues.DocumentationValue{ + Documentation: `Controls whether explicit hostname canonicalization is performed. The default, no, is not to perform any name rewriting and let the system resolver handle all hostname lookups. If set to yes then, for connections that do not use a ProxyCommand or ProxyJump, ssh(1) will attempt to canonicalize the hostname specified on the command line using the CanonicalDomains suffixes and CanonicalizePermittedCNAMEs rules. If CanonicalizeHostname is set to always, then canonicalization is applied to proxied connections too. + If this option is enabled, then the configuration files are processed again using the new target name to pick up any new configuration in matching Host and Match stanzas. A value of none disables the use of a ProxyJump host.`, + Value: docvalues.StringValue{}, + }, + "CanonicalizeMaxDots": docvalues.DocumentationValue{ + Documentation: `Specifies the maximum number of dot characters in a hostname before canonicalization is disabled. The default, 1, allows a single dot (i.e. hostname.subdomain).`, + Value: docvalues.StringValue{}, + }, + "CanonicalizePermittedCNAMEs": docvalues.DocumentationValue{ + Documentation: `Specifies rules to determine whether CNAMEs should be followed when canonicalizing hostnames. The rules consist of one or more arguments of source_domain_list:target_domain_list, where source_domain_list is a pattern-list of domains that may follow CNAMEs in canonicalization, and target_domain_list is a pattern-list of domains that they may resolve to. + For example, + '*.a.example.com:*.b.example.com,*.c.example.com' will allow hostnames matching '*.a.example.com' to be canonicalized to names in the '*.b.example.com' or '*.c.example.com' domains. + A single argument of 'none' causes no CNAMEs to be considered for canonicalization. This is the default behaviour.`, + Value: docvalues.StringValue{}, + }, + "CASignatureAlgorithms": docvalues.DocumentationValue{ + Documentation: `Specifies which algorithms are allowed for signing of certificates by certificate authorities (CAs). The default is: + + ssh-ed25519,ecdsa-sha2-nistp256, +ecdsa-sha2-nistp384,ecdsa-sha2-nistp521, +sk-ssh-ed25519@openssh.com, +sk-ecdsa-sha2-nistp256@openssh.com, +rsa-sha2-512,rsa-sha2-256 + + If the specified list begins with a ‘+’ character, then the specified algorithms will be appended to the default set instead of replacing them. If the specified list begins with a + ‘-’ character, then the specified algorithms (including wildcards) will be removed from the default set instead of replacing them. + ssh(1) will not accept host certificates signed using algorithms other than those specified.`, + Value: docvalues.StringValue{}, + }, + "CertificateFile": docvalues.DocumentationValue{ + Documentation: `Specifies a file from which the user's certificate is read. A corresponding private key must be provided separately in order to use this certificate either from an IdentityFile directive or -i flag to ssh(1), via ssh-agent(1), or via a PKCS11Provider or SecurityKeyProvider. + Arguments to CertificateFile may use the tilde syntax to refer to a user's home directory, the tokens described in the TOKENS section and environment variables as described in the ENVIRONMENT VARIABLES section. + It is possible to have multiple certificate files specified in configuration files; these certificates will be tried in sequence. Multiple CertificateFile directives will add to the list of certificates used for authentication.`, + Value: docvalues.StringValue{}, + }, + "ChannelTimeout": docvalues.DocumentationValue{ + Documentation: `Open X11 forwarding sessions.`, + Value: docvalues.StringValue{}, + }, + "CheckHostIP": docvalues.DocumentationValue{ + Documentation: `If set to yes, ssh(1) will additionally check the host IP address in the known_hosts file. This allows it to detect if a host key changed due to DNS spoofing and will add addresses of destination hosts to ~/.ssh/known_hosts in the process, regardless of the setting of StrictHostKeyChecking. If the option is set to no (the default), the check will not be + executed.`, + Value: docvalues.StringValue{}, + }, + "Ciphers": docvalues.DocumentationValue{ + Documentation: `Specifies the ciphers allowed and their order of preference. Multiple ciphers must be comma-separated. If the specified list begins with a + ‘+’ character, then the specified ciphers will be appended to the default set instead of replacing them. If the specified list begins with a ‘-’ character, then the specified ciphers (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a ‘^’ character, then the specified ciphers will be placed at the head of the default set. + The supported ciphers are: + + 3des-cbc +aes128-cbc +aes192-cbc +aes256-cbc +aes128-ctr +aes192-ctr +aes256-ctr +aes128-gcm@openssh.com +aes256-gcm@openssh.com +chacha20-poly1305@openssh.com + + The default is: + + chacha20-poly1305@openssh.com, +aes128-ctr,aes192-ctr,aes256-ctr, +aes128-gcm@openssh.com,aes256-gcm@openssh.com + + The list of available ciphers may also be obtained using + 'ssh -Q cipher'.`, + Value: docvalues.StringValue{}, + }, + "ClearAllForwardings": docvalues.DocumentationValue{ + Documentation: `Specifies that all local, remote, and dynamic port forwardings specified in the configuration files or on the command line be cleared. This option is primarily useful when used from the ssh(1) command line to clear port forwardings set in configuration files, and is automatically set by scp(1) and sftp(1). The argument must be yes or no (the default).`, + Value: docvalues.StringValue{}, + }, + "Compression": docvalues.DocumentationValue{ + Documentation: `Specifies whether to use compression. The argument must be yes or no (the + default).`, + Value: docvalues.StringValue{}, + }, + "ConnectionAttempts": docvalues.DocumentationValue{ + Documentation: `Specifies the number of tries (one per second) to make before exiting. The argument must be an integer. This may be useful in scripts if the connection sometimes fails. The default is 1.`, + Value: docvalues.StringValue{}, + }, + "ConnectTimeout": docvalues.DocumentationValue{ + Documentation: `Specifies the timeout (in seconds) used when connecting to the SSH server, instead of using the default system TCP timeout. This timeout is applied both to establishing the connection and to performing the initial SSH protocol handshake and key exchange.`, + Value: docvalues.StringValue{}, + }, + "ControlMaster": docvalues.DocumentationValue{ + Documentation: `Enables the sharing of multiple sessions over a single network connection. When set to yes, ssh(1) will listen for connections on a control socket specified using the ControlPath argument. Additional sessions can connect to this socket using the same ControlPath with ControlMaster set to no (the default). These sessions will try to reuse the master instance's network connection rather than initiating new ones, but will fall back to connecting normally if the control socket does not exist, or is not listening. + Setting this to ask will cause ssh(1) to listen for control connections, but require confirmation using ssh-askpass(1). If the ControlPath cannot be opened, ssh(1) will continue without connecting to a master instance. + X11 and ssh-agent(1) forwarding is supported over these multiplexed connections, however the display and agent forwarded will be the one belonging to the master connection i.e. it is not possible to forward multiple displays or agents. + Two additional options allow for opportunistic multiplexing: try to use a master connection but fall back to creating a new one if one does not already exist. These options are: auto and autoask. The latter requires confirmation like the ask option.`, + Value: docvalues.StringValue{}, + }, + "ControlPath": docvalues.DocumentationValue{ + Documentation: `Specify the path to the control socket used for connection sharing as described in the ControlMaster section above or the string none to disable connection sharing. Arguments to ControlPath may use the tilde syntax to refer to a user's home directory, the tokens described in the TOKENS section and environment variables as described in the ENVIRONMENT VARIABLES section. It is recommended that any ControlPath used for opportunistic connection sharing include at least %h, %p, and %r + (or alternatively %C) and be placed in a directory that is not writable by other users. This ensures that shared connections are uniquely + identified.`, + Value: docvalues.StringValue{}, + }, + "ControlPersist": docvalues.DocumentationValue{ + Documentation: `When used in conjunction with ControlMaster, specifies that the master connection should remain open in the background + (waiting for future client connections) after the initial client connection has been closed. If set to no (the default), then the master connection will not be placed into the background, and will close as soon as the initial client connection is closed. If set to yes or 0, then the master connection will remain in the background indefinitely (until killed or closed via a mechanism such as the 'ssh -O exit'). If set to a time in seconds, or a time in any of the formats documented in sshd_config(5), then the backgrounded master connection will automatically terminate after it has remained idle (with no client connections) for the specified time.`, + Value: docvalues.StringValue{}, + }, + "DynamicForward": docvalues.DocumentationValue{ + Documentation: `Specifies that a TCP port on the local machine be forwarded over the secure channel, and the application protocol is then used to determine where to connect to from the remote machine. + The argument must be + [bind_address:]port. IPv6 addresses can be specified by enclosing addresses in square brackets. By default, the local port is bound in accordance with the GatewayPorts setting. However, an explicit bind_address may be used to bind the connection to a specific address. The bind_address of localhost indicates that the listening port be bound for local use only, while an empty address or ‘*’ indicates that the port should be available from all interfaces. + Currently the SOCKS4 and SOCKS5 protocols are supported, and ssh(1) will act as a SOCKS server. Multiple forwardings may be specified, and additional forwardings can be given on the command line. Only the superuser can forward privileged ports.`, + Value: docvalues.StringValue{}, + }, + "EnableEscapeCommandline": docvalues.DocumentationValue{ + Documentation: `Enables the command line option in the EscapeChar menu for interactive sessions (default + ‘~C’). By default, the command line is disabled.`, + Value: docvalues.StringValue{}, + }, + "EnableSSHKeysign": docvalues.DocumentationValue{ + Documentation: `Setting this option to yes in the global client configuration file /etc/ssh/ssh_config enables the use of the helper program ssh-keysign(8) during HostbasedAuthentication. The argument must be yes or no (the default). This option should be placed in the non-hostspecific section. See ssh-keysign(8) for more information.`, + Value: docvalues.StringValue{}, + }, + "EscapeChar": docvalues.DocumentationValue{ + Documentation: `Sets the escape character (default: + ‘~’). The escape character can also be set on the command line. The argument should be a single character, + ‘^’ followed by a letter, or none to disable the escape character entirely + (making the connection transparent for binary data).`, + Value: docvalues.StringValue{}, + }, + "ExitOnForwardFailure": docvalues.DocumentationValue{ + Documentation: `Specifies whether ssh(1) should terminate the connection if it cannot set up all requested dynamic, tunnel, local, and remote port forwardings, (e.g. if either end is unable to bind and listen on a specified port). Note that ExitOnForwardFailure does not apply to connections made over port forwardings and will not, for example, cause ssh(1) to exit if TCP connections to the ultimate forwarding destination fail. The argument must be yes or no + (the default).`, + Value: docvalues.StringValue{}, + }, + "FingerprintHash": docvalues.DocumentationValue{ + Documentation: `Specifies the hash algorithm used when displaying key fingerprints. Valid options are: md5 and sha256 (the default).`, + Value: docvalues.StringValue{}, + }, + "ForkAfterAuthentication": docvalues.DocumentationValue{ + Documentation: `Requests ssh to go to background just before command execution. This is useful if ssh is going to ask for passwords or passphrases, but the user wants it in the background. This implies the StdinNull configuration option being set to “yes”. The recommended way to start X11 programs at a remote site is with something like ssh -f host xterm, which is the same as ssh host xterm if the ForkAfterAuthentication configuration option is set to “yes”. + If the ExitOnForwardFailure configuration option is set to “yes”, then a client started with the ForkAfterAuthentication configuration option being set to “yes” will wait for all remote port forwards to be successfully established before placing itself in the background. The argument to this keyword must be yes (same as the -f option) or no (the default).`, + Value: docvalues.StringValue{}, + }, + "ForwardAgent": docvalues.DocumentationValue{ + Documentation: `Specifies whether the connection to the authentication agent (if any) will be forwarded to the remote machine. The argument may be yes, no (the default), an explicit path to an agent socket or the name of an environment variable + (beginning with ‘$’) in which to find the path. + Agent forwarding should be enabled with caution. Users with the ability to bypass file permissions on the remote host (for the agent's Unix-domain socket) can access the local agent through the forwarded connection. An attacker cannot obtain key material from the agent, however they can perform operations on the keys that enable them to authenticate using the identities loaded into the agent.`, + Value: docvalues.StringValue{}, + }, + "ForwardX11": docvalues.DocumentationValue{ + Documentation: `Specifies whether X11 connections will be automatically redirected over the secure channel and DISPLAY set. The argument must be yes or no (the default). + X11 forwarding should be enabled with caution. Users with the ability to bypass file permissions on the remote host (for the user's X11 authorization database) can access the local X11 display through the forwarded connection. An attacker may then be able to perform activities such as keystroke monitoring if the ForwardX11Trusted option is also enabled.`, + Value: docvalues.StringValue{}, + }, + "ForwardX11Timeout": docvalues.DocumentationValue{ + Documentation: `Specify a timeout for untrusted X11 forwarding using the format described in the TIME FORMATS section of sshd_config(5). X11 connections received by ssh(1) after this time will be refused. Setting ForwardX11Timeout to zero will disable the timeout and permit X11 forwarding for the life of the connection. The default is to disable untrusted X11 forwarding after twenty minutes has elapsed.`, + Value: docvalues.StringValue{}, + }, + "ForwardX11Trusted": docvalues.DocumentationValue{ + Documentation: `If this option is set to yes, remote X11 clients will have full access to the original X11 display. + If this option is set to no (the default), remote X11 clients will be considered untrusted and prevented from stealing or tampering with data belonging to trusted X11 clients. Furthermore, the xauth(1) token used for the session will be set to expire after 20 minutes. Remote clients will be refused access after this time. + See the X11 SECURITY extension specification for full details on the restrictions imposed on untrusted clients.`, + Value: docvalues.StringValue{}, + }, + "GatewayPorts": docvalues.DocumentationValue{ + Documentation: `Specifies whether remote hosts are allowed to connect to local forwarded ports. By default, ssh(1) binds local port forwardings to the loopback address. This prevents other remote hosts from connecting to forwarded ports. GatewayPorts can be used to specify that ssh should bind local port forwardings to the wildcard address, thus allowing remote hosts to connect to forwarded ports. The argument must be yes or no (the + default).`, + Value: docvalues.StringValue{}, + }, + "GlobalKnownHostsFile": docvalues.DocumentationValue{ + Documentation: `Specifies one or more files to use for the global host key database, separated by whitespace. The default is + /etc/ssh/ssh_known_hosts, + /etc/ssh/ssh_known_hosts2.`, + Value: docvalues.StringValue{}, + }, + "GSSAPIAuthentication": docvalues.DocumentationValue{ + Documentation: `Specifies whether user authentication based on GSSAPI is allowed. The default is no.`, + Value: docvalues.StringValue{}, + }, + "GSSAPIDelegateCredentials": docvalues.DocumentationValue{ + Documentation: `Forward (delegate) credentials to the server. The default is no.`, + Value: docvalues.StringValue{}, + }, + "HashKnownHosts": docvalues.DocumentationValue{ + Documentation: `Indicates that ssh(1) should hash host names and addresses when they are added to + ~/.ssh/known_hosts. These hashed names may be used normally by ssh(1) and sshd(8), but they do not visually reveal identifying information if the file's contents are disclosed. The default is no. Note that existing names and addresses in known hosts files will not be converted automatically, but may be manually hashed using ssh-keygen(1).`, + Value: docvalues.StringValue{}, + }, + "HostbasedAcceptedAlgorithms": docvalues.DocumentationValue{ + Documentation: `Specifies the signature algorithms that will be used for hostbased authentication as a comma-separated list of patterns. Alternately if the specified list begins with a ‘+’ character, then the specified signature algorithms will be appended to the default set instead of replacing them. If the specified list begins with a ‘-’ character, then the specified signature algorithms (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a ‘^’ character, then the specified signature algorithms will be placed at the head of the default set. The default for this option is: + + ssh-ed25519-cert-v01@openssh.com, +ecdsa-sha2-nistp256-cert-v01@openssh.com, +ecdsa-sha2-nistp384-cert-v01@openssh.com, +ecdsa-sha2-nistp521-cert-v01@openssh.com, +sk-ssh-ed25519-cert-v01@openssh.com, +sk-ecdsa-sha2-nistp256-cert-v01@openssh.com, +rsa-sha2-512-cert-v01@openssh.com, +rsa-sha2-256-cert-v01@openssh.com, +ssh-ed25519, +ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521, +sk-ssh-ed25519@openssh.com, +sk-ecdsa-sha2-nistp256@openssh.com, +rsa-sha2-512,rsa-sha2-256 + + The -Q option of ssh(1) may be used to list supported signature algorithms. This was formerly named HostbasedKeyTypes.`, + Value: docvalues.StringValue{}, + }, + "HostbasedAuthentication": docvalues.DocumentationValue{ + Documentation: `Specifies whether to try rhosts based authentication with public key authentication. The argument must be yes or no (the default).`, + Value: docvalues.StringValue{}, + }, + "HostKeyAlgorithms": docvalues.DocumentationValue{ + Documentation: `Specifies the host key signature algorithms that the client wants to use in order of preference. Alternately if the specified list begins with a + ‘+’ character, then the specified signature algorithms will be appended to the default set instead of replacing them. If the specified list begins with a ‘-’ character, then the specified signature algorithms (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a + ‘^’ character, then the specified signature algorithms will be placed at the head of the default set. The default for this option is: + + ssh-ed25519-cert-v01@openssh.com, +ecdsa-sha2-nistp256-cert-v01@openssh.com, +ecdsa-sha2-nistp384-cert-v01@openssh.com, +ecdsa-sha2-nistp521-cert-v01@openssh.com, +sk-ssh-ed25519-cert-v01@openssh.com, +sk-ecdsa-sha2-nistp256-cert-v01@openssh.com, +rsa-sha2-512-cert-v01@openssh.com, +rsa-sha2-256-cert-v01@openssh.com, +ssh-ed25519, +ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521, +sk-ecdsa-sha2-nistp256@openssh.com, +sk-ssh-ed25519@openssh.com, +rsa-sha2-512,rsa-sha2-256 + + If hostkeys are known for the destination host then this default is modified to prefer their algorithms. + The list of available signature algorithms may also be obtained using 'ssh -Q HostKeyAlgorithms'.`, + Value: docvalues.StringValue{}, + }, + "HostKeyAlias": docvalues.DocumentationValue{ + Documentation: `Specifies an alias that should be used instead of the real host name when looking up or saving the host key in the host key database files and when validating host certificates. This option is useful for tunneling SSH connections or for multiple servers running on a single host.`, + Value: docvalues.StringValue{}, + }, + "Hostname": docvalues.DocumentationValue{ + Documentation: `Specifies the real host name to log into. This can be used to specify nicknames or abbreviations for hosts. Arguments to Hostname accept the tokens described in the TOKENS section. Numeric IP addresses are also permitted (both on the command line and in Hostname specifications). The default is the name given on the command line.`, + Value: docvalues.StringValue{}, + }, + "IdentitiesOnly": docvalues.DocumentationValue{ + Documentation: `Specifies that ssh(1) should only use the configured authentication identity and certificate files (either the default files, or those explicitly configured in the ssh_config files or passed on the ssh(1) command-line), even if ssh-agent(1) or a PKCS11Provider or SecurityKeyProvider offers more identities. The argument to this keyword must be yes or no (the default). This option is intended for situations where ssh-agent offers many different identities.`, + Value: docvalues.StringValue{}, + }, + "IdentityAgent": docvalues.DocumentationValue{ + Documentation: `Specifies the UNIX-domain socket used to communicate with the authentication agent. + This option overrides the SSH_AUTH_SOCK environment variable and can be used to select a specific agent. Setting the socket name to none disables the use of an authentication agent. If the string 'SSH_AUTH_SOCK' is specified, the location of the socket will be read from the SSH_AUTH_SOCK environment variable. Otherwise if the specified value begins with a ‘$’ character, then it will be treated as an environment variable containing the location of the socket. + Arguments to IdentityAgent may use the tilde syntax to refer to a user's home directory, the tokens described in the TOKENS section and environment variables as described in the ENVIRONMENT VARIABLES section.`, + Value: docvalues.StringValue{}, + }, + "IdentityFile": docvalues.DocumentationValue{ + Documentation: `Specifies a file from which the user's ECDSA, authenticator-hosted ECDSA, Ed25519, authenticator-hosted Ed25519 or RSA authentication identity is read. You can also specify a public key file to use the corresponding private key that is loaded in ssh-agent(1) when the private key file is not present locally. The default is ~/.ssh/id_rsa, + ~/.ssh/id_ecdsa, + ~/.ssh/id_ecdsa_sk, + ~/.ssh/id_ed25519 and + ~/.ssh/id_ed25519_sk. Additionally, any identities represented by the authentication agent will be used for authentication unless IdentitiesOnly is set. If no certificates have been explicitly specified by CertificateFile, ssh(1) will try to load certificate information from the filename obtained by appending -cert.pub to the path of a specified IdentityFile. + Arguments to IdentityFile may use the tilde syntax to refer to a user's home directory or the tokens described in the TOKENS section. Alternately an argument of none may be used to indicate no identity files should be loaded. + It is possible to have multiple identity files specified in configuration files; all these identities will be tried in sequence. Multiple IdentityFile directives will add to the list of identities tried (this behaviour differs from that of other configuration directives). + IdentityFile may be used in conjunction with IdentitiesOnly to select which identities in an agent are offered during authentication. IdentityFile may also be used in conjunction with CertificateFile in order to provide any certificate also needed for authentication with the identity.`, + Value: docvalues.StringValue{}, + }, + "IgnoreUnknown": docvalues.DocumentationValue{ + Documentation: `Specifies a pattern-list of unknown options to be ignored if they are encountered in configuration parsing. This may be used to suppress errors if ssh_config contains options that are unrecognised by ssh(1). It is recommended that IgnoreUnknown be listed early in the configuration file as it will not be applied to unknown options that appear before + it.`, + Value: docvalues.StringValue{}, + }, + "Include": docvalues.DocumentationValue{ + Documentation: `Include the specified configuration file(s). Multiple pathnames may be specified and each pathname may contain glob(7) wildcards, tokens as described in the TOKENS section, environment variables as described in the ENVIRONMENT VARIABLES section and, for user configurations, shell-like + ‘~’ references to user home directories. Wildcards will be expanded and processed in lexical order. Files without absolute paths are assumed to be in ~/.ssh if included in a user configuration file or /etc/ssh if included from the system configuration file. Include directive may appear inside a Match or Host block to perform conditional inclusion.`, + Value: docvalues.StringValue{}, + }, + "IPQoS": docvalues.DocumentationValue{ + Documentation: `Specifies the IPv4 type-of-service or DSCP class for connections. Accepted values are af11, af12, af13, af21, af22, af23, af31, af32, af33, af41, af42, af43, cs0, cs1, cs2, cs3, cs4, cs5, cs6, cs7, ef, le, lowdelay, throughput, reliability, a numeric value, or none to use the operating system default. This option may take one or two arguments, separated by whitespace. If one argument is specified, it is used as the packet class unconditionally. If two values are specified, the first is automatically selected for interactive sessions and the second for non-interactive sessions. The default is af21 (Low-Latency Data) for interactive sessions and cs1 (Lower Effort) for non-interactive sessions.`, + Value: docvalues.StringValue{}, + }, + "KbdInteractiveAuthentication": docvalues.DocumentationValue{ + Documentation: `Specifies whether to use keyboard-interactive authentication. The argument to this keyword must be yes (the default) or no. ChallengeResponseAuthentication is a deprecated alias for this.`, + Value: docvalues.StringValue{}, + }, + "KbdInteractiveDevices": docvalues.DocumentationValue{ + Documentation: `Specifies the list of methods to use in keyboard-interactive authentication. Multiple method names must be comma-separated. The default is to use the server specified list. The methods available vary depending on what the server supports. For an OpenSSH server, it may be zero or more of: bsdauth, pam, and skey.`, + Value: docvalues.StringValue{}, + }, + "KexAlgorithms": docvalues.DocumentationValue{ + Documentation: `Specifies the permitted KEX (Key Exchange) algorithms that will be used and their preference order. The selected algorithm will be the first algorithm in this list that the server also supports. Multiple algorithms must be comma-separated. + If the specified list begins with a ‘+’ character, then the specified algorithms will be appended to the default set instead of replacing them. If the specified list begins with a + ‘-’ character, then the specified algorithms (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a ‘^’ character, then the specified algorithms will be placed at the head of the default set. + The default is: + + sntrup761x25519-sha512,sntrup761x25519-sha512@openssh.com, +mlkem768x25519-sha256, +curve25519-sha256,curve25519-sha256@libssh.org, +ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521, +diffie-hellman-group-exchange-sha256, +diffie-hellman-group16-sha512, +diffie-hellman-group18-sha512, +diffie-hellman-group14-sha256 + + The list of supported key exchange algorithms may also be obtained using 'ssh -Q kex'.`, + Value: docvalues.StringValue{}, + }, + "KnownHostsCommand": docvalues.DocumentationValue{ + Documentation: `Specifies a command to use to obtain a list of host keys, in addition to those listed in UserKnownHostsFile and GlobalKnownHostsFile. This command is executed after the files have been read. It may write host key lines to standard output in identical format to the usual files (described in the VERIFYING HOST KEYS section in ssh(1)). Arguments to KnownHostsCommand accept the tokens described in the TOKENS section. The command may be invoked multiple times per connection: once when preparing the preference list of host key algorithms to use, again to obtain the host key for the requested host name and, if CheckHostIP is enabled, one more time to obtain the host key matching the server's address. If the command exits abnormally or returns a non-zero exit status then the connection is terminated.`, + Value: docvalues.StringValue{}, + }, + "LocalCommand": docvalues.DocumentationValue{ + Documentation: `Specifies a command to execute on the local machine after successfully connecting to the server. The command string extends to the end of the line, and is executed with the user's shell. Arguments to LocalCommand accept the tokens described in the TOKENS section. + The command is run synchronously and does not have access to the session of the ssh(1) that spawned it. It should not be used for interactive commands. + This directive is ignored unless PermitLocalCommand has been enabled.`, + Value: docvalues.StringValue{}, + }, + "LocalForward": docvalues.DocumentationValue{ + Documentation: `Specifies that a TCP port on the local machine be forwarded over the secure channel to the specified host and port from the remote machine. The first argument specifies the listener and may be + [bind_address:]port or a Unix domain socket path. The second argument is the destination and may be host:hostport or a Unix domain socket path if the remote host supports it. + IPv6 addresses can be specified by enclosing addresses in square brackets. Multiple forwardings may be specified, and additional forwardings can be given on the command line. Only the superuser can forward privileged ports. By default, the local port is bound in accordance with the GatewayPorts setting. However, an explicit bind_address may be used to bind the connection to a specific address. The bind_address of localhost indicates that the listening port be bound for local use only, while an empty address or ‘*’ indicates that the port should be available from all interfaces. Unix domain socket paths may use the tokens described in the TOKENS section and environment variables as described in the ENVIRONMENT VARIABLES section.`, + Value: docvalues.StringValue{}, + }, + "LogLevel": docvalues.DocumentationValue{ + Documentation: `Gives the verbosity level that is used when logging messages from ssh(1). The possible values are: QUIET, FATAL, ERROR, INFO, VERBOSE, DEBUG, DEBUG1, DEBUG2, and DEBUG3. The default is INFO. DEBUG and DEBUG1 are equivalent. DEBUG2 and DEBUG3 each specify higher levels of verbose output.`, + Value: docvalues.StringValue{}, + }, + "LogVerbose": docvalues.DocumentationValue{ + Documentation: `Specify one or more overrides to LogLevel. An override consists of one or more pattern lists that matches the source file, function and line number to force detailed logging for. For example, an override pattern of: + + kex.c:*:1000,*:kex_exchange_identification():*,packet.c:* + + would enable detailed logging for line 1000 of kex.c, everything in the kex_exchange_identification() function, and all code in the packet.c file. This option is intended for debugging and no overrides are enabled by default.`, + Value: docvalues.StringValue{}, + }, + "MACs": docvalues.DocumentationValue{ + Documentation: `Specifies the MAC (message authentication code) algorithms in order of preference. The MAC algorithm is used for data integrity protection. Multiple algorithms must be comma-separated. If the specified list begins with a ‘+’ character, then the specified algorithms will be appended to the default set instead of replacing them. If the specified list begins with a ‘-’ character, then the specified algorithms (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a + ‘^’ character, then the specified algorithms will be placed at the head of the default set. + The algorithms that contain '-etm' calculate the MAC after encryption (encrypt-then-mac). These are considered safer and their use recommended. + The default is: + + umac-64-etm@openssh.com,umac-128-etm@openssh.com, +hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com, +hmac-sha1-etm@openssh.com, +umac-64@openssh.com,umac-128@openssh.com, +hmac-sha2-256,hmac-sha2-512,hmac-sha1 + + The list of available MAC algorithms may also be obtained using 'ssh -Q mac'.`, + Value: docvalues.StringValue{}, + }, + "NoHostAuthenticationForLocalhost": docvalues.DocumentationValue{ + Documentation: `Disable host authentication for localhost (loopback addresses). The argument to this keyword must be yes or no (the default).`, + Value: docvalues.StringValue{}, + }, + "NumberOfPasswordPrompts": docvalues.DocumentationValue{ + Documentation: `Specifies the number of password prompts before giving up. The argument to this keyword must be an integer. The default is 3.`, + Value: docvalues.StringValue{}, + }, + "ObscureKeystrokeTiming": docvalues.DocumentationValue{ + Documentation: `Specifies whether ssh(1) should try to obscure inter-keystroke timings from passive observers of network traffic. If enabled, then for interactive sessions, ssh(1) will send keystrokes at fixed intervals of a few tens of milliseconds and will send fake keystroke packets for some time after typing ceases. The argument to this keyword must be yes, no or an interval specifier of the form interval:milliseconds (e.g. interval:80 for 80 milliseconds). The default is to obscure keystrokes using a 20ms packet interval. Note that smaller intervals will result in higher fake keystroke packet rates.`, + Value: docvalues.StringValue{}, + }, + "PasswordAuthentication": docvalues.DocumentationValue{ + Documentation: `Specifies whether to use password authentication. The argument to this keyword must be yes (the default) or no.`, + Value: docvalues.StringValue{}, + }, + "PermitLocalCommand": docvalues.DocumentationValue{ + Documentation: `Allow local command execution via the LocalCommand option or using the !command escape sequence in ssh(1). The argument must be yes or no (the default).`, + Value: docvalues.StringValue{}, + }, + "PermitRemoteOpen": docvalues.DocumentationValue{ + Documentation: `Specifies the destinations to which remote TCP port forwarding is permitted when RemoteForward is used as a SOCKS proxy. The forwarding specification must be one of the following forms: + + PermitRemoteOpen host:port PermitRemoteOpen IPv4_addr:port PermitRemoteOpen + [IPv6_addr]:port + + Multiple forwards may be specified by separating them with whitespace. An argument of any can be used to remove all restrictions and permit any forwarding requests. An argument of none can be used to prohibit all forwarding requests. The wildcard ‘*’ can be used for host or port to allow all hosts or ports respectively. Otherwise, no pattern matching or address lookups are performed on supplied names.`, + Value: docvalues.StringValue{}, + }, + "PKCS11Provider": docvalues.DocumentationValue{ + Documentation: `Specifies which PKCS#11 provider to use or none to indicate that no provider should be used (the default). The argument to this keyword is a path to the PKCS#11 shared library ssh(1) should use to communicate with a PKCS#11 token providing keys for user authentication.`, + Value: docvalues.StringValue{}, + }, + "Port": docvalues.DocumentationValue{ + Documentation: `Specifies the port number to connect on the remote host. The default is 22.`, + Value: docvalues.StringValue{}, + }, + "PreferredAuthentications": docvalues.DocumentationValue{ + Documentation: `Specifies the order in which the client should try authentication methods. This allows a client to prefer one method (e.g. keyboard-interactive) over another method (e.g. password). The default is: + + gssapi-with-mic,hostbased,publickey, +keyboard-interactive,password`, + Value: docvalues.StringValue{}, + }, + "ProxyCommand": docvalues.DocumentationValue{ + Documentation: `Specifies the command to use to connect to the server. The command string extends to the end of the line, and is executed using the user's shell + ‘exec’ directive to avoid a lingering shell process. + Arguments to ProxyCommand accept the tokens described in the TOKENS section. The command can be basically anything, and should read from its standard input and write to its standard output. It should eventually connect an sshd(8) server running on some machine, or execute sshd + -i somewhere. Host key management will be done using the Hostname of the host being connected (defaulting to the name typed by the user). Setting the command to none disables this option entirely. Note that CheckHostIP is not available for connects with a proxy command. + This directive is useful in conjunction with nc(1) and its proxy support. For example, the following directive would connect via an HTTP proxy at 192.0.2.0: + + ProxyCommand /usr/bin/nc -X connect -x 192.0.2.0:8080 %h %p`, + Value: docvalues.StringValue{}, + }, + "ProxyJump": docvalues.DocumentationValue{ + Documentation: `Specifies one or more jump proxies as either + [user@]host[:port] or an ssh URI. Multiple proxies may be separated by comma characters and will be visited sequentially. Setting this option will cause ssh(1) to connect to the target host by first making a ssh(1) connection to the specified ProxyJump host and then establishing a TCP forwarding to the ultimate target from there. Setting the host to none disables this option entirely. + Note that this option will compete with the ProxyCommand option - whichever is specified first will prevent later instances of the other from taking effect. + Note also that the configuration for the destination host + (either supplied via the command-line or the configuration file) is not generally applied to jump hosts. ~/.ssh/config should be used if specific configuration is required for jump hosts.`, + Value: docvalues.StringValue{}, + }, + "ProxyUseFdpass": docvalues.DocumentationValue{ + Documentation: `Specifies that ProxyCommand will pass a connected file descriptor back to ssh(1) instead of continuing to execute and pass data. The default is no.`, + Value: docvalues.StringValue{}, + }, + "PubkeyAcceptedAlgorithms": docvalues.DocumentationValue{ + Documentation: `Specifies the signature algorithms that will be used for public key authentication as a comma-separated list of patterns. If the specified list begins with a ‘+’ character, then the algorithms after it will be appended to the default instead of replacing it. If the specified list begins with a ‘-’ character, then the specified algorithms (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a + ‘^’ character, then the specified algorithms will be placed at the head of the default set. The default for this option is: + + ssh-ed25519-cert-v01@openssh.com, +ecdsa-sha2-nistp256-cert-v01@openssh.com, +ecdsa-sha2-nistp384-cert-v01@openssh.com, +ecdsa-sha2-nistp521-cert-v01@openssh.com, +sk-ssh-ed25519-cert-v01@openssh.com, +sk-ecdsa-sha2-nistp256-cert-v01@openssh.com, +rsa-sha2-512-cert-v01@openssh.com, +rsa-sha2-256-cert-v01@openssh.com, +ssh-ed25519, +ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521, +sk-ssh-ed25519@openssh.com, +sk-ecdsa-sha2-nistp256@openssh.com, +rsa-sha2-512,rsa-sha2-256 + + The list of available signature algorithms may also be obtained using 'ssh -Q PubkeyAcceptedAlgorithms'.`, + Value: docvalues.StringValue{}, + }, + "PubkeyAuthentication": docvalues.DocumentationValue{ + Documentation: `Specifies whether to try public key authentication. The argument to this keyword must be yes (the default), no, unbound or host-bound. The final two options enable public key authentication while respectively disabling or enabling the OpenSSH host-bound authentication protocol extension required for restricted ssh-agent(1) forwarding.`, + Value: docvalues.StringValue{}, + }, + "RekeyLimit": docvalues.DocumentationValue{ + Documentation: `Specifies the maximum amount of data that may be transmitted or received before the session key is renegotiated, optionally followed by a maximum amount of time that may pass before the session key is renegotiated. The first argument is specified in bytes and may have a suffix of + ‘K’, ‘M’, or ‘G’ to indicate Kilobytes, Megabytes, or Gigabytes, respectively. The default is between + ‘1G’ and ‘4G’, depending on the cipher. The optional second value is specified in seconds and may use any of the units documented in the TIME FORMATS section of sshd_config(5). The default value for RekeyLimit is default none, which means that rekeying is performed after the cipher's default amount of data has been sent or received and no time based rekeying is done.`, + Value: docvalues.StringValue{}, + }, + "RemoteCommand": docvalues.DocumentationValue{ + Documentation: `Specifies a command to execute on the remote machine after successfully connecting to the server. The command string extends to the end of the line, and is executed with the user's shell. Arguments to RemoteCommand accept the tokens described in the TOKENS section.`, + Value: docvalues.StringValue{}, + }, + "RemoteForward": docvalues.DocumentationValue{ + Documentation: `Specifies that a TCP port on the remote machine be forwarded over the secure channel. The remote port may either be forwarded to a specified host and port from the local machine, or may act as a SOCKS 4/5 proxy that allows a remote client to connect to arbitrary destinations from the local machine. The first argument is the listening specification and may be + [bind_address:]port or, if the remote host supports it, a Unix domain socket path. If forwarding to a specific destination then the second argument must be host:hostport or a Unix domain socket path, otherwise if no destination argument is specified then the remote forwarding will be established as a SOCKS proxy. When acting as a SOCKS proxy, the destination of the connection can be restricted by PermitRemoteOpen. + IPv6 addresses can be specified by enclosing addresses in square brackets. Multiple forwardings may be specified, and additional forwardings can be given on the command line. Privileged ports can be forwarded only when logging in as root on the remote machine. Unix domain socket paths may use the tokens described in the TOKENS section and environment variables as described in the ENVIRONMENT VARIABLES section. + If the port argument is 0, the listen port will be dynamically allocated on the server and reported to the client at run time. + If the bind_address is not specified, the default is to only bind to loopback addresses. If the bind_address is + ‘*’ or an empty string, then the forwarding is requested to listen on all interfaces. Specifying a remote bind_address will only succeed if the server's GatewayPorts option is enabled (see sshd_config(5)).`, + Value: docvalues.StringValue{}, + }, + "RequestTTY": docvalues.DocumentationValue{ + Documentation: `Specifies whether to request a pseudo-tty for the session. The argument may be one of: no (never request a TTY), yes (always request a TTY when standard input is a TTY), force (always request a TTY) or auto (request a TTY when opening a login session). This option mirrors the -t and + -T flags for ssh(1).`, + Value: docvalues.StringValue{}, + }, + "RequiredRSASize": docvalues.DocumentationValue{ + Documentation: `Specifies the minimum RSA key size (in bits) that ssh(1) will accept. User authentication keys smaller than this limit will be ignored. Servers that present host keys smaller than this limit will cause the connection to be terminated. The default is 1024 bits. Note that this limit may only be raised from the default.`, + Value: docvalues.StringValue{}, + }, + "RevokedHostKeys": docvalues.DocumentationValue{ + Documentation: `Specifies revoked host public keys. Keys listed in this file will be refused for host authentication. Note that if this file does not exist or is not readable, then host authentication will be refused for all hosts. Keys may be specified as a text file, listing one public key per line, or as an OpenSSH Key Revocation List (KRL) as generated by ssh-keygen(1). For more information on KRLs, see the KEY REVOCATION LISTS section in ssh-keygen(1). Arguments to RevokedHostKeys may use the tilde syntax to refer to a user's home directory, the tokens described in the TOKENS section and environment variables as described in the ENVIRONMENT VARIABLES section.`, + Value: docvalues.StringValue{}, + }, + "SecurityKeyProvider": docvalues.DocumentationValue{ + Documentation: `Specifies a path to a library that will be used when loading any FIDO authenticator-hosted keys, overriding the default of using the built-in USB HID support. + If the specified value begins with a ‘$’ character, then it will be treated as an environment variable containing the path to the library.`, + Value: docvalues.StringValue{}, + }, + "SendEnv": docvalues.DocumentationValue{ + Documentation: `Specifies what variables from the local environ(7) should be sent to the server. The server must also support it, and the server must be configured to accept these environment variables. Note that the TERM environment variable is always sent whenever a pseudo-terminal is requested as it is required by the protocol. Refer to AcceptEnv in sshd_config(5) for how to configure the server. Variables are specified by name, which may contain wildcard characters. Multiple environment variables may be separated by whitespace or spread across multiple SendEnv directives. + See PATTERNS for more information on patterns. + It is possible to clear previously set SendEnv variable names by prefixing patterns with -. The default is not to send any environment variables.`, + Value: docvalues.StringValue{}, + }, + "ServerAliveCountMax": docvalues.DocumentationValue{ + Documentation: `Sets the number of server alive messages (see below) which may be sent without ssh(1) receiving any messages back from the server. If this threshold is reached while server alive messages are being sent, ssh will disconnect from the server, terminating the session. It is important to note that the use of server alive messages is very different from TCPKeepAlive (below). The server alive messages are sent through the encrypted channel and therefore will not be spoofable. The TCP keepalive option enabled by TCPKeepAlive is spoofable. The server alive mechanism is valuable when the client or server depend on knowing when a connection has become unresponsive. + The default value is 3. If, for example, ServerAliveInterval (see below) is set to 15 and ServerAliveCountMax is left at the default, if the server becomes unresponsive, ssh will disconnect after approximately 45 seconds.`, + Value: docvalues.StringValue{}, + }, + "ServerAliveInterval": docvalues.DocumentationValue{ + Documentation: `Sets a timeout interval in seconds after which if no data has been received from the server, ssh(1) will send a message through the encrypted channel to request a response from the server. The default is 0, indicating that these messages will not be sent to the server.`, + Value: docvalues.StringValue{}, + }, + "SessionType": docvalues.DocumentationValue{ + Documentation: `May be used to either request invocation of a subsystem on the remote system, or to prevent the execution of a remote command at all. The latter is useful for just forwarding ports. The argument to this keyword must be none (same as the -N option), subsystem (same as the + -s option) or default + (shell or command execution).`, + Value: docvalues.StringValue{}, + }, + "SetEnv": docvalues.DocumentationValue{ + Documentation: `Directly specify one or more environment variables and their contents to be sent to the server. Similarly to SendEnv, with the exception of the TERM variable, the server must be prepared to accept the environment variable.`, + Value: docvalues.StringValue{}, + }, + "StdinNull": docvalues.DocumentationValue{ + Documentation: `Redirects stdin from /dev/null (actually, prevents reading from stdin). Either this or the equivalent + -n option must be used when ssh is run in the background. The argument to this keyword must be yes (same as the + -n option) or no (the default).`, + Value: docvalues.StringValue{}, + }, + "StreamLocalBindMask": docvalues.DocumentationValue{ + Documentation: `Sets the octal file creation mode mask (umask) used when creating a Unix-domain socket file for local or remote port forwarding. This option is only used for port forwarding to a Unix-domain socket file. + The default value is 0177, which creates a Unix-domain socket file that is readable and writable only by the owner. Note that not all operating systems honor the file mode on Unix-domain socket files.`, + Value: docvalues.StringValue{}, + }, + "StreamLocalBindUnlink": docvalues.DocumentationValue{ + Documentation: `Specifies whether to remove an existing Unix-domain socket file for local or remote port forwarding before creating a new one. If the socket file already exists and StreamLocalBindUnlink is not enabled, ssh will be unable to forward the port to the Unix-domain socket file. This option is only used for port forwarding to a Unix-domain socket file. + The argument must be yes or no (the default).`, + Value: docvalues.StringValue{}, + }, + "StrictHostKeyChecking": docvalues.DocumentationValue{ + Documentation: `If this flag is set to yes, ssh(1) will never automatically add host keys to the + ~/.ssh/known_hosts file, and refuses to connect to hosts whose host key has changed. This provides maximum protection against man-in-the-middle (MITM) attacks, though it can be annoying when the + /etc/ssh/ssh_known_hosts file is poorly maintained or when connections to new hosts are frequently made. This option forces the user to manually add all new hosts. + If this flag is set to accept-new then ssh will automatically add new host keys to the user's known_hosts file, but will not permit connections to hosts with changed host keys. If this flag is set to no or off, ssh will automatically add new host keys to the user known hosts files and allow connections to hosts with changed hostkeys to proceed, subject to some restrictions. If this flag is set to ask (the default), new host keys will be added to the user known host files only after the user has confirmed that is what they really want to do, and ssh will refuse to connect to hosts whose host key has changed. The host keys of known hosts will be verified automatically in all cases.`, + Value: docvalues.StringValue{}, + }, + "SyslogFacility": docvalues.DocumentationValue{ + Documentation: `Gives the facility code that is used when logging messages from ssh(1). The possible values are: DAEMON, USER, AUTH, LOCAL0, LOCAL1, LOCAL2, LOCAL3, LOCAL4, LOCAL5, LOCAL6, LOCAL7. The default is USER.`, + Value: docvalues.StringValue{}, + }, + "TCPKeepAlive": docvalues.DocumentationValue{ + Documentation: `Specifies whether the system should send TCP keepalive messages to the other side. If they are sent, death of the connection or crash of one of the machines will be properly noticed. However, this means that connections will die if the route is down temporarily, and some people find it annoying. + The default is yes (to send TCP keepalive messages), and the client will notice if the network goes down or the remote host dies. This is important in scripts, and many users want it too. + To disable TCP keepalive messages, the value should be set to no. See also ServerAliveInterval for protocol-level keepalives.`, + Value: docvalues.StringValue{}, + }, + "Tag": docvalues.DocumentationValue{ + Documentation: `Specify a configuration tag name that may be later used by a Match directive to select a block of configuration.`, + Value: docvalues.StringValue{}, + }, + "Tunnel": docvalues.DocumentationValue{ + Documentation: `Request tun(4) device forwarding between the client and the server. The argument must be yes, point-to-point (layer 3), ethernet (layer 2), or no (the default). Specifying yes requests the default tunnel mode, which is point-to-point.`, + Value: docvalues.StringValue{}, + }, + "TunnelDevice": docvalues.DocumentationValue{ + Documentation: `Specifies the tun(4) devices to open on the client + (local_tun) and the server + (remote_tun). + The argument must be local_tun[:remote_tun]. The devices may be specified by numerical ID or the keyword any, which uses the next available tunnel device. If remote_tun is not specified, it defaults to any. The default is any:any.`, + Value: docvalues.StringValue{}, + }, + "UpdateHostKeys": docvalues.DocumentationValue{ + Documentation: `Specifies whether ssh(1) should accept notifications of additional hostkeys from the server sent after authentication has completed and add them to UserKnownHostsFile. The argument must be yes, no or ask. This option allows learning alternate hostkeys for a server and supports graceful key rotation by allowing a server to send replacement public keys before old ones are removed. + Additional hostkeys are only accepted if the key used to authenticate the host was already trusted or explicitly accepted by the user, the host was authenticated via UserKnownHostsFile (i.e. not GlobalKnownHostsFile) and the host was authenticated using a plain key and not a certificate. + UpdateHostKeys is enabled by default if the user has not overridden the default UserKnownHostsFile setting and has not enabled VerifyHostKeyDNS, otherwise UpdateHostKeys will be set to no. + If UpdateHostKeys is set to ask, then the user is asked to confirm the modifications to the known_hosts file. Confirmation is currently incompatible with ControlPersist, and will be disabled if it is enabled. + Presently, only sshd(8) from OpenSSH 6.8 and greater support the + 'hostkeys@openssh.com' protocol extension used to inform the client of all the server's hostkeys.`, + Value: docvalues.StringValue{}, + }, + "User": docvalues.DocumentationValue{ + Documentation: `Specifies the user to log in as. This can be useful when a different user name is used on different machines. This saves the trouble of having to remember to give the user name on the command line.`, + Value: docvalues.StringValue{}, + }, + "UserKnownHostsFile": docvalues.DocumentationValue{ + Documentation: `Specifies one or more files to use for the user host key database, separated by whitespace. Each filename may use tilde notation to refer to the user's home directory, the tokens described in the TOKENS section and environment variables as described in the ENVIRONMENT VARIABLES section. A value of none causes ssh(1) to ignore any user-specific known hosts files. The default is + ~/.ssh/known_hosts, + ~/.ssh/known_hosts2.`, + Value: docvalues.StringValue{}, + }, + "VerifyHostKeyDNS": docvalues.DocumentationValue{ + Documentation: `Specifies whether to verify the remote key using DNS and SSHFP resource records. If this option is set to yes, the client will implicitly trust keys that match a secure fingerprint from DNS. Insecure fingerprints will be handled as if this option was set to ask. If this option is set to ask, information on fingerprint match will be displayed, but the user will still need to confirm new host keys according to the StrictHostKeyChecking option. The default is no. + See also VERIFYING HOST KEYS in ssh(1).`, + Value: docvalues.StringValue{}, + }, + "VisualHostKey": docvalues.DocumentationValue{ + Documentation: `If this flag is set to yes, an ASCII art representation of the remote host key fingerprint is printed in addition to the fingerprint string at login and for unknown host keys. If this flag is set to no (the default), no fingerprint strings are printed at login and only the fingerprint string will be printed for unknown host keys.`, + Value: docvalues.StringValue{}, + }, + "XAuthLocation": docvalues.DocumentationValue{ + Documentation: `Specifies the full pathname of the xauth(1) program. The default is /usr/X11R6/bin/xauth.`, + Value: docvalues.StringValue{}, + }, +} From f530195cac7c654f596bef1497aa5993a70f7b63 Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Tue, 17 Sep 2024 20:17:56 +0200 Subject: [PATCH 045/133] fix(sshd_config): Rename AST nodes to start with SSHD --- handlers/ssh_config/fields/fields.go | 202 +++++++++--------- handlers/sshd_config/analyzer/options.go | 16 +- handlers/sshd_config/ast/listener.go | 18 +- handlers/sshd_config/ast/parser.go | 10 +- handlers/sshd_config/ast/parser_test.go | 38 ++-- handlers/sshd_config/ast/sshd_config.go | 36 ++-- .../sshd_config/ast/sshd_config_fields.go | 28 +-- handlers/sshd_config/handlers/completions.go | 6 +- handlers/sshd_config/handlers/hover.go | 4 +- handlers/sshd_config/indexes/indexes.go | 30 +-- handlers/sshd_config/shared.go | 2 +- 11 files changed, 195 insertions(+), 195 deletions(-) diff --git a/handlers/ssh_config/fields/fields.go b/handlers/ssh_config/fields/fields.go index fb904dd..83237d3 100644 --- a/handlers/ssh_config/fields/fields.go +++ b/handlers/ssh_config/fields/fields.go @@ -3,13 +3,13 @@ package fields import docvalues "config-lsp/doc-values" var Options = map[string]docvalues.DocumentationValue{ - "Host": docvalues.DocumentationValue{ + "Host": { Documentation: `Restricts the following declarations (up to the next Host or Match keyword) to be only for those hosts that match one of the patterns given after the keyword. If more than one pattern is provided, they should be separated by whitespace. A single ‘*’ as a pattern can be used to provide global defaults for all hosts. The host is usually the hostname argument given on the command line (see the CanonicalizeHostname keyword for exceptions). A pattern entry may be negated by prefixing it with an exclamation mark (‘!’). If a negated entry is matched, then the Host entry is ignored, regardless of whether any other patterns on the line match. Negated matches are therefore useful to provide exceptions for wildcard matches. See PATTERNS for more information on patterns.`, Value: docvalues.StringValue{}, }, - "Match": docvalues.DocumentationValue{ + "Match": { Documentation: `Restricts the following declarations (up to the next Host or Match keyword) to be used only when the conditions following the Match keyword are satisfied. Match conditions are specified using one or more criteria or the single token all which always matches. The available criteria keywords are: canonical, final, exec, localnetwork, host, originalhost, tagged, user, and localuser. The all criteria must appear alone or immediately after canonical or final. Other criteria may be combined arbitrarily. All criteria but all, canonical, and final require an argument. Criteria may be negated by prepending an exclamation mark (‘!’). The canonical keyword matches only when the configuration file is being re-parsed after hostname canonicalization (see the CanonicalizeHostname option). This may be useful to specify conditions that work with canonical host names only. The final keyword requests that the configuration be re-parsed (regardless of whether CanonicalizeHostname is enabled), and matches only during this final pass. If CanonicalizeHostname is enabled, then canonical and final match during the same pass. @@ -18,52 +18,52 @@ var Options = map[string]docvalues.DocumentationValue{ The other keywords' criteria must be single entries or comma-separated lists and may use the wildcard and negation operators described in the PATTERNS section. The criteria for the host keyword are matched against the target hostname, after any substitution by the Hostname or CanonicalizeHostname options. The originalhost keyword matches against the hostname as it was specified on the command-line. The tagged keyword matches a tag name specified by a prior Tag directive or on the ssh(1) command-line using the -P flag. The user keyword matches against the target username on the remote host. The localuser keyword matches against the name of the local user running ssh(1) (this keyword may be useful in system-wide ssh_config files).`, Value: docvalues.StringValue{}, }, - "AddKeysToAgent": docvalues.DocumentationValue{ + "AddKeysToAgent": { Documentation: `Specifies whether keys should be automatically added to a running ssh-agent(1). If this option is set to yes and a key is loaded from a file, the key and its passphrase are added to the agent with the default lifetime, as if by ssh-add(1). If this option is set to ask, ssh(1) will require confirmation using the SSH_ASKPASS program before adding a key (see ssh-add(1) for details). If this option is set to confirm, each use of the key must be confirmed, as if the -c option was specified to ssh-add(1). If this option is set to no, no keys are added to the agent. Alternately, this option may be specified as a time interval using the format described in the TIME FORMATS section of sshd_config(5) to specify the key's lifetime in ssh-agent(1), after which it will automatically be removed. The argument must be no (the default), yes, confirm (optionally followed by a time interval), ask or a time interval.`, Value: docvalues.StringValue{}, }, - "AddressFamily": docvalues.DocumentationValue{ + "AddressFamily": { Documentation: `Specifies which address family to use when connecting. Valid arguments are any (the default), inet (use IPv4 only), or inet6 (use IPv6 only).`, Value: docvalues.StringValue{}, }, - "BatchMode": docvalues.DocumentationValue{ + "BatchMode": { Documentation: `If set to yes, user interaction such as password prompts and host key confirmation requests will be disabled. This option is useful in scripts and other batch jobs where no user is present to interact with ssh(1). The argument must be yes or no (the default).`, Value: docvalues.StringValue{}, }, - "BindAddress": docvalues.DocumentationValue{ + "BindAddress": { Documentation: `Use the specified address on the local machine as the source address of the connection. Only useful on systems with more than one address.`, Value: docvalues.StringValue{}, }, - "BindInterface": docvalues.DocumentationValue{ + "BindInterface": { Documentation: `Use the address of the specified interface on the local machine as the source address of the connection.`, Value: docvalues.StringValue{}, }, - "CanonicalDomains": docvalues.DocumentationValue{ + "CanonicalDomains": { Documentation: `When CanonicalizeHostname is enabled, this option specifies the list of domain suffixes in which to search for the specified destination host.`, Value: docvalues.StringValue{}, }, - "CanonicalizeFallbackLocal": docvalues.DocumentationValue{ + "CanonicalizeFallbackLocal": { Documentation: `Specifies whether to fail with an error when hostname canonicalization fails. The default, yes, will attempt to look up the unqualified hostname using the system resolver's search rules. A value of no will cause ssh(1) to fail instantly if CanonicalizeHostname is enabled and the target hostname cannot be found in any of the domains specified by CanonicalDomains.`, Value: docvalues.StringValue{}, }, - "CanonicalizeHostname": docvalues.DocumentationValue{ + "CanonicalizeHostname": { Documentation: `Controls whether explicit hostname canonicalization is performed. The default, no, is not to perform any name rewriting and let the system resolver handle all hostname lookups. If set to yes then, for connections that do not use a ProxyCommand or ProxyJump, ssh(1) will attempt to canonicalize the hostname specified on the command line using the CanonicalDomains suffixes and CanonicalizePermittedCNAMEs rules. If CanonicalizeHostname is set to always, then canonicalization is applied to proxied connections too. If this option is enabled, then the configuration files are processed again using the new target name to pick up any new configuration in matching Host and Match stanzas. A value of none disables the use of a ProxyJump host.`, Value: docvalues.StringValue{}, }, - "CanonicalizeMaxDots": docvalues.DocumentationValue{ + "CanonicalizeMaxDots": { Documentation: `Specifies the maximum number of dot characters in a hostname before canonicalization is disabled. The default, 1, allows a single dot (i.e. hostname.subdomain).`, Value: docvalues.StringValue{}, }, - "CanonicalizePermittedCNAMEs": docvalues.DocumentationValue{ + "CanonicalizePermittedCNAMEs": { Documentation: `Specifies rules to determine whether CNAMEs should be followed when canonicalizing hostnames. The rules consist of one or more arguments of source_domain_list:target_domain_list, where source_domain_list is a pattern-list of domains that may follow CNAMEs in canonicalization, and target_domain_list is a pattern-list of domains that they may resolve to. For example, '*.a.example.com:*.b.example.com,*.c.example.com' will allow hostnames matching '*.a.example.com' to be canonicalized to names in the '*.b.example.com' or '*.c.example.com' domains. A single argument of 'none' causes no CNAMEs to be considered for canonicalization. This is the default behaviour.`, Value: docvalues.StringValue{}, }, - "CASignatureAlgorithms": docvalues.DocumentationValue{ + "CASignatureAlgorithms": { Documentation: `Specifies which algorithms are allowed for signing of certificates by certificate authorities (CAs). The default is: ssh-ed25519,ecdsa-sha2-nistp256, @@ -77,22 +77,22 @@ rsa-sha2-512,rsa-sha2-256 ssh(1) will not accept host certificates signed using algorithms other than those specified.`, Value: docvalues.StringValue{}, }, - "CertificateFile": docvalues.DocumentationValue{ + "CertificateFile": { Documentation: `Specifies a file from which the user's certificate is read. A corresponding private key must be provided separately in order to use this certificate either from an IdentityFile directive or -i flag to ssh(1), via ssh-agent(1), or via a PKCS11Provider or SecurityKeyProvider. Arguments to CertificateFile may use the tilde syntax to refer to a user's home directory, the tokens described in the TOKENS section and environment variables as described in the ENVIRONMENT VARIABLES section. It is possible to have multiple certificate files specified in configuration files; these certificates will be tried in sequence. Multiple CertificateFile directives will add to the list of certificates used for authentication.`, Value: docvalues.StringValue{}, }, - "ChannelTimeout": docvalues.DocumentationValue{ + "ChannelTimeout": { Documentation: `Open X11 forwarding sessions.`, Value: docvalues.StringValue{}, }, - "CheckHostIP": docvalues.DocumentationValue{ + "CheckHostIP": { Documentation: `If set to yes, ssh(1) will additionally check the host IP address in the known_hosts file. This allows it to detect if a host key changed due to DNS spoofing and will add addresses of destination hosts to ~/.ssh/known_hosts in the process, regardless of the setting of StrictHostKeyChecking. If the option is set to no (the default), the check will not be executed.`, Value: docvalues.StringValue{}, }, - "Ciphers": docvalues.DocumentationValue{ + "Ciphers": { Documentation: `Specifies the ciphers allowed and their order of preference. Multiple ciphers must be comma-separated. If the specified list begins with a ‘+’ character, then the specified ciphers will be appended to the default set instead of replacing them. If the specified list begins with a ‘-’ character, then the specified ciphers (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a ‘^’ character, then the specified ciphers will be placed at the head of the default set. The supported ciphers are: @@ -118,124 +118,124 @@ aes128-gcm@openssh.com,aes256-gcm@openssh.com 'ssh -Q cipher'.`, Value: docvalues.StringValue{}, }, - "ClearAllForwardings": docvalues.DocumentationValue{ + "ClearAllForwardings": { Documentation: `Specifies that all local, remote, and dynamic port forwardings specified in the configuration files or on the command line be cleared. This option is primarily useful when used from the ssh(1) command line to clear port forwardings set in configuration files, and is automatically set by scp(1) and sftp(1). The argument must be yes or no (the default).`, Value: docvalues.StringValue{}, }, - "Compression": docvalues.DocumentationValue{ + "Compression": { Documentation: `Specifies whether to use compression. The argument must be yes or no (the default).`, Value: docvalues.StringValue{}, }, - "ConnectionAttempts": docvalues.DocumentationValue{ + "ConnectionAttempts": { Documentation: `Specifies the number of tries (one per second) to make before exiting. The argument must be an integer. This may be useful in scripts if the connection sometimes fails. The default is 1.`, Value: docvalues.StringValue{}, }, - "ConnectTimeout": docvalues.DocumentationValue{ + "ConnectTimeout": { Documentation: `Specifies the timeout (in seconds) used when connecting to the SSH server, instead of using the default system TCP timeout. This timeout is applied both to establishing the connection and to performing the initial SSH protocol handshake and key exchange.`, Value: docvalues.StringValue{}, }, - "ControlMaster": docvalues.DocumentationValue{ + "ControlMaster": { Documentation: `Enables the sharing of multiple sessions over a single network connection. When set to yes, ssh(1) will listen for connections on a control socket specified using the ControlPath argument. Additional sessions can connect to this socket using the same ControlPath with ControlMaster set to no (the default). These sessions will try to reuse the master instance's network connection rather than initiating new ones, but will fall back to connecting normally if the control socket does not exist, or is not listening. Setting this to ask will cause ssh(1) to listen for control connections, but require confirmation using ssh-askpass(1). If the ControlPath cannot be opened, ssh(1) will continue without connecting to a master instance. X11 and ssh-agent(1) forwarding is supported over these multiplexed connections, however the display and agent forwarded will be the one belonging to the master connection i.e. it is not possible to forward multiple displays or agents. Two additional options allow for opportunistic multiplexing: try to use a master connection but fall back to creating a new one if one does not already exist. These options are: auto and autoask. The latter requires confirmation like the ask option.`, Value: docvalues.StringValue{}, }, - "ControlPath": docvalues.DocumentationValue{ + "ControlPath": { Documentation: `Specify the path to the control socket used for connection sharing as described in the ControlMaster section above or the string none to disable connection sharing. Arguments to ControlPath may use the tilde syntax to refer to a user's home directory, the tokens described in the TOKENS section and environment variables as described in the ENVIRONMENT VARIABLES section. It is recommended that any ControlPath used for opportunistic connection sharing include at least %h, %p, and %r (or alternatively %C) and be placed in a directory that is not writable by other users. This ensures that shared connections are uniquely identified.`, Value: docvalues.StringValue{}, }, - "ControlPersist": docvalues.DocumentationValue{ + "ControlPersist": { Documentation: `When used in conjunction with ControlMaster, specifies that the master connection should remain open in the background (waiting for future client connections) after the initial client connection has been closed. If set to no (the default), then the master connection will not be placed into the background, and will close as soon as the initial client connection is closed. If set to yes or 0, then the master connection will remain in the background indefinitely (until killed or closed via a mechanism such as the 'ssh -O exit'). If set to a time in seconds, or a time in any of the formats documented in sshd_config(5), then the backgrounded master connection will automatically terminate after it has remained idle (with no client connections) for the specified time.`, Value: docvalues.StringValue{}, }, - "DynamicForward": docvalues.DocumentationValue{ + "DynamicForward": { Documentation: `Specifies that a TCP port on the local machine be forwarded over the secure channel, and the application protocol is then used to determine where to connect to from the remote machine. The argument must be [bind_address:]port. IPv6 addresses can be specified by enclosing addresses in square brackets. By default, the local port is bound in accordance with the GatewayPorts setting. However, an explicit bind_address may be used to bind the connection to a specific address. The bind_address of localhost indicates that the listening port be bound for local use only, while an empty address or ‘*’ indicates that the port should be available from all interfaces. Currently the SOCKS4 and SOCKS5 protocols are supported, and ssh(1) will act as a SOCKS server. Multiple forwardings may be specified, and additional forwardings can be given on the command line. Only the superuser can forward privileged ports.`, Value: docvalues.StringValue{}, }, - "EnableEscapeCommandline": docvalues.DocumentationValue{ + "EnableEscapeCommandline": { Documentation: `Enables the command line option in the EscapeChar menu for interactive sessions (default ‘~C’). By default, the command line is disabled.`, Value: docvalues.StringValue{}, }, - "EnableSSHKeysign": docvalues.DocumentationValue{ + "EnableSSHKeysign": { Documentation: `Setting this option to yes in the global client configuration file /etc/ssh/ssh_config enables the use of the helper program ssh-keysign(8) during HostbasedAuthentication. The argument must be yes or no (the default). This option should be placed in the non-hostspecific section. See ssh-keysign(8) for more information.`, Value: docvalues.StringValue{}, }, - "EscapeChar": docvalues.DocumentationValue{ + "EscapeChar": { Documentation: `Sets the escape character (default: ‘~’). The escape character can also be set on the command line. The argument should be a single character, ‘^’ followed by a letter, or none to disable the escape character entirely (making the connection transparent for binary data).`, Value: docvalues.StringValue{}, }, - "ExitOnForwardFailure": docvalues.DocumentationValue{ + "ExitOnForwardFailure": { Documentation: `Specifies whether ssh(1) should terminate the connection if it cannot set up all requested dynamic, tunnel, local, and remote port forwardings, (e.g. if either end is unable to bind and listen on a specified port). Note that ExitOnForwardFailure does not apply to connections made over port forwardings and will not, for example, cause ssh(1) to exit if TCP connections to the ultimate forwarding destination fail. The argument must be yes or no (the default).`, Value: docvalues.StringValue{}, }, - "FingerprintHash": docvalues.DocumentationValue{ + "FingerprintHash": { Documentation: `Specifies the hash algorithm used when displaying key fingerprints. Valid options are: md5 and sha256 (the default).`, Value: docvalues.StringValue{}, }, - "ForkAfterAuthentication": docvalues.DocumentationValue{ + "ForkAfterAuthentication": { Documentation: `Requests ssh to go to background just before command execution. This is useful if ssh is going to ask for passwords or passphrases, but the user wants it in the background. This implies the StdinNull configuration option being set to “yes”. The recommended way to start X11 programs at a remote site is with something like ssh -f host xterm, which is the same as ssh host xterm if the ForkAfterAuthentication configuration option is set to “yes”. If the ExitOnForwardFailure configuration option is set to “yes”, then a client started with the ForkAfterAuthentication configuration option being set to “yes” will wait for all remote port forwards to be successfully established before placing itself in the background. The argument to this keyword must be yes (same as the -f option) or no (the default).`, Value: docvalues.StringValue{}, }, - "ForwardAgent": docvalues.DocumentationValue{ + "ForwardAgent": { Documentation: `Specifies whether the connection to the authentication agent (if any) will be forwarded to the remote machine. The argument may be yes, no (the default), an explicit path to an agent socket or the name of an environment variable (beginning with ‘$’) in which to find the path. Agent forwarding should be enabled with caution. Users with the ability to bypass file permissions on the remote host (for the agent's Unix-domain socket) can access the local agent through the forwarded connection. An attacker cannot obtain key material from the agent, however they can perform operations on the keys that enable them to authenticate using the identities loaded into the agent.`, Value: docvalues.StringValue{}, }, - "ForwardX11": docvalues.DocumentationValue{ + "ForwardX11": { Documentation: `Specifies whether X11 connections will be automatically redirected over the secure channel and DISPLAY set. The argument must be yes or no (the default). X11 forwarding should be enabled with caution. Users with the ability to bypass file permissions on the remote host (for the user's X11 authorization database) can access the local X11 display through the forwarded connection. An attacker may then be able to perform activities such as keystroke monitoring if the ForwardX11Trusted option is also enabled.`, Value: docvalues.StringValue{}, }, - "ForwardX11Timeout": docvalues.DocumentationValue{ + "ForwardX11Timeout": { Documentation: `Specify a timeout for untrusted X11 forwarding using the format described in the TIME FORMATS section of sshd_config(5). X11 connections received by ssh(1) after this time will be refused. Setting ForwardX11Timeout to zero will disable the timeout and permit X11 forwarding for the life of the connection. The default is to disable untrusted X11 forwarding after twenty minutes has elapsed.`, Value: docvalues.StringValue{}, }, - "ForwardX11Trusted": docvalues.DocumentationValue{ + "ForwardX11Trusted": { Documentation: `If this option is set to yes, remote X11 clients will have full access to the original X11 display. If this option is set to no (the default), remote X11 clients will be considered untrusted and prevented from stealing or tampering with data belonging to trusted X11 clients. Furthermore, the xauth(1) token used for the session will be set to expire after 20 minutes. Remote clients will be refused access after this time. See the X11 SECURITY extension specification for full details on the restrictions imposed on untrusted clients.`, Value: docvalues.StringValue{}, }, - "GatewayPorts": docvalues.DocumentationValue{ + "GatewayPorts": { Documentation: `Specifies whether remote hosts are allowed to connect to local forwarded ports. By default, ssh(1) binds local port forwardings to the loopback address. This prevents other remote hosts from connecting to forwarded ports. GatewayPorts can be used to specify that ssh should bind local port forwardings to the wildcard address, thus allowing remote hosts to connect to forwarded ports. The argument must be yes or no (the default).`, Value: docvalues.StringValue{}, }, - "GlobalKnownHostsFile": docvalues.DocumentationValue{ + "GlobalKnownHostsFile": { Documentation: `Specifies one or more files to use for the global host key database, separated by whitespace. The default is /etc/ssh/ssh_known_hosts, /etc/ssh/ssh_known_hosts2.`, Value: docvalues.StringValue{}, }, - "GSSAPIAuthentication": docvalues.DocumentationValue{ + "GSSAPIAuthentication": { Documentation: `Specifies whether user authentication based on GSSAPI is allowed. The default is no.`, Value: docvalues.StringValue{}, }, - "GSSAPIDelegateCredentials": docvalues.DocumentationValue{ + "GSSAPIDelegateCredentials": { Documentation: `Forward (delegate) credentials to the server. The default is no.`, Value: docvalues.StringValue{}, }, - "HashKnownHosts": docvalues.DocumentationValue{ + "HashKnownHosts": { Documentation: `Indicates that ssh(1) should hash host names and addresses when they are added to ~/.ssh/known_hosts. These hashed names may be used normally by ssh(1) and sshd(8), but they do not visually reveal identifying information if the file's contents are disclosed. The default is no. Note that existing names and addresses in known hosts files will not be converted automatically, but may be manually hashed using ssh-keygen(1).`, Value: docvalues.StringValue{}, }, - "HostbasedAcceptedAlgorithms": docvalues.DocumentationValue{ + "HostbasedAcceptedAlgorithms": { Documentation: `Specifies the signature algorithms that will be used for hostbased authentication as a comma-separated list of patterns. Alternately if the specified list begins with a ‘+’ character, then the specified signature algorithms will be appended to the default set instead of replacing them. If the specified list begins with a ‘-’ character, then the specified signature algorithms (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a ‘^’ character, then the specified signature algorithms will be placed at the head of the default set. The default for this option is: ssh-ed25519-cert-v01@openssh.com, @@ -255,11 +255,11 @@ rsa-sha2-512,rsa-sha2-256 The -Q option of ssh(1) may be used to list supported signature algorithms. This was formerly named HostbasedKeyTypes.`, Value: docvalues.StringValue{}, }, - "HostbasedAuthentication": docvalues.DocumentationValue{ + "HostbasedAuthentication": { Documentation: `Specifies whether to try rhosts based authentication with public key authentication. The argument must be yes or no (the default).`, Value: docvalues.StringValue{}, }, - "HostKeyAlgorithms": docvalues.DocumentationValue{ + "HostKeyAlgorithms": { Documentation: `Specifies the host key signature algorithms that the client wants to use in order of preference. Alternately if the specified list begins with a ‘+’ character, then the specified signature algorithms will be appended to the default set instead of replacing them. If the specified list begins with a ‘-’ character, then the specified signature algorithms (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a ‘^’ character, then the specified signature algorithms will be placed at the head of the default set. The default for this option is: @@ -282,25 +282,25 @@ rsa-sha2-512,rsa-sha2-256 The list of available signature algorithms may also be obtained using 'ssh -Q HostKeyAlgorithms'.`, Value: docvalues.StringValue{}, }, - "HostKeyAlias": docvalues.DocumentationValue{ + "HostKeyAlias": { Documentation: `Specifies an alias that should be used instead of the real host name when looking up or saving the host key in the host key database files and when validating host certificates. This option is useful for tunneling SSH connections or for multiple servers running on a single host.`, Value: docvalues.StringValue{}, }, - "Hostname": docvalues.DocumentationValue{ + "Hostname": { Documentation: `Specifies the real host name to log into. This can be used to specify nicknames or abbreviations for hosts. Arguments to Hostname accept the tokens described in the TOKENS section. Numeric IP addresses are also permitted (both on the command line and in Hostname specifications). The default is the name given on the command line.`, Value: docvalues.StringValue{}, }, - "IdentitiesOnly": docvalues.DocumentationValue{ + "IdentitiesOnly": { Documentation: `Specifies that ssh(1) should only use the configured authentication identity and certificate files (either the default files, or those explicitly configured in the ssh_config files or passed on the ssh(1) command-line), even if ssh-agent(1) or a PKCS11Provider or SecurityKeyProvider offers more identities. The argument to this keyword must be yes or no (the default). This option is intended for situations where ssh-agent offers many different identities.`, Value: docvalues.StringValue{}, }, - "IdentityAgent": docvalues.DocumentationValue{ + "IdentityAgent": { Documentation: `Specifies the UNIX-domain socket used to communicate with the authentication agent. This option overrides the SSH_AUTH_SOCK environment variable and can be used to select a specific agent. Setting the socket name to none disables the use of an authentication agent. If the string 'SSH_AUTH_SOCK' is specified, the location of the socket will be read from the SSH_AUTH_SOCK environment variable. Otherwise if the specified value begins with a ‘$’ character, then it will be treated as an environment variable containing the location of the socket. Arguments to IdentityAgent may use the tilde syntax to refer to a user's home directory, the tokens described in the TOKENS section and environment variables as described in the ENVIRONMENT VARIABLES section.`, Value: docvalues.StringValue{}, }, - "IdentityFile": docvalues.DocumentationValue{ + "IdentityFile": { Documentation: `Specifies a file from which the user's ECDSA, authenticator-hosted ECDSA, Ed25519, authenticator-hosted Ed25519 or RSA authentication identity is read. You can also specify a public key file to use the corresponding private key that is loaded in ssh-agent(1) when the private key file is not present locally. The default is ~/.ssh/id_rsa, ~/.ssh/id_ecdsa, ~/.ssh/id_ecdsa_sk, @@ -311,29 +311,29 @@ rsa-sha2-512,rsa-sha2-256 IdentityFile may be used in conjunction with IdentitiesOnly to select which identities in an agent are offered during authentication. IdentityFile may also be used in conjunction with CertificateFile in order to provide any certificate also needed for authentication with the identity.`, Value: docvalues.StringValue{}, }, - "IgnoreUnknown": docvalues.DocumentationValue{ + "IgnoreUnknown": { Documentation: `Specifies a pattern-list of unknown options to be ignored if they are encountered in configuration parsing. This may be used to suppress errors if ssh_config contains options that are unrecognised by ssh(1). It is recommended that IgnoreUnknown be listed early in the configuration file as it will not be applied to unknown options that appear before it.`, Value: docvalues.StringValue{}, }, - "Include": docvalues.DocumentationValue{ + "Include": { Documentation: `Include the specified configuration file(s). Multiple pathnames may be specified and each pathname may contain glob(7) wildcards, tokens as described in the TOKENS section, environment variables as described in the ENVIRONMENT VARIABLES section and, for user configurations, shell-like ‘~’ references to user home directories. Wildcards will be expanded and processed in lexical order. Files without absolute paths are assumed to be in ~/.ssh if included in a user configuration file or /etc/ssh if included from the system configuration file. Include directive may appear inside a Match or Host block to perform conditional inclusion.`, Value: docvalues.StringValue{}, }, - "IPQoS": docvalues.DocumentationValue{ + "IPQoS": { Documentation: `Specifies the IPv4 type-of-service or DSCP class for connections. Accepted values are af11, af12, af13, af21, af22, af23, af31, af32, af33, af41, af42, af43, cs0, cs1, cs2, cs3, cs4, cs5, cs6, cs7, ef, le, lowdelay, throughput, reliability, a numeric value, or none to use the operating system default. This option may take one or two arguments, separated by whitespace. If one argument is specified, it is used as the packet class unconditionally. If two values are specified, the first is automatically selected for interactive sessions and the second for non-interactive sessions. The default is af21 (Low-Latency Data) for interactive sessions and cs1 (Lower Effort) for non-interactive sessions.`, Value: docvalues.StringValue{}, }, - "KbdInteractiveAuthentication": docvalues.DocumentationValue{ + "KbdInteractiveAuthentication": { Documentation: `Specifies whether to use keyboard-interactive authentication. The argument to this keyword must be yes (the default) or no. ChallengeResponseAuthentication is a deprecated alias for this.`, Value: docvalues.StringValue{}, }, - "KbdInteractiveDevices": docvalues.DocumentationValue{ + "KbdInteractiveDevices": { Documentation: `Specifies the list of methods to use in keyboard-interactive authentication. Multiple method names must be comma-separated. The default is to use the server specified list. The methods available vary depending on what the server supports. For an OpenSSH server, it may be zero or more of: bsdauth, pam, and skey.`, Value: docvalues.StringValue{}, }, - "KexAlgorithms": docvalues.DocumentationValue{ + "KexAlgorithms": { Documentation: `Specifies the permitted KEX (Key Exchange) algorithms that will be used and their preference order. The selected algorithm will be the first algorithm in this list that the server also supports. Multiple algorithms must be comma-separated. If the specified list begins with a ‘+’ character, then the specified algorithms will be appended to the default set instead of replacing them. If the specified list begins with a ‘-’ character, then the specified algorithms (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a ‘^’ character, then the specified algorithms will be placed at the head of the default set. @@ -351,27 +351,27 @@ diffie-hellman-group14-sha256 The list of supported key exchange algorithms may also be obtained using 'ssh -Q kex'.`, Value: docvalues.StringValue{}, }, - "KnownHostsCommand": docvalues.DocumentationValue{ + "KnownHostsCommand": { Documentation: `Specifies a command to use to obtain a list of host keys, in addition to those listed in UserKnownHostsFile and GlobalKnownHostsFile. This command is executed after the files have been read. It may write host key lines to standard output in identical format to the usual files (described in the VERIFYING HOST KEYS section in ssh(1)). Arguments to KnownHostsCommand accept the tokens described in the TOKENS section. The command may be invoked multiple times per connection: once when preparing the preference list of host key algorithms to use, again to obtain the host key for the requested host name and, if CheckHostIP is enabled, one more time to obtain the host key matching the server's address. If the command exits abnormally or returns a non-zero exit status then the connection is terminated.`, Value: docvalues.StringValue{}, }, - "LocalCommand": docvalues.DocumentationValue{ + "LocalCommand": { Documentation: `Specifies a command to execute on the local machine after successfully connecting to the server. The command string extends to the end of the line, and is executed with the user's shell. Arguments to LocalCommand accept the tokens described in the TOKENS section. The command is run synchronously and does not have access to the session of the ssh(1) that spawned it. It should not be used for interactive commands. This directive is ignored unless PermitLocalCommand has been enabled.`, Value: docvalues.StringValue{}, }, - "LocalForward": docvalues.DocumentationValue{ + "LocalForward": { Documentation: `Specifies that a TCP port on the local machine be forwarded over the secure channel to the specified host and port from the remote machine. The first argument specifies the listener and may be [bind_address:]port or a Unix domain socket path. The second argument is the destination and may be host:hostport or a Unix domain socket path if the remote host supports it. IPv6 addresses can be specified by enclosing addresses in square brackets. Multiple forwardings may be specified, and additional forwardings can be given on the command line. Only the superuser can forward privileged ports. By default, the local port is bound in accordance with the GatewayPorts setting. However, an explicit bind_address may be used to bind the connection to a specific address. The bind_address of localhost indicates that the listening port be bound for local use only, while an empty address or ‘*’ indicates that the port should be available from all interfaces. Unix domain socket paths may use the tokens described in the TOKENS section and environment variables as described in the ENVIRONMENT VARIABLES section.`, Value: docvalues.StringValue{}, }, - "LogLevel": docvalues.DocumentationValue{ + "LogLevel": { Documentation: `Gives the verbosity level that is used when logging messages from ssh(1). The possible values are: QUIET, FATAL, ERROR, INFO, VERBOSE, DEBUG, DEBUG1, DEBUG2, and DEBUG3. The default is INFO. DEBUG and DEBUG1 are equivalent. DEBUG2 and DEBUG3 each specify higher levels of verbose output.`, Value: docvalues.StringValue{}, }, - "LogVerbose": docvalues.DocumentationValue{ + "LogVerbose": { Documentation: `Specify one or more overrides to LogLevel. An override consists of one or more pattern lists that matches the source file, function and line number to force detailed logging for. For example, an override pattern of: kex.c:*:1000,*:kex_exchange_identification():*,packet.c:* @@ -379,7 +379,7 @@ diffie-hellman-group14-sha256 would enable detailed logging for line 1000 of kex.c, everything in the kex_exchange_identification() function, and all code in the packet.c file. This option is intended for debugging and no overrides are enabled by default.`, Value: docvalues.StringValue{}, }, - "MACs": docvalues.DocumentationValue{ + "MACs": { Documentation: `Specifies the MAC (message authentication code) algorithms in order of preference. The MAC algorithm is used for data integrity protection. Multiple algorithms must be comma-separated. If the specified list begins with a ‘+’ character, then the specified algorithms will be appended to the default set instead of replacing them. If the specified list begins with a ‘-’ character, then the specified algorithms (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a ‘^’ character, then the specified algorithms will be placed at the head of the default set. The algorithms that contain '-etm' calculate the MAC after encryption (encrypt-then-mac). These are considered safer and their use recommended. @@ -394,27 +394,27 @@ hmac-sha2-256,hmac-sha2-512,hmac-sha1 The list of available MAC algorithms may also be obtained using 'ssh -Q mac'.`, Value: docvalues.StringValue{}, }, - "NoHostAuthenticationForLocalhost": docvalues.DocumentationValue{ + "NoHostAuthenticationForLocalhost": { Documentation: `Disable host authentication for localhost (loopback addresses). The argument to this keyword must be yes or no (the default).`, Value: docvalues.StringValue{}, }, - "NumberOfPasswordPrompts": docvalues.DocumentationValue{ + "NumberOfPasswordPrompts": { Documentation: `Specifies the number of password prompts before giving up. The argument to this keyword must be an integer. The default is 3.`, Value: docvalues.StringValue{}, }, - "ObscureKeystrokeTiming": docvalues.DocumentationValue{ + "ObscureKeystrokeTiming": { Documentation: `Specifies whether ssh(1) should try to obscure inter-keystroke timings from passive observers of network traffic. If enabled, then for interactive sessions, ssh(1) will send keystrokes at fixed intervals of a few tens of milliseconds and will send fake keystroke packets for some time after typing ceases. The argument to this keyword must be yes, no or an interval specifier of the form interval:milliseconds (e.g. interval:80 for 80 milliseconds). The default is to obscure keystrokes using a 20ms packet interval. Note that smaller intervals will result in higher fake keystroke packet rates.`, Value: docvalues.StringValue{}, }, - "PasswordAuthentication": docvalues.DocumentationValue{ + "PasswordAuthentication": { Documentation: `Specifies whether to use password authentication. The argument to this keyword must be yes (the default) or no.`, Value: docvalues.StringValue{}, }, - "PermitLocalCommand": docvalues.DocumentationValue{ + "PermitLocalCommand": { Documentation: `Allow local command execution via the LocalCommand option or using the !command escape sequence in ssh(1). The argument must be yes or no (the default).`, Value: docvalues.StringValue{}, }, - "PermitRemoteOpen": docvalues.DocumentationValue{ + "PermitRemoteOpen": { Documentation: `Specifies the destinations to which remote TCP port forwarding is permitted when RemoteForward is used as a SOCKS proxy. The forwarding specification must be one of the following forms: PermitRemoteOpen host:port PermitRemoteOpen IPv4_addr:port PermitRemoteOpen @@ -423,22 +423,22 @@ hmac-sha2-256,hmac-sha2-512,hmac-sha1 Multiple forwards may be specified by separating them with whitespace. An argument of any can be used to remove all restrictions and permit any forwarding requests. An argument of none can be used to prohibit all forwarding requests. The wildcard ‘*’ can be used for host or port to allow all hosts or ports respectively. Otherwise, no pattern matching or address lookups are performed on supplied names.`, Value: docvalues.StringValue{}, }, - "PKCS11Provider": docvalues.DocumentationValue{ + "PKCS11Provider": { Documentation: `Specifies which PKCS#11 provider to use or none to indicate that no provider should be used (the default). The argument to this keyword is a path to the PKCS#11 shared library ssh(1) should use to communicate with a PKCS#11 token providing keys for user authentication.`, Value: docvalues.StringValue{}, }, - "Port": docvalues.DocumentationValue{ + "Port": { Documentation: `Specifies the port number to connect on the remote host. The default is 22.`, Value: docvalues.StringValue{}, }, - "PreferredAuthentications": docvalues.DocumentationValue{ + "PreferredAuthentications": { Documentation: `Specifies the order in which the client should try authentication methods. This allows a client to prefer one method (e.g. keyboard-interactive) over another method (e.g. password). The default is: gssapi-with-mic,hostbased,publickey, keyboard-interactive,password`, Value: docvalues.StringValue{}, }, - "ProxyCommand": docvalues.DocumentationValue{ + "ProxyCommand": { Documentation: `Specifies the command to use to connect to the server. The command string extends to the end of the line, and is executed using the user's shell ‘exec’ directive to avoid a lingering shell process. Arguments to ProxyCommand accept the tokens described in the TOKENS section. The command can be basically anything, and should read from its standard input and write to its standard output. It should eventually connect an sshd(8) server running on some machine, or execute sshd @@ -448,7 +448,7 @@ keyboard-interactive,password`, ProxyCommand /usr/bin/nc -X connect -x 192.0.2.0:8080 %h %p`, Value: docvalues.StringValue{}, }, - "ProxyJump": docvalues.DocumentationValue{ + "ProxyJump": { Documentation: `Specifies one or more jump proxies as either [user@]host[:port] or an ssh URI. Multiple proxies may be separated by comma characters and will be visited sequentially. Setting this option will cause ssh(1) to connect to the target host by first making a ssh(1) connection to the specified ProxyJump host and then establishing a TCP forwarding to the ultimate target from there. Setting the host to none disables this option entirely. Note that this option will compete with the ProxyCommand option - whichever is specified first will prevent later instances of the other from taking effect. @@ -456,11 +456,11 @@ keyboard-interactive,password`, (either supplied via the command-line or the configuration file) is not generally applied to jump hosts. ~/.ssh/config should be used if specific configuration is required for jump hosts.`, Value: docvalues.StringValue{}, }, - "ProxyUseFdpass": docvalues.DocumentationValue{ + "ProxyUseFdpass": { Documentation: `Specifies that ProxyCommand will pass a connected file descriptor back to ssh(1) instead of continuing to execute and pass data. The default is no.`, Value: docvalues.StringValue{}, }, - "PubkeyAcceptedAlgorithms": docvalues.DocumentationValue{ + "PubkeyAcceptedAlgorithms": { Documentation: `Specifies the signature algorithms that will be used for public key authentication as a comma-separated list of patterns. If the specified list begins with a ‘+’ character, then the algorithms after it will be appended to the default instead of replacing it. If the specified list begins with a ‘-’ character, then the specified algorithms (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a ‘^’ character, then the specified algorithms will be placed at the head of the default set. The default for this option is: @@ -481,21 +481,21 @@ rsa-sha2-512,rsa-sha2-256 The list of available signature algorithms may also be obtained using 'ssh -Q PubkeyAcceptedAlgorithms'.`, Value: docvalues.StringValue{}, }, - "PubkeyAuthentication": docvalues.DocumentationValue{ + "PubkeyAuthentication": { Documentation: `Specifies whether to try public key authentication. The argument to this keyword must be yes (the default), no, unbound or host-bound. The final two options enable public key authentication while respectively disabling or enabling the OpenSSH host-bound authentication protocol extension required for restricted ssh-agent(1) forwarding.`, Value: docvalues.StringValue{}, }, - "RekeyLimit": docvalues.DocumentationValue{ + "RekeyLimit": { Documentation: `Specifies the maximum amount of data that may be transmitted or received before the session key is renegotiated, optionally followed by a maximum amount of time that may pass before the session key is renegotiated. The first argument is specified in bytes and may have a suffix of ‘K’, ‘M’, or ‘G’ to indicate Kilobytes, Megabytes, or Gigabytes, respectively. The default is between ‘1G’ and ‘4G’, depending on the cipher. The optional second value is specified in seconds and may use any of the units documented in the TIME FORMATS section of sshd_config(5). The default value for RekeyLimit is default none, which means that rekeying is performed after the cipher's default amount of data has been sent or received and no time based rekeying is done.`, Value: docvalues.StringValue{}, }, - "RemoteCommand": docvalues.DocumentationValue{ + "RemoteCommand": { Documentation: `Specifies a command to execute on the remote machine after successfully connecting to the server. The command string extends to the end of the line, and is executed with the user's shell. Arguments to RemoteCommand accept the tokens described in the TOKENS section.`, Value: docvalues.StringValue{}, }, - "RemoteForward": docvalues.DocumentationValue{ + "RemoteForward": { Documentation: `Specifies that a TCP port on the remote machine be forwarded over the secure channel. The remote port may either be forwarded to a specified host and port from the local machine, or may act as a SOCKS 4/5 proxy that allows a remote client to connect to arbitrary destinations from the local machine. The first argument is the listening specification and may be [bind_address:]port or, if the remote host supports it, a Unix domain socket path. If forwarding to a specific destination then the second argument must be host:hostport or a Unix domain socket path, otherwise if no destination argument is specified then the remote forwarding will be established as a SOCKS proxy. When acting as a SOCKS proxy, the destination of the connection can be restricted by PermitRemoteOpen. IPv6 addresses can be specified by enclosing addresses in square brackets. Multiple forwardings may be specified, and additional forwardings can be given on the command line. Privileged ports can be forwarded only when logging in as root on the remote machine. Unix domain socket paths may use the tokens described in the TOKENS section and environment variables as described in the ENVIRONMENT VARIABLES section. @@ -504,98 +504,98 @@ rsa-sha2-512,rsa-sha2-256 ‘*’ or an empty string, then the forwarding is requested to listen on all interfaces. Specifying a remote bind_address will only succeed if the server's GatewayPorts option is enabled (see sshd_config(5)).`, Value: docvalues.StringValue{}, }, - "RequestTTY": docvalues.DocumentationValue{ + "RequestTTY": { Documentation: `Specifies whether to request a pseudo-tty for the session. The argument may be one of: no (never request a TTY), yes (always request a TTY when standard input is a TTY), force (always request a TTY) or auto (request a TTY when opening a login session). This option mirrors the -t and -T flags for ssh(1).`, Value: docvalues.StringValue{}, }, - "RequiredRSASize": docvalues.DocumentationValue{ + "RequiredRSASize": { Documentation: `Specifies the minimum RSA key size (in bits) that ssh(1) will accept. User authentication keys smaller than this limit will be ignored. Servers that present host keys smaller than this limit will cause the connection to be terminated. The default is 1024 bits. Note that this limit may only be raised from the default.`, Value: docvalues.StringValue{}, }, - "RevokedHostKeys": docvalues.DocumentationValue{ + "RevokedHostKeys": { Documentation: `Specifies revoked host public keys. Keys listed in this file will be refused for host authentication. Note that if this file does not exist or is not readable, then host authentication will be refused for all hosts. Keys may be specified as a text file, listing one public key per line, or as an OpenSSH Key Revocation List (KRL) as generated by ssh-keygen(1). For more information on KRLs, see the KEY REVOCATION LISTS section in ssh-keygen(1). Arguments to RevokedHostKeys may use the tilde syntax to refer to a user's home directory, the tokens described in the TOKENS section and environment variables as described in the ENVIRONMENT VARIABLES section.`, Value: docvalues.StringValue{}, }, - "SecurityKeyProvider": docvalues.DocumentationValue{ + "SecurityKeyProvider": { Documentation: `Specifies a path to a library that will be used when loading any FIDO authenticator-hosted keys, overriding the default of using the built-in USB HID support. If the specified value begins with a ‘$’ character, then it will be treated as an environment variable containing the path to the library.`, Value: docvalues.StringValue{}, }, - "SendEnv": docvalues.DocumentationValue{ + "SendEnv": { Documentation: `Specifies what variables from the local environ(7) should be sent to the server. The server must also support it, and the server must be configured to accept these environment variables. Note that the TERM environment variable is always sent whenever a pseudo-terminal is requested as it is required by the protocol. Refer to AcceptEnv in sshd_config(5) for how to configure the server. Variables are specified by name, which may contain wildcard characters. Multiple environment variables may be separated by whitespace or spread across multiple SendEnv directives. See PATTERNS for more information on patterns. It is possible to clear previously set SendEnv variable names by prefixing patterns with -. The default is not to send any environment variables.`, Value: docvalues.StringValue{}, }, - "ServerAliveCountMax": docvalues.DocumentationValue{ + "ServerAliveCountMax": { Documentation: `Sets the number of server alive messages (see below) which may be sent without ssh(1) receiving any messages back from the server. If this threshold is reached while server alive messages are being sent, ssh will disconnect from the server, terminating the session. It is important to note that the use of server alive messages is very different from TCPKeepAlive (below). The server alive messages are sent through the encrypted channel and therefore will not be spoofable. The TCP keepalive option enabled by TCPKeepAlive is spoofable. The server alive mechanism is valuable when the client or server depend on knowing when a connection has become unresponsive. The default value is 3. If, for example, ServerAliveInterval (see below) is set to 15 and ServerAliveCountMax is left at the default, if the server becomes unresponsive, ssh will disconnect after approximately 45 seconds.`, Value: docvalues.StringValue{}, }, - "ServerAliveInterval": docvalues.DocumentationValue{ + "ServerAliveInterval": { Documentation: `Sets a timeout interval in seconds after which if no data has been received from the server, ssh(1) will send a message through the encrypted channel to request a response from the server. The default is 0, indicating that these messages will not be sent to the server.`, Value: docvalues.StringValue{}, }, - "SessionType": docvalues.DocumentationValue{ + "SessionType": { Documentation: `May be used to either request invocation of a subsystem on the remote system, or to prevent the execution of a remote command at all. The latter is useful for just forwarding ports. The argument to this keyword must be none (same as the -N option), subsystem (same as the -s option) or default (shell or command execution).`, Value: docvalues.StringValue{}, }, - "SetEnv": docvalues.DocumentationValue{ + "SetEnv": { Documentation: `Directly specify one or more environment variables and their contents to be sent to the server. Similarly to SendEnv, with the exception of the TERM variable, the server must be prepared to accept the environment variable.`, Value: docvalues.StringValue{}, }, - "StdinNull": docvalues.DocumentationValue{ + "StdinNull": { Documentation: `Redirects stdin from /dev/null (actually, prevents reading from stdin). Either this or the equivalent -n option must be used when ssh is run in the background. The argument to this keyword must be yes (same as the -n option) or no (the default).`, Value: docvalues.StringValue{}, }, - "StreamLocalBindMask": docvalues.DocumentationValue{ + "StreamLocalBindMask": { Documentation: `Sets the octal file creation mode mask (umask) used when creating a Unix-domain socket file for local or remote port forwarding. This option is only used for port forwarding to a Unix-domain socket file. The default value is 0177, which creates a Unix-domain socket file that is readable and writable only by the owner. Note that not all operating systems honor the file mode on Unix-domain socket files.`, Value: docvalues.StringValue{}, }, - "StreamLocalBindUnlink": docvalues.DocumentationValue{ + "StreamLocalBindUnlink": { Documentation: `Specifies whether to remove an existing Unix-domain socket file for local or remote port forwarding before creating a new one. If the socket file already exists and StreamLocalBindUnlink is not enabled, ssh will be unable to forward the port to the Unix-domain socket file. This option is only used for port forwarding to a Unix-domain socket file. The argument must be yes or no (the default).`, Value: docvalues.StringValue{}, }, - "StrictHostKeyChecking": docvalues.DocumentationValue{ + "StrictHostKeyChecking": { Documentation: `If this flag is set to yes, ssh(1) will never automatically add host keys to the ~/.ssh/known_hosts file, and refuses to connect to hosts whose host key has changed. This provides maximum protection against man-in-the-middle (MITM) attacks, though it can be annoying when the /etc/ssh/ssh_known_hosts file is poorly maintained or when connections to new hosts are frequently made. This option forces the user to manually add all new hosts. If this flag is set to accept-new then ssh will automatically add new host keys to the user's known_hosts file, but will not permit connections to hosts with changed host keys. If this flag is set to no or off, ssh will automatically add new host keys to the user known hosts files and allow connections to hosts with changed hostkeys to proceed, subject to some restrictions. If this flag is set to ask (the default), new host keys will be added to the user known host files only after the user has confirmed that is what they really want to do, and ssh will refuse to connect to hosts whose host key has changed. The host keys of known hosts will be verified automatically in all cases.`, Value: docvalues.StringValue{}, }, - "SyslogFacility": docvalues.DocumentationValue{ + "SyslogFacility": { Documentation: `Gives the facility code that is used when logging messages from ssh(1). The possible values are: DAEMON, USER, AUTH, LOCAL0, LOCAL1, LOCAL2, LOCAL3, LOCAL4, LOCAL5, LOCAL6, LOCAL7. The default is USER.`, Value: docvalues.StringValue{}, }, - "TCPKeepAlive": docvalues.DocumentationValue{ + "TCPKeepAlive": { Documentation: `Specifies whether the system should send TCP keepalive messages to the other side. If they are sent, death of the connection or crash of one of the machines will be properly noticed. However, this means that connections will die if the route is down temporarily, and some people find it annoying. The default is yes (to send TCP keepalive messages), and the client will notice if the network goes down or the remote host dies. This is important in scripts, and many users want it too. To disable TCP keepalive messages, the value should be set to no. See also ServerAliveInterval for protocol-level keepalives.`, Value: docvalues.StringValue{}, }, - "Tag": docvalues.DocumentationValue{ + "Tag": { Documentation: `Specify a configuration tag name that may be later used by a Match directive to select a block of configuration.`, Value: docvalues.StringValue{}, }, - "Tunnel": docvalues.DocumentationValue{ + "Tunnel": { Documentation: `Request tun(4) device forwarding between the client and the server. The argument must be yes, point-to-point (layer 3), ethernet (layer 2), or no (the default). Specifying yes requests the default tunnel mode, which is point-to-point.`, Value: docvalues.StringValue{}, }, - "TunnelDevice": docvalues.DocumentationValue{ + "TunnelDevice": { Documentation: `Specifies the tun(4) devices to open on the client (local_tun) and the server (remote_tun). The argument must be local_tun[:remote_tun]. The devices may be specified by numerical ID or the keyword any, which uses the next available tunnel device. If remote_tun is not specified, it defaults to any. The default is any:any.`, Value: docvalues.StringValue{}, }, - "UpdateHostKeys": docvalues.DocumentationValue{ + "UpdateHostKeys": { Documentation: `Specifies whether ssh(1) should accept notifications of additional hostkeys from the server sent after authentication has completed and add them to UserKnownHostsFile. The argument must be yes, no or ask. This option allows learning alternate hostkeys for a server and supports graceful key rotation by allowing a server to send replacement public keys before old ones are removed. Additional hostkeys are only accepted if the key used to authenticate the host was already trusted or explicitly accepted by the user, the host was authenticated via UserKnownHostsFile (i.e. not GlobalKnownHostsFile) and the host was authenticated using a plain key and not a certificate. UpdateHostKeys is enabled by default if the user has not overridden the default UserKnownHostsFile setting and has not enabled VerifyHostKeyDNS, otherwise UpdateHostKeys will be set to no. @@ -604,26 +604,26 @@ rsa-sha2-512,rsa-sha2-256 'hostkeys@openssh.com' protocol extension used to inform the client of all the server's hostkeys.`, Value: docvalues.StringValue{}, }, - "User": docvalues.DocumentationValue{ + "User": { Documentation: `Specifies the user to log in as. This can be useful when a different user name is used on different machines. This saves the trouble of having to remember to give the user name on the command line.`, Value: docvalues.StringValue{}, }, - "UserKnownHostsFile": docvalues.DocumentationValue{ + "UserKnownHostsFile": { Documentation: `Specifies one or more files to use for the user host key database, separated by whitespace. Each filename may use tilde notation to refer to the user's home directory, the tokens described in the TOKENS section and environment variables as described in the ENVIRONMENT VARIABLES section. A value of none causes ssh(1) to ignore any user-specific known hosts files. The default is ~/.ssh/known_hosts, ~/.ssh/known_hosts2.`, Value: docvalues.StringValue{}, }, - "VerifyHostKeyDNS": docvalues.DocumentationValue{ + "VerifyHostKeyDNS": { Documentation: `Specifies whether to verify the remote key using DNS and SSHFP resource records. If this option is set to yes, the client will implicitly trust keys that match a secure fingerprint from DNS. Insecure fingerprints will be handled as if this option was set to ask. If this option is set to ask, information on fingerprint match will be displayed, but the user will still need to confirm new host keys according to the StrictHostKeyChecking option. The default is no. See also VERIFYING HOST KEYS in ssh(1).`, Value: docvalues.StringValue{}, }, - "VisualHostKey": docvalues.DocumentationValue{ + "VisualHostKey": { Documentation: `If this flag is set to yes, an ASCII art representation of the remote host key fingerprint is printed in addition to the fingerprint string at login and for unknown host keys. If this flag is set to no (the default), no fingerprint strings are printed at login and only the fingerprint string will be printed for unknown host keys.`, Value: docvalues.StringValue{}, }, - "XAuthLocation": docvalues.DocumentationValue{ + "XAuthLocation": { Documentation: `Specifies the full pathname of the xauth(1) program. The default is /usr/X11R6/bin/xauth.`, Value: docvalues.StringValue{}, }, diff --git a/handlers/sshd_config/analyzer/options.go b/handlers/sshd_config/analyzer/options.go index 67aaf87..40381b7 100644 --- a/handlers/sshd_config/analyzer/options.go +++ b/handlers/sshd_config/analyzer/options.go @@ -18,13 +18,13 @@ func analyzeOptionsAreValid( it := d.Config.Options.Iterator() for it.Next() { - entry := it.Value().(ast.SSHEntry) + entry := it.Value().(ast.SSHDEntry) switch entry.(type) { - case *ast.SSHOption: - errs = append(errs, checkOption(entry.(*ast.SSHOption), false)...) - case *ast.SSHMatchBlock: - matchBlock := entry.(*ast.SSHMatchBlock) + case *ast.SSHDOption: + errs = append(errs, checkOption(entry.(*ast.SSHDOption), false)...) + case *ast.SSHDMatchBlock: + matchBlock := entry.(*ast.SSHDMatchBlock) errs = append(errs, checkMatchBlock(matchBlock)...) } @@ -34,7 +34,7 @@ func analyzeOptionsAreValid( } func checkOption( - option *ast.SSHOption, + option *ast.SSHDOption, isInMatchBlock bool, ) []common.LSPError { errs := make([]common.LSPError, 0) @@ -87,7 +87,7 @@ func checkOption( } func checkMatchBlock( - matchBlock *ast.SSHMatchBlock, + matchBlock *ast.SSHDMatchBlock, ) []common.LSPError { errs := make([]common.LSPError, 0) @@ -112,7 +112,7 @@ func checkMatchBlock( it := matchBlock.Options.Iterator() for it.Next() { - option := it.Value().(*ast.SSHOption) + option := it.Value().(*ast.SSHDOption) errs = append(errs, checkOption(option, true)...) } diff --git a/handlers/sshd_config/ast/listener.go b/handlers/sshd_config/ast/listener.go index 4830005..c32e2d9 100644 --- a/handlers/sshd_config/ast/listener.go +++ b/handlers/sshd_config/ast/listener.go @@ -12,8 +12,8 @@ import ( type sshListenerContext struct { line uint32 - currentOption *SSHOption - currentMatchBlock *SSHMatchBlock + currentOption *SSHDOption + currentMatchBlock *SSHDMatchBlock isKeyAMatchBlock bool } @@ -25,7 +25,7 @@ func createSSHListenerContext() *sshListenerContext { } func createListener( - config *SSHConfig, + config *SSHDConfig, context *sshListenerContext, ) sshParserListener { return sshParserListener{ @@ -37,7 +37,7 @@ func createListener( type sshParserListener struct { *parser.BaseConfigListener - Config *SSHConfig + Config *SSHDConfig Errors []common.LSPError sshContext *sshListenerContext } @@ -46,7 +46,7 @@ func (s *sshParserListener) EnterEntry(ctx *parser.EntryContext) { location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext) location.ChangeBothLines(s.sshContext.line) - option := &SSHOption{ + option := &SSHDOption{ LocationRange: location, Value: ctx.GetText(), } @@ -64,7 +64,7 @@ func (s *sshParserListener) EnterKey(ctx *parser.KeyContext) { s.sshContext.isKeyAMatchBlock = true } - s.sshContext.currentOption.Key = &SSHKey{ + s.sshContext.currentOption.Key = &SSHDKey{ LocationRange: location, Value: ctx.GetText(), } @@ -74,7 +74,7 @@ func (s *sshParserListener) EnterSeparator(ctx *parser.SeparatorContext) { location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext) location.ChangeBothLines(s.sshContext.line) - s.sshContext.currentOption.Separator = &SSHSeparator{ + s.sshContext.currentOption.Separator = &SSHDSeparator{ LocationRange: location, } } @@ -83,7 +83,7 @@ func (s *sshParserListener) EnterValue(ctx *parser.ValueContext) { location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext) location.ChangeBothLines(s.sshContext.line) - s.sshContext.currentOption.OptionValue = &SSHValue{ + s.sshContext.currentOption.OptionValue = &SSHDValue{ LocationRange: location, Value: ctx.GetText(), } @@ -121,7 +121,7 @@ func (s *sshParserListener) ExitEntry(ctx *parser.EntryContext) { } } - matchBlock := &SSHMatchBlock{ + matchBlock := &SSHDMatchBlock{ LocationRange: location, MatchEntry: s.sshContext.currentOption, MatchValue: match, diff --git a/handlers/sshd_config/ast/parser.go b/handlers/sshd_config/ast/parser.go index 466f61e..75c9523 100644 --- a/handlers/sshd_config/ast/parser.go +++ b/handlers/sshd_config/ast/parser.go @@ -12,14 +12,14 @@ import ( gods "github.com/emirpasic/gods/utils" ) -func NewSSHConfig() *SSHConfig { - config := &SSHConfig{} +func NewSSHConfig() *SSHDConfig { + config := &SSHDConfig{} config.Clear() return config } -func (c *SSHConfig) Clear() { +func (c *SSHDConfig) Clear() { c.Options = treemap.NewWith(gods.UInt32Comparator) c.CommentLines = map[uint32]struct{}{} } @@ -27,7 +27,7 @@ func (c *SSHConfig) Clear() { var commentPattern = regexp.MustCompile(`^\s*#.*$`) var emptyPattern = regexp.MustCompile(`^\s*$`) -func (c *SSHConfig) Parse(input string) []common.LSPError { +func (c *SSHDConfig) Parse(input string) []common.LSPError { errors := make([]common.LSPError, 0) lines := utils.SplitIntoLines(input) context := createSSHListenerContext() @@ -53,7 +53,7 @@ func (c *SSHConfig) Parse(input string) []common.LSPError { return errors } -func (c *SSHConfig) parseStatement( +func (c *SSHDConfig) parseStatement( context *sshListenerContext, input string, ) []common.LSPError { diff --git a/handlers/sshd_config/ast/parser_test.go b/handlers/sshd_config/ast/parser_test.go index 63d5bb0..2b43b8d 100644 --- a/handlers/sshd_config/ast/parser_test.go +++ b/handlers/sshd_config/ast/parser_test.go @@ -25,7 +25,7 @@ PasswordAuthentication yes } rawFirstEntry, _ := p.Options.Get(uint32(0)) - firstEntry := rawFirstEntry.(*SSHOption) + firstEntry := rawFirstEntry.(*SSHDOption) if !(firstEntry.Value == "PermitRootLogin no" && firstEntry.LocationRange.Start.Line == 0 && @@ -42,7 +42,7 @@ PasswordAuthentication yes } rawSecondEntry, _ := p.Options.Get(uint32(1)) - secondEntry := rawSecondEntry.(*SSHOption) + secondEntry := rawSecondEntry.(*SSHDOption) if !(secondEntry.Value == "PasswordAuthentication yes" && secondEntry.LocationRange.Start.Line == 1 && @@ -81,13 +81,13 @@ Match Address 192.168.0.1 } rawFirstEntry, _ := p.Options.Get(uint32(0)) - firstEntry := rawFirstEntry.(*SSHOption) + firstEntry := rawFirstEntry.(*SSHDOption) if !(firstEntry.Value == "PermitRootLogin no") { t.Errorf("Expected first entry to be 'PermitRootLogin no', but got: %v", firstEntry.Value) } rawSecondEntry, _ := p.Options.Get(uint32(2)) - secondEntry := rawSecondEntry.(*SSHMatchBlock) + secondEntry := rawSecondEntry.(*SSHDMatchBlock) if !(secondEntry.MatchEntry.Value == "Match Address 192.168.0.1") { t.Errorf("Expected second entry to be 'Match Address 192.168.0.1', but got: %v", secondEntry.MatchEntry.Value) } @@ -105,7 +105,7 @@ Match Address 192.168.0.1 } rawThirdEntry, _ := secondEntry.Options.Get(uint32(3)) - thirdEntry := rawThirdEntry.(*SSHOption) + thirdEntry := rawThirdEntry.(*SSHDOption) if !(thirdEntry.Key.Value == "PasswordAuthentication" && thirdEntry.OptionValue.Value == "yes") { t.Errorf("Expected third entry to be 'PasswordAuthentication yes', but got: %v", thirdEntry.Value) } @@ -196,31 +196,31 @@ Match Address 192.168.0.2 } rawSecondEntry, _ := p.Options.Get(uint32(2)) - secondEntry := rawSecondEntry.(*SSHMatchBlock) + secondEntry := rawSecondEntry.(*SSHDMatchBlock) if !(secondEntry.Options.Size() == 2) { t.Errorf("Expected 2 options in second match block, but got: %v", secondEntry.Options) } rawThirdEntry, _ := secondEntry.Options.Get(uint32(3)) - thirdEntry := rawThirdEntry.(*SSHOption) + thirdEntry := rawThirdEntry.(*SSHDOption) if !(thirdEntry.Key.Value == "PasswordAuthentication" && thirdEntry.OptionValue.Value == "yes" && thirdEntry.LocationRange.Start.Line == 3) { t.Errorf("Expected third entry to be 'PasswordAuthentication yes', but got: %v", thirdEntry.Value) } rawFourthEntry, _ := secondEntry.Options.Get(uint32(4)) - fourthEntry := rawFourthEntry.(*SSHOption) + fourthEntry := rawFourthEntry.(*SSHDOption) if !(fourthEntry.Key.Value == "AllowUsers" && fourthEntry.OptionValue.Value == "root user" && fourthEntry.LocationRange.Start.Line == 4) { t.Errorf("Expected fourth entry to be 'AllowUsers root user', but got: %v", fourthEntry.Value) } rawFifthEntry, _ := p.Options.Get(uint32(6)) - fifthEntry := rawFifthEntry.(*SSHMatchBlock) + fifthEntry := rawFifthEntry.(*SSHDMatchBlock) if !(fifthEntry.Options.Size() == 1) { t.Errorf("Expected 1 option in fifth match block, but got: %v", fifthEntry.Options) } rawSixthEntry, _ := fifthEntry.Options.Get(uint32(7)) - sixthEntry := rawSixthEntry.(*SSHOption) + sixthEntry := rawSixthEntry.(*SSHDOption) if !(sixthEntry.Key.Value == "MaxAuthTries" && sixthEntry.OptionValue.Value == "3" && sixthEntry.LocationRange.Start.Line == 7) { t.Errorf("Expected sixth entry to be 'MaxAuthTries 3', but got: %v", sixthEntry.Value) } @@ -276,7 +276,7 @@ Sample } rawFirstEntry, _ := p.Options.Get(uint32(1)) - firstEntry := rawFirstEntry.(*SSHOption) + firstEntry := rawFirstEntry.(*SSHDOption) firstEntryOpt, _ := p.FindOption(uint32(1)) if !(firstEntry.Value == "PermitRootLogin no" && firstEntry.LocationRange.Start.Line == 1 && firstEntryOpt == firstEntry) { t.Errorf("Expected first entry to be 'PermitRootLogin no', but got: %v", firstEntry.Value) @@ -295,7 +295,7 @@ Sample } rawSecondEntry, _ := p.Options.Get(uint32(5)) - secondEntry := rawSecondEntry.(*SSHOption) + secondEntry := rawSecondEntry.(*SSHDOption) if !(secondEntry.Value == "Sample") { t.Errorf("Expected second entry to be 'Sample', but got: %v", secondEntry.Value) @@ -467,25 +467,25 @@ Match Address 172.22.100.0/24,172.22.5.0/24,127.0.0.1 } rawFirstEntry, _ := p.Options.Get(uint32(38)) - firstEntry := rawFirstEntry.(*SSHOption) + firstEntry := rawFirstEntry.(*SSHDOption) if !(firstEntry.Key.Value == "PermitRootLogin" && firstEntry.OptionValue.Value == "no") { t.Errorf("Expected first entry to be 'PermitRootLogin no', but got: %v", firstEntry.Value) } rawSecondEntry, _ := p.Options.Get(uint32(60)) - secondEntry := rawSecondEntry.(*SSHOption) + secondEntry := rawSecondEntry.(*SSHDOption) if !(secondEntry.Key.Value == "PasswordAuthentication" && secondEntry.OptionValue.Value == "no") { t.Errorf("Expected second entry to be 'PasswordAuthentication no', but got: %v", secondEntry.Value) } rawThirdEntry, _ := p.Options.Get(uint32(118)) - thirdEntry := rawThirdEntry.(*SSHOption) + thirdEntry := rawThirdEntry.(*SSHDOption) if !(thirdEntry.Key.Value == "Subsystem" && thirdEntry.OptionValue.Value == "sftp\tinternal-sftp") { t.Errorf("Expected third entry to be 'Subsystem sftp internal-sftp', but got: %v", thirdEntry.Value) } rawFourthEntry, _ := p.Options.Get(uint32(135)) - fourthEntry := rawFourthEntry.(*SSHMatchBlock) + fourthEntry := rawFourthEntry.(*SSHDMatchBlock) if !(fourthEntry.MatchEntry.Value == "Match User anoncvs") { t.Errorf("Expected fourth entry to be 'Match User anoncvs', but got: %v", fourthEntry.MatchEntry.Value) } @@ -499,13 +499,13 @@ Match Address 172.22.100.0/24,172.22.5.0/24,127.0.0.1 } rawFifthEntry, _ := fourthEntry.Options.Get(uint32(136)) - fifthEntry := rawFifthEntry.(*SSHOption) + fifthEntry := rawFifthEntry.(*SSHDOption) if !(fifthEntry.Key.Value == "X11Forwarding" && fifthEntry.OptionValue.Value == "no") { t.Errorf("Expected fifth entry to be 'X11Forwarding no', but got: %v", fifthEntry.Value) } rawSixthEntry, _ := p.Options.Get(uint32(142)) - sixthEntry := rawSixthEntry.(*SSHMatchBlock) + sixthEntry := rawSixthEntry.(*SSHDMatchBlock) if !(sixthEntry.MatchEntry.Value == "Match Address 172.22.100.0/24,172.22.5.0/24,127.0.0.1") { t.Errorf("Expected sixth entry to be 'Match Address 172.22.100.0/24,172.22.5.0/24,127.0.0.1', but got: %v", sixthEntry.MatchEntry.Value) } @@ -523,7 +523,7 @@ Match Address 172.22.100.0/24,172.22.5.0/24,127.0.0.1 } rawSeventhEntry, _ := sixthEntry.Options.Get(uint32(143)) - seventhEntry := rawSeventhEntry.(*SSHOption) + seventhEntry := rawSeventhEntry.(*SSHDOption) if !(seventhEntry.Key.Value == "PermitRootLogin" && seventhEntry.OptionValue.Value == "without-password") { t.Errorf("Expected seventh entry to be 'PermitRootLogin without-password', but got: %v", seventhEntry.Value) } diff --git a/handlers/sshd_config/ast/sshd_config.go b/handlers/sshd_config/ast/sshd_config.go index fb2edee..76987a2 100644 --- a/handlers/sshd_config/ast/sshd_config.go +++ b/handlers/sshd_config/ast/sshd_config.go @@ -7,52 +7,52 @@ import ( "github.com/emirpasic/gods/maps/treemap" ) -type SSHKey struct { +type SSHDKey struct { common.LocationRange Value string } -type SSHValue struct { +type SSHDValue struct { common.LocationRange Value string } -type SSHEntryType uint +type SSHDEntryType uint const ( - SSHEntryTypeOption SSHEntryType = iota - SSHEntryTypeMatchBlock + SSHDEntryTypeOption SSHDEntryType = iota + SSHDEntryTypeMatchBlock ) -type SSHEntry interface { - GetType() SSHEntryType - GetOption() SSHOption +type SSHDEntry interface { + GetType() SSHDEntryType + GetOption() SSHDOption } -type SSHSeparator struct { +type SSHDSeparator struct { common.LocationRange } -type SSHOption struct { +type SSHDOption struct { common.LocationRange Value string - Key *SSHKey - Separator *SSHSeparator - OptionValue *SSHValue + Key *SSHDKey + Separator *SSHDSeparator + OptionValue *SSHDValue } -type SSHMatchBlock struct { +type SSHDMatchBlock struct { common.LocationRange - MatchEntry *SSHOption + MatchEntry *SSHDOption MatchValue *match_parser.Match - // [uint32]*SSHOption -> line number -> *SSHOption + // [uint32]*SSHDOption -> line number -> *SSHDOption Options *treemap.Map } -type SSHConfig struct { - // [uint32]SSHOption -> line number -> *SSHEntry +type SSHDConfig struct { + // [uint32]SSHDOption -> line number -> *SSHDEntry Options *treemap.Map // [uint32]{} -> line number -> {} CommentLines map[uint32]struct{} diff --git a/handlers/sshd_config/ast/sshd_config_fields.go b/handlers/sshd_config/ast/sshd_config_fields.go index f82d49c..ce760bd 100644 --- a/handlers/sshd_config/ast/sshd_config_fields.go +++ b/handlers/sshd_config/ast/sshd_config_fields.go @@ -1,22 +1,22 @@ package ast -func (o SSHOption) GetType() SSHEntryType { - return SSHEntryTypeOption +func (o SSHDOption) GetType() SSHDEntryType { + return SSHDEntryTypeOption } -func (o SSHOption) GetOption() SSHOption { +func (o SSHDOption) GetOption() SSHDOption { return o } -func (m SSHMatchBlock) GetType() SSHEntryType { - return SSHEntryTypeMatchBlock +func (m SSHDMatchBlock) GetType() SSHDEntryType { + return SSHDEntryTypeMatchBlock } -func (m SSHMatchBlock) GetOption() SSHOption { +func (m SSHDMatchBlock) GetOption() SSHDOption { return *m.MatchEntry } -func (c SSHConfig) FindMatchBlock(line uint32) *SSHMatchBlock { +func (c SSHDConfig) FindMatchBlock(line uint32) *SSHDMatchBlock { for currentLine := line; currentLine > 0; currentLine-- { rawEntry, found := c.Options.Get(currentLine) @@ -25,7 +25,7 @@ func (c SSHConfig) FindMatchBlock(line uint32) *SSHMatchBlock { } switch entry := rawEntry.(type) { - case *SSHMatchBlock: + case *SSHDMatchBlock: return entry } } @@ -33,7 +33,7 @@ func (c SSHConfig) FindMatchBlock(line uint32) *SSHMatchBlock { return nil } -func (c SSHConfig) FindOption(line uint32) (*SSHOption, *SSHMatchBlock) { +func (c SSHDConfig) FindOption(line uint32) (*SSHDOption, *SSHDMatchBlock) { matchBlock := c.FindMatchBlock(line) if matchBlock != nil { @@ -44,7 +44,7 @@ func (c SSHConfig) FindOption(line uint32) (*SSHOption, *SSHMatchBlock) { rawEntry, found := matchBlock.Options.Get(line) if found { - return rawEntry.(*SSHOption), matchBlock + return rawEntry.(*SSHDOption), matchBlock } else { return nil, matchBlock } @@ -54,10 +54,10 @@ func (c SSHConfig) FindOption(line uint32) (*SSHOption, *SSHMatchBlock) { if found { switch rawEntry.(type) { - case *SSHMatchBlock: - return rawEntry.(*SSHMatchBlock).MatchEntry, rawEntry.(*SSHMatchBlock) - case *SSHOption: - return rawEntry.(*SSHOption), nil + case *SSHDMatchBlock: + return rawEntry.(*SSHDMatchBlock).MatchEntry, rawEntry.(*SSHDMatchBlock) + case *SSHDOption: + return rawEntry.(*SSHDOption), nil } } diff --git a/handlers/sshd_config/handlers/completions.go b/handlers/sshd_config/handlers/completions.go index f415b25..50930b7 100644 --- a/handlers/sshd_config/handlers/completions.go +++ b/handlers/sshd_config/handlers/completions.go @@ -13,7 +13,7 @@ import ( func GetRootCompletions( d *sshdconfig.SSHDocument, - parentMatchBlock *ast.SSHMatchBlock, + parentMatchBlock *ast.SSHDMatchBlock, suggestValue bool, ) ([]protocol.CompletionItem, error) { kind := protocol.CompletionItemKindField @@ -54,8 +54,8 @@ func GetRootCompletions( func GetOptionCompletions( d *sshdconfig.SSHDocument, - entry *ast.SSHOption, - matchBlock *ast.SSHMatchBlock, + entry *ast.SSHDOption, + matchBlock *ast.SSHDMatchBlock, cursor uint32, ) ([]protocol.CompletionItem, error) { option, found := fields.Options[entry.Key.Value] diff --git a/handlers/sshd_config/handlers/hover.go b/handlers/sshd_config/handlers/hover.go index 56a033a..6ce3ec8 100644 --- a/handlers/sshd_config/handlers/hover.go +++ b/handlers/sshd_config/handlers/hover.go @@ -10,8 +10,8 @@ import ( ) func GetHoverInfoForOption( - option *ast.SSHOption, - matchBlock *ast.SSHMatchBlock, + option *ast.SSHDOption, + matchBlock *ast.SSHDMatchBlock, line uint32, cursor uint32, ) (*protocol.Hover, error) { diff --git a/handlers/sshd_config/indexes/indexes.go b/handlers/sshd_config/indexes/indexes.go index ebdda30..8ba416d 100644 --- a/handlers/sshd_config/indexes/indexes.go +++ b/handlers/sshd_config/indexes/indexes.go @@ -20,12 +20,12 @@ var allowedDoubleOptions = map[string]struct{}{ type SSHIndexKey struct { Option string - MatchBlock *ast.SSHMatchBlock + MatchBlock *ast.SSHDMatchBlock } type SSHIndexAllOption struct { - MatchBlock *ast.SSHMatchBlock - Option *ast.SSHOption + MatchBlock *ast.SSHDMatchBlock + Option *ast.SSHDOption } type ValidPath string @@ -52,7 +52,7 @@ type SSHIndexes struct { // This means an option may be specified inside a match block, and to get this // option you need to know the match block it was specified in // If you want to get all options for a specific name, you can use the `AllOptionsPerName` field - OptionsPerRelativeKey map[SSHIndexKey][]*ast.SSHOption + OptionsPerRelativeKey map[SSHIndexKey][]*ast.SSHDOption // This is a map of `Option name` to a list of options with that name AllOptionsPerName map[string]map[uint32]*SSHIndexAllOption @@ -62,31 +62,31 @@ type SSHIndexes struct { var whitespacePattern = regexp.MustCompile(`\S+`) -func CreateIndexes(config ast.SSHConfig) (*SSHIndexes, []common.LSPError) { +func CreateIndexes(config ast.SSHDConfig) (*SSHIndexes, []common.LSPError) { errs := make([]common.LSPError, 0) indexes := &SSHIndexes{ - OptionsPerRelativeKey: make(map[SSHIndexKey][]*ast.SSHOption), + OptionsPerRelativeKey: make(map[SSHIndexKey][]*ast.SSHDOption), AllOptionsPerName: make(map[string]map[uint32]*SSHIndexAllOption), Includes: make(map[uint32]*SSHIndexIncludeLine), } it := config.Options.Iterator() for it.Next() { - entry := it.Value().(ast.SSHEntry) + entry := it.Value().(ast.SSHDEntry) switch entry.(type) { - case *ast.SSHOption: - option := entry.(*ast.SSHOption) + case *ast.SSHDOption: + option := entry.(*ast.SSHDOption) errs = append(errs, addOption(indexes, option, nil)...) - case *ast.SSHMatchBlock: - matchBlock := entry.(*ast.SSHMatchBlock) + case *ast.SSHDMatchBlock: + matchBlock := entry.(*ast.SSHDMatchBlock) errs = append(errs, addOption(indexes, matchBlock.MatchEntry, matchBlock)...) it := matchBlock.Options.Iterator() for it.Next() { - option := it.Value().(*ast.SSHOption) + option := it.Value().(*ast.SSHDOption) errs = append(errs, addOption(indexes, option, matchBlock)...) } @@ -135,8 +135,8 @@ func CreateIndexes(config ast.SSHConfig) (*SSHIndexes, []common.LSPError) { func addOption( i *SSHIndexes, - option *ast.SSHOption, - matchBlock *ast.SSHMatchBlock, + option *ast.SSHDOption, + matchBlock *ast.SSHDMatchBlock, ) []common.LSPError { var errs []common.LSPError @@ -156,7 +156,7 @@ func addOption( }) } } else { - i.OptionsPerRelativeKey[indexEntry] = []*ast.SSHOption{option} + i.OptionsPerRelativeKey[indexEntry] = []*ast.SSHDOption{option} } if _, found := i.AllOptionsPerName[option.Key.Value]; found { diff --git a/handlers/sshd_config/shared.go b/handlers/sshd_config/shared.go index b44850f..66e133f 100644 --- a/handlers/sshd_config/shared.go +++ b/handlers/sshd_config/shared.go @@ -8,7 +8,7 @@ import ( ) type SSHDocument struct { - Config *ast.SSHConfig + Config *ast.SSHDConfig Indexes *indexes.SSHIndexes } From eb587dfb422bf2adb505dcff5a5feb0db67235c5 Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Tue, 17 Sep 2024 21:21:31 +0200 Subject: [PATCH 046/133] feat(common): Add string parser --- common/parser/strings.go | 129 +++++++++++++++++++++++++ common/parser/strings_test.go | 177 ++++++++++++++++++++++++++++++++++ go.mod | 1 + go.sum | 2 + 4 files changed, 309 insertions(+) create mode 100644 common/parser/strings.go create mode 100644 common/parser/strings_test.go diff --git a/common/parser/strings.go b/common/parser/strings.go new file mode 100644 index 0000000..6ccc962 --- /dev/null +++ b/common/parser/strings.go @@ -0,0 +1,129 @@ +package parser + +type ParseFeatures struct { + ParseDoubleQuotes bool + ParseEscapedCharacters bool +} + +var FullFeatures = ParseFeatures{ + ParseDoubleQuotes: true, + ParseEscapedCharacters: true, +} + +type ParsedString struct { + Raw string + Value string + + Features ParseFeatures +} + +func ParseRawString( + raw string, + features ParseFeatures, +) ParsedString { + value := raw + + // Parse double quotes + if features.ParseDoubleQuotes { + value = ParseDoubleQuotes(value) + } + + // Parse escaped characters + if features.ParseEscapedCharacters { + value = ParseEscapedCharacters(value) + } + + return ParsedString{ + Raw: raw, + Value: value, + Features: features, + } +} + +func ParseDoubleQuotes( + raw string, +) string { + value := raw + currentIndex := 0 + + for { + start, found := findNextDoubleQuote(value, currentIndex) + + if found && start < (len(value)-1) { + currentIndex = max(0, start-1) + end, found := findNextDoubleQuote(value, start+1) + + if found { + insideContent := value[start+1 : end] + value = modifyString(value, start, end+1, insideContent) + + continue + } + } + + break + } + + return value +} + +func ParseEscapedCharacters( + raw string, +) string { + value := raw + currentIndex := 0 + + for { + position, found := findNextEscapedCharacter(value, currentIndex) + + if found { + currentIndex = max(0, position-1) + escapedCharacter := value[position+1] + value = modifyString(value, position, position+2, string(escapedCharacter)) + } else { + break + } + } + + return value +} + +func modifyString( + input string, + start int, + end int, + newValue string, +) string { + return input[:start] + newValue + input[end:] +} + +// Find the next non-escaped double quote in [raw] starting from [startIndex] +// When no double quote is found, return -1 +// Return as the second argument whether a double quote was found +func findNextDoubleQuote( + raw string, + startIndex int, +) (int, bool) { + for index := startIndex; index < len(raw); index++ { + if raw[index] == '"' { + if index == 0 || raw[index-1] != '\\' { + return index, true + } + } + } + + return -1, false +} + +func findNextEscapedCharacter( + raw string, + startIndex int, +) (int, bool) { + for index := startIndex; index < len(raw); index++ { + if raw[index] == '\\' && index < len(raw)-1 { + return index, true + } + } + + return -1, false +} diff --git a/common/parser/strings_test.go b/common/parser/strings_test.go new file mode 100644 index 0000000..bb3265b --- /dev/null +++ b/common/parser/strings_test.go @@ -0,0 +1,177 @@ +package parser + +import ( + "testing" + + "github.com/google/go-cmp/cmp" +) + +func TestStringsSingleWortQuotedFullFeatures( + t *testing.T, +) { + input := `hello "world"` + expected := ParsedString{ + Raw: input, + Value: "hello world", + Features: FullFeatures, + } + + actual := ParseRawString(input, FullFeatures) + + if !(cmp.Equal(expected, actual)) { + t.Errorf("Expected %v, got %v", expected, actual) + } +} + +func TestStringsFullyQuotedFullFeatures( + t *testing.T, +) { + input := `"hello world"` + expected := ParsedString{ + Raw: input, + Value: "hello world", + Features: FullFeatures, + } + + actual := ParseRawString(input, FullFeatures) + + if !(cmp.Equal(expected, actual)) { + t.Errorf("Expected %v, got %v", expected, actual) + } +} + +func TestStringsMultipleQuotesFullFeatures( + t *testing.T, +) { + input := `hello "world goodbye"` + expected := ParsedString{ + Raw: input, + Value: "hello world goodbye", + Features: FullFeatures, + } + + actual := ParseRawString(input, FullFeatures) + + if !(cmp.Equal(expected, actual)) { + t.Errorf("Expected %v, got %v", expected, actual) + } +} + +func TestStringsSimpleEscapedFullFeatures( + t *testing.T, +) { + input := `hello \"world` + expected := ParsedString{ + Raw: input, + Value: `hello "world`, + Features: FullFeatures, + } + + actual := ParseRawString(input, FullFeatures) + + if !(cmp.Equal(expected, actual)) { + t.Errorf("Expected %v, got %v", expected, actual) + } +} + +func TestStringsEscapedQuotesFullFeatures( + t *testing.T, +) { + input := `hello \"world\"` + expected := ParsedString{ + Raw: input, + Value: `hello "world"`, + Features: FullFeatures, + } + + actual := ParseRawString(input, FullFeatures) + + if !(cmp.Equal(expected, actual)) { + t.Errorf("Expected %v, got %v", expected, actual) + } +} + +func TestStringsQuotesAndEscapedFullFeatures( + t *testing.T, +) { + input := `hello "world how\" are you"` + expected := ParsedString{ + Raw: input, + Value: `hello world how" are you`, + Features: FullFeatures, + } + + actual := ParseRawString(input, FullFeatures) + + if !(cmp.Equal(expected, actual)) { + t.Errorf("Expected %v, got %v", expected, actual) + } +} + +func TestStringsIncompleteQuotesFullFeatures( + t *testing.T, +) { + input := `hello "world` + expected := ParsedString{ + Raw: input, + Value: `hello "world`, + Features: FullFeatures, + } + + actual := ParseRawString(input, FullFeatures) + + if !(cmp.Equal(expected, actual)) { + t.Errorf("Expected %v, got %v", expected, actual) + } +} + +func TestStringsIncompleteQuoteEscapedFullFeatures( + t *testing.T, +) { + input := `hello "world\"` + expected := ParsedString{ + Raw: input, + Value: `hello "world"`, + Features: FullFeatures, + } + + actual := ParseRawString(input, FullFeatures) + + if !(cmp.Equal(expected, actual)) { + t.Errorf("Expected %v, got %v", expected, actual) + } +} + +func TestStringsIncompleteQuotes2FullFeatures( + t *testing.T, +) { + input := `hello "world how" "are you` + expected := ParsedString{ + Raw: input, + Value: `hello world how "are you`, + Features: FullFeatures, + } + + actual := ParseRawString(input, FullFeatures) + + if !(cmp.Equal(expected, actual)) { + t.Errorf("Expected %v, got %v", expected, actual) + } +} + +func TestStringsIncompleteQuotes3FullFeatures( + t *testing.T, +) { + input := `hello "world how are you` + expected := ParsedString{ + Raw: input, + Value: `hello "world how are you`, + Features: FullFeatures, + } + + actual := ParseRawString(input, FullFeatures) + + if !(cmp.Equal(expected, actual)) { + t.Errorf("Expected %v, got %v", expected, actual) + } +} diff --git a/go.mod b/go.mod index 661cc9a..8c84359 100644 --- a/go.mod +++ b/go.mod @@ -11,6 +11,7 @@ require ( github.com/antlr4-go/antlr/v4 v4.13.1 // indirect github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect github.com/emirpasic/gods v1.18.1 // indirect + github.com/google/go-cmp v0.6.0 // indirect github.com/gorilla/websocket v1.5.3 // indirect github.com/iancoleman/strcase v0.3.0 // indirect github.com/k0kubun/pp v3.0.1+incompatible // indirect diff --git a/go.sum b/go.sum index 60c2e89..100a1f7 100644 --- a/go.sum +++ b/go.sum @@ -4,6 +4,8 @@ github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiE github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8= github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc= github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= From 3a0e88602138910d087b3642b7a1b9198b5d7187 Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Tue, 17 Sep 2024 23:25:36 +0200 Subject: [PATCH 047/133] chore: Migrate ast Value to ParsedString --- common/parser/strings.go | 7 +- common/parser/strings_test.go | 50 +++---- handlers/sshd_config/analyzer/match.go | 19 ++- handlers/sshd_config/analyzer/options.go | 16 +-- handlers/sshd_config/ast/listener.go | 18 ++- handlers/sshd_config/ast/parser_test.go | 66 ++++----- handlers/sshd_config/ast/sshd_config.go | 12 +- handlers/sshd_config/fields/fields.go | 10 ++ .../fields/match-parser/listener.go | 10 +- .../fields/match-parser/match_ast.go | 8 +- .../fields/match-parser/parser_test.go | 12 +- handlers/sshd_config/handlers/completions.go | 12 +- .../sshd_config/handlers/completions_match.go | 2 +- handlers/sshd_config/handlers/hover.go | 10 +- handlers/sshd_config/indexes/indexes.go | 125 +++++++++--------- handlers/sshd_config/indexes/indexes_test.go | 92 ++----------- .../lsp/text-document-completion.go | 2 +- .../lsp/text-document-definition.go | 2 +- 18 files changed, 206 insertions(+), 267 deletions(-) diff --git a/common/parser/strings.go b/common/parser/strings.go index 6ccc962..931983f 100644 --- a/common/parser/strings.go +++ b/common/parser/strings.go @@ -13,8 +13,6 @@ var FullFeatures = ParseFeatures{ type ParsedString struct { Raw string Value string - - Features ParseFeatures } func ParseRawString( @@ -34,9 +32,8 @@ func ParseRawString( } return ParsedString{ - Raw: raw, - Value: value, - Features: features, + Raw: raw, + Value: value, } } diff --git a/common/parser/strings_test.go b/common/parser/strings_test.go index bb3265b..e82352f 100644 --- a/common/parser/strings_test.go +++ b/common/parser/strings_test.go @@ -11,9 +11,8 @@ func TestStringsSingleWortQuotedFullFeatures( ) { input := `hello "world"` expected := ParsedString{ - Raw: input, - Value: "hello world", - Features: FullFeatures, + Raw: input, + Value: "hello world", } actual := ParseRawString(input, FullFeatures) @@ -28,9 +27,8 @@ func TestStringsFullyQuotedFullFeatures( ) { input := `"hello world"` expected := ParsedString{ - Raw: input, - Value: "hello world", - Features: FullFeatures, + Raw: input, + Value: "hello world", } actual := ParseRawString(input, FullFeatures) @@ -45,9 +43,8 @@ func TestStringsMultipleQuotesFullFeatures( ) { input := `hello "world goodbye"` expected := ParsedString{ - Raw: input, - Value: "hello world goodbye", - Features: FullFeatures, + Raw: input, + Value: "hello world goodbye", } actual := ParseRawString(input, FullFeatures) @@ -62,9 +59,8 @@ func TestStringsSimpleEscapedFullFeatures( ) { input := `hello \"world` expected := ParsedString{ - Raw: input, - Value: `hello "world`, - Features: FullFeatures, + Raw: input, + Value: `hello "world`, } actual := ParseRawString(input, FullFeatures) @@ -79,9 +75,8 @@ func TestStringsEscapedQuotesFullFeatures( ) { input := `hello \"world\"` expected := ParsedString{ - Raw: input, - Value: `hello "world"`, - Features: FullFeatures, + Raw: input, + Value: `hello "world"`, } actual := ParseRawString(input, FullFeatures) @@ -96,9 +91,8 @@ func TestStringsQuotesAndEscapedFullFeatures( ) { input := `hello "world how\" are you"` expected := ParsedString{ - Raw: input, - Value: `hello world how" are you`, - Features: FullFeatures, + Raw: input, + Value: `hello world how" are you`, } actual := ParseRawString(input, FullFeatures) @@ -113,9 +107,8 @@ func TestStringsIncompleteQuotesFullFeatures( ) { input := `hello "world` expected := ParsedString{ - Raw: input, - Value: `hello "world`, - Features: FullFeatures, + Raw: input, + Value: `hello "world`, } actual := ParseRawString(input, FullFeatures) @@ -130,9 +123,8 @@ func TestStringsIncompleteQuoteEscapedFullFeatures( ) { input := `hello "world\"` expected := ParsedString{ - Raw: input, - Value: `hello "world"`, - Features: FullFeatures, + Raw: input, + Value: `hello "world"`, } actual := ParseRawString(input, FullFeatures) @@ -147,9 +139,8 @@ func TestStringsIncompleteQuotes2FullFeatures( ) { input := `hello "world how" "are you` expected := ParsedString{ - Raw: input, - Value: `hello world how "are you`, - Features: FullFeatures, + Raw: input, + Value: `hello world how "are you`, } actual := ParseRawString(input, FullFeatures) @@ -164,9 +155,8 @@ func TestStringsIncompleteQuotes3FullFeatures( ) { input := `hello "world how are you` expected := ParsedString{ - Raw: input, - Value: `hello "world how are you`, - Features: FullFeatures, + Raw: input, + Value: `hello "world how are you`, } actual := ParseRawString(input, FullFeatures) diff --git a/handlers/sshd_config/analyzer/match.go b/handlers/sshd_config/analyzer/match.go index c5ad800..c773004 100644 --- a/handlers/sshd_config/analyzer/match.go +++ b/handlers/sshd_config/analyzer/match.go @@ -15,19 +15,18 @@ func analyzeMatchBlocks( ) []common.LSPError { errs := make([]common.LSPError, 0) - for _, indexOption := range d.Indexes.AllOptionsPerName["Match"] { - matchBlock := indexOption.MatchBlock.MatchValue - + for matchBlock, options := range d.Indexes.GetAllOptionsForName("Match") { + option := options[0] // Check if the match block has filled out all fields - if matchBlock == nil || len(matchBlock.Entries) == 0 { + if matchBlock == nil || matchBlock.MatchValue == nil || len(matchBlock.MatchValue.Entries) == 0 { errs = append(errs, common.LSPError{ - Range: indexOption.Option.LocationRange, + Range: option.LocationRange, Err: errors.New("A match expression is required"), }) continue } - for _, entry := range matchBlock.Entries { + for _, entry := range matchBlock.MatchValue.Entries { if entry.Values == nil { errs = append(errs, common.LSPError{ Range: entry.LocationRange, @@ -43,9 +42,9 @@ func analyzeMatchBlocks( } // Check if match blocks are not empty - if indexOption.MatchBlock.Options.Size() == 0 { + if matchBlock.Options.Size() == 0 { errs = append(errs, common.LSPError{ - Range: indexOption.Option.LocationRange, + Range: option.LocationRange, Err: errors.New("This match block is empty"), }) } @@ -59,7 +58,7 @@ func analyzeMatchValueNegation( ) []common.LSPError { errs := make([]common.LSPError, 0) - positionsAsList := utils.AllIndexes(value.Value, "!") + positionsAsList := utils.AllIndexes(value.Value.Value, "!") positions := utils.SliceToMap(positionsAsList, struct{}{}) delete(positions, 0) @@ -93,7 +92,7 @@ func analyzeMatchValuesContainsPositiveValue( containsPositive := false for _, value := range values.Values { - if !strings.HasPrefix(value.Value, "!") { + if !strings.HasPrefix(value.Value.Value, "!") { containsPositive = true break } diff --git a/handlers/sshd_config/analyzer/options.go b/handlers/sshd_config/analyzer/options.go index 40381b7..b6b07a1 100644 --- a/handlers/sshd_config/analyzer/options.go +++ b/handlers/sshd_config/analyzer/options.go @@ -40,33 +40,33 @@ func checkOption( errs := make([]common.LSPError, 0) if option.Key != nil { - docOption, found := fields.Options[option.Key.Value] + docOption, found := fields.Options[option.Key.Key] if !found { errs = append(errs, common.LSPError{ Range: option.Key.LocationRange, - Err: errors.New(fmt.Sprintf("Unknown option: %s", option.Key.Value)), + Err: errors.New(fmt.Sprintf("Unknown option: %s", option.Key.Key)), }) return errs } - if _, found := fields.MatchAllowedOptions[option.Key.Value]; !found && isInMatchBlock { + if _, found := fields.MatchAllowedOptions[option.Key.Key]; !found && isInMatchBlock { errs = append(errs, common.LSPError{ Range: option.Key.LocationRange, - Err: errors.New(fmt.Sprintf("Option '%s' is not allowed inside Match blocks", option.Key.Value)), + Err: errors.New(fmt.Sprintf("Option '%s' is not allowed inside Match blocks", option.Key.Key)), }) return errs } - if option.OptionValue == nil || option.OptionValue.Value == "" { + if option.OptionValue == nil || option.OptionValue.Value.Value == "" { errs = append(errs, common.LSPError{ Range: option.Key.LocationRange, - Err: errors.New(fmt.Sprintf("Option '%s' requires a value", option.Key.Value)), + Err: errors.New(fmt.Sprintf("Option '%s' requires a value", option.Key.Key)), }) } else { - invalidValues := docOption.CheckIsValid(option.OptionValue.Value) + invalidValues := docOption.CheckIsValid(option.OptionValue.Value.Value) errs = append( errs, @@ -93,7 +93,7 @@ func checkMatchBlock( matchOption := matchBlock.MatchEntry.OptionValue if matchOption != nil { - invalidValues := fields.Options["Match"].CheckIsValid(matchOption.Value) + invalidValues := fields.Options["Match"].CheckIsValid(matchOption.Value.Value) errs = append( errs, diff --git a/handlers/sshd_config/ast/listener.go b/handlers/sshd_config/ast/listener.go index c32e2d9..27fa37a 100644 --- a/handlers/sshd_config/ast/listener.go +++ b/handlers/sshd_config/ast/listener.go @@ -2,6 +2,7 @@ package ast import ( "config-lsp/common" + commonparser "config-lsp/common/parser" "config-lsp/handlers/sshd_config/ast/parser" match_parser "config-lsp/handlers/sshd_config/fields/match-parser" "strings" @@ -48,7 +49,7 @@ func (s *sshParserListener) EnterEntry(ctx *parser.EntryContext) { option := &SSHDOption{ LocationRange: location, - Value: ctx.GetText(), + Value: commonparser.ParseRawString(ctx.GetText(), commonparser.FullFeatures), } s.sshContext.currentOption = option @@ -59,6 +60,14 @@ func (s *sshParserListener) EnterKey(ctx *parser.KeyContext) { location.ChangeBothLines(s.sshContext.line) text := ctx.GetText() + value := commonparser.ParseRawString(text, commonparser.FullFeatures) + key := strings.TrimRight( + strings.TrimLeft( + value.Value, + " ", + ), + " ", + ) if strings.ToLower(text) == "match" { s.sshContext.isKeyAMatchBlock = true @@ -66,7 +75,8 @@ func (s *sshParserListener) EnterKey(ctx *parser.KeyContext) { s.sshContext.currentOption.Key = &SSHDKey{ LocationRange: location, - Value: ctx.GetText(), + Value: value, + Key: key, } } @@ -85,7 +95,7 @@ func (s *sshParserListener) EnterValue(ctx *parser.ValueContext) { s.sshContext.currentOption.OptionValue = &SSHDValue{ LocationRange: location, - Value: ctx.GetText(), + Value: commonparser.ParseRawString(ctx.GetText(), commonparser.FullFeatures), } } @@ -104,7 +114,7 @@ func (s *sshParserListener) ExitEntry(ctx *parser.EntryContext) { if s.sshContext.currentOption.OptionValue != nil { matchParser := match_parser.NewMatch() errors := matchParser.Parse( - s.sshContext.currentOption.OptionValue.Value, + s.sshContext.currentOption.OptionValue.Value.Raw, location.Start.Line, s.sshContext.currentOption.OptionValue.Start.Character, ) diff --git a/handlers/sshd_config/ast/parser_test.go b/handlers/sshd_config/ast/parser_test.go index 2b43b8d..46c6338 100644 --- a/handlers/sshd_config/ast/parser_test.go +++ b/handlers/sshd_config/ast/parser_test.go @@ -27,15 +27,15 @@ PasswordAuthentication yes rawFirstEntry, _ := p.Options.Get(uint32(0)) firstEntry := rawFirstEntry.(*SSHDOption) - if !(firstEntry.Value == "PermitRootLogin no" && + if !(firstEntry.Value.Value == "PermitRootLogin no" && firstEntry.LocationRange.Start.Line == 0 && firstEntry.LocationRange.End.Line == 0 && firstEntry.LocationRange.Start.Character == 0 && firstEntry.LocationRange.End.Character == 17 && - firstEntry.Key.Value == "PermitRootLogin" && + firstEntry.Key.Value.Value == "PermitRootLogin" && firstEntry.Key.LocationRange.Start.Character == 0 && firstEntry.Key.LocationRange.End.Character == 14 && - firstEntry.OptionValue.Value == "no" && + firstEntry.OptionValue.Value.Value == "no" && firstEntry.OptionValue.LocationRange.Start.Character == 16 && firstEntry.OptionValue.LocationRange.End.Character == 17) { t.Errorf("Expected first entry to be PermitRootLogin no, but got: %v", firstEntry) @@ -44,15 +44,15 @@ PasswordAuthentication yes rawSecondEntry, _ := p.Options.Get(uint32(1)) secondEntry := rawSecondEntry.(*SSHDOption) - if !(secondEntry.Value == "PasswordAuthentication yes" && + if !(secondEntry.Value.Value == "PasswordAuthentication yes" && secondEntry.LocationRange.Start.Line == 1 && secondEntry.LocationRange.End.Line == 1 && secondEntry.LocationRange.Start.Character == 0 && secondEntry.LocationRange.End.Character == 25 && - secondEntry.Key.Value == "PasswordAuthentication" && + secondEntry.Key.Value.Value == "PasswordAuthentication" && secondEntry.Key.LocationRange.Start.Character == 0 && secondEntry.Key.LocationRange.End.Character == 21 && - secondEntry.OptionValue.Value == "yes" && + secondEntry.OptionValue.Value.Value == "yes" && secondEntry.OptionValue.LocationRange.Start.Character == 23 && secondEntry.OptionValue.LocationRange.End.Character == 25) { t.Errorf("Expected second entry to be PasswordAuthentication yes, but got: %v", secondEntry) @@ -82,13 +82,13 @@ Match Address 192.168.0.1 rawFirstEntry, _ := p.Options.Get(uint32(0)) firstEntry := rawFirstEntry.(*SSHDOption) - if !(firstEntry.Value == "PermitRootLogin no") { + if !(firstEntry.Value.Value == "PermitRootLogin no") { t.Errorf("Expected first entry to be 'PermitRootLogin no', but got: %v", firstEntry.Value) } rawSecondEntry, _ := p.Options.Get(uint32(2)) secondEntry := rawSecondEntry.(*SSHDMatchBlock) - if !(secondEntry.MatchEntry.Value == "Match Address 192.168.0.1") { + if !(secondEntry.MatchEntry.Value.Value == "Match Address 192.168.0.1") { t.Errorf("Expected second entry to be 'Match Address 192.168.0.1', but got: %v", secondEntry.MatchEntry.Value) } @@ -96,7 +96,7 @@ Match Address 192.168.0.1 t.Errorf("Expected second entry's location to be 2:0-3:25, but got: %v", secondEntry.LocationRange) } - if !(secondEntry.MatchValue.Entries[0].Criteria.Type == "Address" && secondEntry.MatchValue.Entries[0].Values.Values[0].Value == "192.168.0.1" && secondEntry.MatchEntry.OptionValue.Start.Character == 6) { + if !(secondEntry.MatchValue.Entries[0].Criteria.Type == "Address" && secondEntry.MatchValue.Entries[0].Values.Values[0].Value.Value == "192.168.0.1" && secondEntry.MatchEntry.OptionValue.Start.Character == 6) { t.Errorf("Expected second entry to be 'Match Address 192.168.0.1', but got: %v", secondEntry.MatchValue) } @@ -106,7 +106,7 @@ Match Address 192.168.0.1 rawThirdEntry, _ := secondEntry.Options.Get(uint32(3)) thirdEntry := rawThirdEntry.(*SSHDOption) - if !(thirdEntry.Key.Value == "PasswordAuthentication" && thirdEntry.OptionValue.Value == "yes") { + if !(thirdEntry.Key.Value.Value == "PasswordAuthentication" && thirdEntry.OptionValue.Value.Value == "yes") { t.Errorf("Expected third entry to be 'PasswordAuthentication yes', but got: %v", thirdEntry.Value) } } @@ -126,7 +126,7 @@ Match User lena User root _, matchBlock := p.FindOption(uint32(0)) - if !(matchBlock.MatchEntry.Value == "Match User lena User root") { + if !(matchBlock.MatchEntry.Value.Value == "Match User lena User root") { t.Errorf("Expected match block to be 'Match User lena User root', but got: %v", matchBlock.MatchEntry.Value) } @@ -134,11 +134,11 @@ Match User lena User root t.Errorf("Expected 2 entries in match block, but got: %v", matchBlock.MatchValue.Entries) } - if !(matchBlock.MatchValue.Entries[0].Criteria.Type == "User" && matchBlock.MatchValue.Entries[0].Values.Values[0].Value == "lena") { + if !(matchBlock.MatchValue.Entries[0].Criteria.Type == "User" && matchBlock.MatchValue.Entries[0].Values.Values[0].Value.Value == "lena") { t.Errorf("Expected first entry to be 'User lena', but got: %v", matchBlock.MatchValue.Entries[0]) } - if !(matchBlock.MatchValue.Entries[1].Criteria.Type == "User" && matchBlock.MatchValue.Entries[1].Values.Values[0].Value == "root") { + if !(matchBlock.MatchValue.Entries[1].Criteria.Type == "User" && matchBlock.MatchValue.Entries[1].Values.Values[0].Value.Value == "root") { t.Errorf("Expected second entry to be 'User root', but got: %v", matchBlock.MatchValue.Entries[1]) } } @@ -157,15 +157,15 @@ func TestIncompleteMatchBlock( _, matchBlock := p.FindOption(uint32(0)) - if !(matchBlock.MatchEntry.Value == "Match User lena User ") { + if !(matchBlock.MatchEntry.Value.Value == "Match User lena User ") { t.Errorf("Expected match block to be 'Match User lena User ', but got: %v", matchBlock.MatchEntry.Value) } - if !(matchBlock.MatchValue.Entries[0].Criteria.Type == "User" && matchBlock.MatchValue.Entries[0].Values.Values[0].Value == "lena") { + if !(matchBlock.MatchValue.Entries[0].Criteria.Type == "User" && matchBlock.MatchValue.Entries[0].Values.Values[0].Value.Value == "lena") { t.Errorf("Expected first entry to be 'User lena', but got: %v", matchBlock.MatchValue.Entries[0]) } - if !(matchBlock.MatchValue.Entries[1].Value == "User " && matchBlock.MatchValue.Entries[1].Criteria.Type == "User" && matchBlock.MatchValue.Entries[1].Values == nil) { + if !(matchBlock.MatchValue.Entries[1].Value.Value == "User " && matchBlock.MatchValue.Entries[1].Criteria.Type == "User" && matchBlock.MatchValue.Entries[1].Values == nil) { t.Errorf("Expected second entry to be 'User ', but got: %v", matchBlock.MatchValue.Entries[1]) } } @@ -203,13 +203,13 @@ Match Address 192.168.0.2 rawThirdEntry, _ := secondEntry.Options.Get(uint32(3)) thirdEntry := rawThirdEntry.(*SSHDOption) - if !(thirdEntry.Key.Value == "PasswordAuthentication" && thirdEntry.OptionValue.Value == "yes" && thirdEntry.LocationRange.Start.Line == 3) { + if !(thirdEntry.Key.Value.Value == "PasswordAuthentication" && thirdEntry.OptionValue.Value.Value == "yes" && thirdEntry.LocationRange.Start.Line == 3) { t.Errorf("Expected third entry to be 'PasswordAuthentication yes', but got: %v", thirdEntry.Value) } rawFourthEntry, _ := secondEntry.Options.Get(uint32(4)) fourthEntry := rawFourthEntry.(*SSHDOption) - if !(fourthEntry.Key.Value == "AllowUsers" && fourthEntry.OptionValue.Value == "root user" && fourthEntry.LocationRange.Start.Line == 4) { + if !(fourthEntry.Key.Value.Value == "AllowUsers" && fourthEntry.OptionValue.Value.Value == "root user" && fourthEntry.LocationRange.Start.Line == 4) { t.Errorf("Expected fourth entry to be 'AllowUsers root user', but got: %v", fourthEntry.Value) } @@ -221,22 +221,22 @@ Match Address 192.168.0.2 rawSixthEntry, _ := fifthEntry.Options.Get(uint32(7)) sixthEntry := rawSixthEntry.(*SSHDOption) - if !(sixthEntry.Key.Value == "MaxAuthTries" && sixthEntry.OptionValue.Value == "3" && sixthEntry.LocationRange.Start.Line == 7) { + if !(sixthEntry.Key.Value.Value == "MaxAuthTries" && sixthEntry.OptionValue.Value.Value == "3" && sixthEntry.LocationRange.Start.Line == 7) { t.Errorf("Expected sixth entry to be 'MaxAuthTries 3', but got: %v", sixthEntry.Value) } firstOption, firstMatchBlock := p.FindOption(uint32(3)) - if !(firstOption.Key.Value == "PasswordAuthentication" && firstOption.OptionValue.Value == "yes") { + if !(firstOption.Key.Key == "PasswordAuthentication" && firstOption.OptionValue.Value.Value == "yes") { t.Errorf("Expected first option to be 'PasswordAuthentication yes' and first match block to be 'Match Address 192.168.0.1', but got: %v, %v", firstOption, firstMatchBlock) } emptyOption, matchBlock := p.FindOption(uint32(5)) - if !(emptyOption == nil && matchBlock.MatchEntry.Value == "Match User lena" && matchBlock.MatchValue.Entries[0].Values.Values[0].Value == "lena") { + if !(emptyOption == nil && matchBlock.MatchEntry.Value.Value == "Match User lena" && matchBlock.MatchValue.Entries[0].Values.Values[0].Value.Value == "lena") { t.Errorf("Expected empty option and match block to be 'Match User lena', but got: %v, %v", emptyOption, matchBlock) } matchOption, matchBlock := p.FindOption(uint32(2)) - if !(matchOption.Value == "Match User lena" && matchBlock.MatchEntry.Value == "Match User lena" && matchBlock.MatchValue.Entries[0].Values.Values[0].Value == "lena" && matchBlock.MatchEntry.OptionValue.Start.Character == 6) { + if !(matchOption.Value.Value == "Match User lena" && matchBlock.MatchEntry.Value.Value == "Match User lena" && matchBlock.MatchValue.Entries[0].Values.Values[0].Value.Value == "lena" && matchBlock.MatchEntry.OptionValue.Start.Character == 6) { t.Errorf("Expected match option to be 'Match User lena', but got: %v, %v", matchOption, matchBlock) } @@ -278,7 +278,7 @@ Sample rawFirstEntry, _ := p.Options.Get(uint32(1)) firstEntry := rawFirstEntry.(*SSHDOption) firstEntryOpt, _ := p.FindOption(uint32(1)) - if !(firstEntry.Value == "PermitRootLogin no" && firstEntry.LocationRange.Start.Line == 1 && firstEntryOpt == firstEntry) { + if !(firstEntry.Value.Value == "PermitRootLogin no" && firstEntry.LocationRange.Start.Line == 1 && firstEntryOpt == firstEntry) { t.Errorf("Expected first entry to be 'PermitRootLogin no', but got: %v", firstEntry.Value) } @@ -297,7 +297,7 @@ Sample rawSecondEntry, _ := p.Options.Get(uint32(5)) secondEntry := rawSecondEntry.(*SSHDOption) - if !(secondEntry.Value == "Sample") { + if !(secondEntry.Value.Value == "Sample") { t.Errorf("Expected second entry to be 'Sample', but got: %v", secondEntry.Value) } @@ -468,29 +468,29 @@ Match Address 172.22.100.0/24,172.22.5.0/24,127.0.0.1 rawFirstEntry, _ := p.Options.Get(uint32(38)) firstEntry := rawFirstEntry.(*SSHDOption) - if !(firstEntry.Key.Value == "PermitRootLogin" && firstEntry.OptionValue.Value == "no") { + if !(firstEntry.Key.Value.Value == "PermitRootLogin" && firstEntry.OptionValue.Value.Value == "no") { t.Errorf("Expected first entry to be 'PermitRootLogin no', but got: %v", firstEntry.Value) } rawSecondEntry, _ := p.Options.Get(uint32(60)) secondEntry := rawSecondEntry.(*SSHDOption) - if !(secondEntry.Key.Value == "PasswordAuthentication" && secondEntry.OptionValue.Value == "no") { + if !(secondEntry.Key.Value.Value == "PasswordAuthentication" && secondEntry.OptionValue.Value.Value == "no") { t.Errorf("Expected second entry to be 'PasswordAuthentication no', but got: %v", secondEntry.Value) } rawThirdEntry, _ := p.Options.Get(uint32(118)) thirdEntry := rawThirdEntry.(*SSHDOption) - if !(thirdEntry.Key.Value == "Subsystem" && thirdEntry.OptionValue.Value == "sftp\tinternal-sftp") { + if !(thirdEntry.Key.Value.Value == "Subsystem" && thirdEntry.OptionValue.Value.Value == "sftp\tinternal-sftp") { t.Errorf("Expected third entry to be 'Subsystem sftp internal-sftp', but got: %v", thirdEntry.Value) } rawFourthEntry, _ := p.Options.Get(uint32(135)) fourthEntry := rawFourthEntry.(*SSHDMatchBlock) - if !(fourthEntry.MatchEntry.Value == "Match User anoncvs") { + if !(fourthEntry.MatchEntry.Value.Value == "Match User anoncvs") { t.Errorf("Expected fourth entry to be 'Match User anoncvs', but got: %v", fourthEntry.MatchEntry.Value) } - if !(fourthEntry.MatchValue.Entries[0].Criteria.Type == "User" && fourthEntry.MatchValue.Entries[0].Values.Values[0].Value == "anoncvs") { + if !(fourthEntry.MatchValue.Entries[0].Criteria.Type == "User" && fourthEntry.MatchValue.Entries[0].Values.Values[0].Value.Value == "anoncvs") { t.Errorf("Expected fourth entry to be 'Match User anoncvs', but got: %v", fourthEntry.MatchValue) } @@ -500,17 +500,17 @@ Match Address 172.22.100.0/24,172.22.5.0/24,127.0.0.1 rawFifthEntry, _ := fourthEntry.Options.Get(uint32(136)) fifthEntry := rawFifthEntry.(*SSHDOption) - if !(fifthEntry.Key.Value == "X11Forwarding" && fifthEntry.OptionValue.Value == "no") { + if !(fifthEntry.Key.Value.Value == "X11Forwarding" && fifthEntry.OptionValue.Value.Value == "no") { t.Errorf("Expected fifth entry to be 'X11Forwarding no', but got: %v", fifthEntry.Value) } rawSixthEntry, _ := p.Options.Get(uint32(142)) sixthEntry := rawSixthEntry.(*SSHDMatchBlock) - if !(sixthEntry.MatchEntry.Value == "Match Address 172.22.100.0/24,172.22.5.0/24,127.0.0.1") { + if !(sixthEntry.MatchEntry.Value.Value == "Match Address 172.22.100.0/24,172.22.5.0/24,127.0.0.1") { t.Errorf("Expected sixth entry to be 'Match Address 172.22.100.0/24,172.22.5.0/24,127.0.0.1', but got: %v", sixthEntry.MatchEntry.Value) } - if !(sixthEntry.MatchEntry.Key.Value == "Match" && sixthEntry.MatchEntry.OptionValue.Value == "Address 172.22.100.0/24,172.22.5.0/24,127.0.0.1") { + if !(sixthEntry.MatchEntry.Key.Value.Value == "Match" && sixthEntry.MatchEntry.OptionValue.Value.Value == "Address 172.22.100.0/24,172.22.5.0/24,127.0.0.1") { t.Errorf("Expected sixth entry to be 'Match Address 172.22.100.0/24,172.22.5.0/24,127.0.0.1', but got: %v", sixthEntry.MatchEntry.Value) } @@ -524,7 +524,7 @@ Match Address 172.22.100.0/24,172.22.5.0/24,127.0.0.1 rawSeventhEntry, _ := sixthEntry.Options.Get(uint32(143)) seventhEntry := rawSeventhEntry.(*SSHDOption) - if !(seventhEntry.Key.Value == "PermitRootLogin" && seventhEntry.OptionValue.Value == "without-password") { + if !(seventhEntry.Key.Value.Value == "PermitRootLogin" && seventhEntry.OptionValue.Value.Value == "without-password") { t.Errorf("Expected seventh entry to be 'PermitRootLogin without-password', but got: %v", seventhEntry.Value) } } diff --git a/handlers/sshd_config/ast/sshd_config.go b/handlers/sshd_config/ast/sshd_config.go index 76987a2..fda6f34 100644 --- a/handlers/sshd_config/ast/sshd_config.go +++ b/handlers/sshd_config/ast/sshd_config.go @@ -2,19 +2,21 @@ package ast import ( "config-lsp/common" - match_parser "config-lsp/handlers/sshd_config/fields/match-parser" + commonparser "config-lsp/common/parser" + matchparser "config-lsp/handlers/sshd_config/fields/match-parser" "github.com/emirpasic/gods/maps/treemap" ) type SSHDKey struct { common.LocationRange - Value string + Value commonparser.ParsedString + Key string } type SSHDValue struct { common.LocationRange - Value string + Value commonparser.ParsedString } type SSHDEntryType uint @@ -35,7 +37,7 @@ type SSHDSeparator struct { type SSHDOption struct { common.LocationRange - Value string + Value commonparser.ParsedString Key *SSHDKey Separator *SSHDSeparator @@ -45,7 +47,7 @@ type SSHDOption struct { type SSHDMatchBlock struct { common.LocationRange MatchEntry *SSHDOption - MatchValue *match_parser.Match + MatchValue *matchparser.Match // [uint32]*SSHDOption -> line number -> *SSHDOption Options *treemap.Map diff --git a/handlers/sshd_config/fields/fields.go b/handlers/sshd_config/fields/fields.go index be277c3..09f9536 100644 --- a/handlers/sshd_config/fields/fields.go +++ b/handlers/sshd_config/fields/fields.go @@ -9,6 +9,16 @@ var ZERO = 0 var MAX_PORT = 65535 var MAX_FILE_MODE = 0777 +var AllowedDuplicateOptions = map[string]struct{}{ + "AllowGroups": {}, + "AllowUsers": {}, + "DenyGroups": {}, + "DenyUsers": {}, + "ListenAddress": {}, + "Match": {}, + "Port": {}, +} + var Options = map[string]docvalues.DocumentationValue{ "AcceptEnv": { Documentation: `Specifies what environment variables sent by the client will be copied into the session's environ(7). See SendEnv and SetEnv in ssh_config(5) for how to configure the client. The TERM environment variable is always accepted whenever the client requests a pseudo-terminal as it is required by the protocol. Variables are specified by name, which may contain the wildcard characters ‘*’ and ‘?’. Multiple environment variables may be separated by whitespace or spread across multiple AcceptEnv directives. Be warned that some environment variables could be used to bypass restricted user environments. For this reason, care should be taken in the use of this directive. The default is not to accept any environment variables.`, diff --git a/handlers/sshd_config/fields/match-parser/listener.go b/handlers/sshd_config/fields/match-parser/listener.go index 31bc0cb..01f6fb4 100644 --- a/handlers/sshd_config/fields/match-parser/listener.go +++ b/handlers/sshd_config/fields/match-parser/listener.go @@ -2,6 +2,7 @@ package match_parser import ( "config-lsp/common" + commonparser "config-lsp/common/parser" "config-lsp/handlers/sshd_config/fields/match-parser/parser" "config-lsp/utils" "errors" @@ -50,7 +51,7 @@ func (s *matchParserListener) EnterMatchEntry(ctx *parser.MatchEntryContext) { entry := &MatchEntry{ LocationRange: location, - Value: ctx.GetText(), + Value: commonparser.ParseRawString(ctx.GetText(), commonparser.FullFeatures), } s.match.Entries = append(s.match.Entries, entry) @@ -75,7 +76,9 @@ func (s *matchParserListener) EnterCriteria(ctx *parser.CriteriaContext) { location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext).ShiftHorizontal(s.matchContext.startCharacter) location.ChangeBothLines(s.matchContext.line) - criteria, found := availableCriteria[ctx.GetText()] + value := commonparser.ParseRawString(ctx.GetText(), commonparser.FullFeatures) + + criteria, found := availableCriteria[value.Value] if !found { s.Errors = append(s.Errors, common.LSPError{ @@ -88,6 +91,7 @@ func (s *matchParserListener) EnterCriteria(ctx *parser.CriteriaContext) { s.matchContext.currentEntry.Criteria = MatchCriteria{ LocationRange: location, Type: criteria, + Value: value, } } @@ -116,7 +120,7 @@ func (s *matchParserListener) EnterValue(ctx *parser.ValueContext) { value := &MatchValue{ LocationRange: location, - Value: ctx.GetText(), + Value: commonparser.ParseRawString(ctx.GetText(), commonparser.FullFeatures), } s.matchContext.currentEntry.Values.Values = append(s.matchContext.currentEntry.Values.Values, value) diff --git a/handlers/sshd_config/fields/match-parser/match_ast.go b/handlers/sshd_config/fields/match-parser/match_ast.go index d02a693..1d80f78 100644 --- a/handlers/sshd_config/fields/match-parser/match_ast.go +++ b/handlers/sshd_config/fields/match-parser/match_ast.go @@ -2,6 +2,7 @@ package match_parser import ( "config-lsp/common" + commonparser "config-lsp/common/parser" ) type Match struct { @@ -23,7 +24,8 @@ const ( type MatchCriteria struct { common.LocationRange - Type MatchCriteriaType + Type MatchCriteriaType + Value commonparser.ParsedString } type MatchSeparator struct { @@ -38,7 +40,7 @@ type MatchValues struct { type MatchEntry struct { common.LocationRange - Value string + Value commonparser.ParsedString Criteria MatchCriteria Separator *MatchSeparator @@ -47,5 +49,5 @@ type MatchEntry struct { type MatchValue struct { common.LocationRange - Value string + Value commonparser.ParsedString } diff --git a/handlers/sshd_config/fields/match-parser/parser_test.go b/handlers/sshd_config/fields/match-parser/parser_test.go index d24343a..2dbdb8a 100644 --- a/handlers/sshd_config/fields/match-parser/parser_test.go +++ b/handlers/sshd_config/fields/match-parser/parser_test.go @@ -25,15 +25,15 @@ func TestComplexExample( t.Fatalf("Expected User, but got %v", match.Entries[0]) } - if !(match.Entries[0].Values.Values[0].Value == "root" && match.Entries[0].Values.Values[0].Start.Character == 5+offset && match.Entries[0].Values.Values[0].End.Character == 8+offset && match.Entries[0].Start.Character == 0+offset && match.Entries[0].End.Character == 20+offset) { + if !(match.Entries[0].Values.Values[0].Value.Value == "root" && match.Entries[0].Values.Values[0].Start.Character == 5+offset && match.Entries[0].Values.Values[0].End.Character == 8+offset && match.Entries[0].Start.Character == 0+offset && match.Entries[0].End.Character == 20+offset) { t.Errorf("Expected root, but got %v", match.Entries[0].Values.Values[0]) } - if !(match.Entries[0].Values.Values[1].Value == "admin" && match.Entries[0].Values.Values[1].Start.Character == 10+offset && match.Entries[0].Values.Values[1].End.Character == 14+offset) { + if !(match.Entries[0].Values.Values[1].Value.Value == "admin" && match.Entries[0].Values.Values[1].Start.Character == 10+offset && match.Entries[0].Values.Values[1].End.Character == 14+offset) { t.Errorf("Expected admin, but got %v", match.Entries[0].Values.Values[1]) } - if !(match.Entries[0].Values.Values[2].Value == "alice" && match.Entries[0].Values.Values[2].Start.Character == 16+offset && match.Entries[0].Values.Values[2].End.Character == 20+offset) { + if !(match.Entries[0].Values.Values[2].Value.Value == "alice" && match.Entries[0].Values.Values[2].Start.Character == 16+offset && match.Entries[0].Values.Values[2].End.Character == 20+offset) { t.Errorf("Expected alice, but got %v", match.Entries[0].Values.Values[2]) } @@ -41,11 +41,11 @@ func TestComplexExample( t.Errorf("Expected Address, but got %v", match.Entries[1]) } - if !(match.Entries[1].Values.Values[0].Value == "*" && match.Entries[1].Values.Values[0].Start.Character == 30+offset && match.Entries[1].Values.Values[0].End.Character == 30+offset) { + if !(match.Entries[1].Values.Values[0].Value.Value == "*" && match.Entries[1].Values.Values[0].Start.Character == 30+offset && match.Entries[1].Values.Values[0].End.Character == 30+offset) { t.Errorf("Expected *, but got %v", match.Entries[1].Values.Values[0]) } - if !(match.Entries[1].Values.Values[1].Value == "!192.168.0.1" && match.Entries[1].Values.Values[1].Start.Character == 32+offset && match.Entries[1].Values.Values[1].End.Character == 43+offset) { + if !(match.Entries[1].Values.Values[1].Value.Value == "!192.168.0.1" && match.Entries[1].Values.Values[1].Start.Character == 32+offset && match.Entries[1].Values.Values[1].End.Character == 43+offset) { t.Errorf("Expected !192.168.0.1, but got %v", match.Entries[1].Values.Values[1]) } } @@ -74,7 +74,7 @@ func TestSecondComplexExample( t.Fatalf("Expected 3 values, but got %v", len(match.Entries[0].Values.Values)) } - if !(match.Entries[0].Values.Values[0].Value == "172.22.100.0/24") { + if !(match.Entries[0].Values.Values[0].Value.Value == "172.22.100.0/24") { t.Fatalf("Expected 172.22.100.0/24, but got %v", match.Entries[0].Values.Values[0]) } } diff --git a/handlers/sshd_config/handlers/completions.go b/handlers/sshd_config/handlers/completions.go index 50930b7..034a30e 100644 --- a/handlers/sshd_config/handlers/completions.go +++ b/handlers/sshd_config/handlers/completions.go @@ -58,13 +58,13 @@ func GetOptionCompletions( matchBlock *ast.SSHDMatchBlock, cursor uint32, ) ([]protocol.CompletionItem, error) { - option, found := fields.Options[entry.Key.Value] + option, found := fields.Options[entry.Key.Key] if !found { return nil, nil } - if entry.Key.Value == "Match" { + if entry.Key.Key == "Match" { return getMatchCompletions( d, matchBlock.MatchValue, @@ -72,11 +72,13 @@ func GetOptionCompletions( ) } - line := entry.OptionValue.Value - if entry.OptionValue == nil { return option.FetchCompletions("", 0), nil } - return option.FetchCompletions(line, common.CursorToCharacterIndex(cursor)), nil + line := entry.OptionValue.Value.Raw + return option.FetchCompletions( + line, + common.CursorToCharacterIndex(cursor)-entry.OptionValue.Start.Character, + ), nil } diff --git a/handlers/sshd_config/handlers/completions_match.go b/handlers/sshd_config/handlers/completions_match.go index 6a10ebe..462afa4 100644 --- a/handlers/sshd_config/handlers/completions_match.go +++ b/handlers/sshd_config/handlers/completions_match.go @@ -83,7 +83,7 @@ func getMatchValueCompletions( var relativeCursor uint32 if value != nil { - line = value.Value + line = value.Value.Raw relativeCursor = cursor - value.Start.Character } else { line = "" diff --git a/handlers/sshd_config/handlers/hover.go b/handlers/sshd_config/handlers/hover.go index 6ce3ec8..f8ad890 100644 --- a/handlers/sshd_config/handlers/hover.go +++ b/handlers/sshd_config/handlers/hover.go @@ -19,11 +19,11 @@ func GetHoverInfoForOption( // Either root level or in the line of a match block if matchBlock == nil || matchBlock.Start.Line == line { - val := fields.Options[option.Key.Value] + val := fields.Options[option.Key.Key] docValue = &val } else { - if _, found := fields.MatchAllowedOptions[option.Key.Value]; found { - val := fields.Options[option.Key.Value] + if _, found := fields.MatchAllowedOptions[option.Key.Key]; found { + val := fields.Options[option.Key.Key] docValue = &val } } @@ -31,7 +31,7 @@ func GetHoverInfoForOption( if cursor >= option.Key.Start.Character && cursor <= option.Key.End.Character { if docValue != nil { contents := []string{ - "## " + option.Key.Value, + "## " + option.Key.Key, "", } contents = append(contents, docValue.Documentation) @@ -54,7 +54,7 @@ func GetHoverInfoForOption( if option.OptionValue != nil && cursor >= option.OptionValue.Start.Character && cursor <= option.OptionValue.End.Character { relativeCursor := cursor - option.OptionValue.Start.Character - contents := docValue.FetchHoverInfo(option.OptionValue.Value, relativeCursor) + contents := docValue.FetchHoverInfo(option.OptionValue.Value.Raw, relativeCursor) return &protocol.Hover{ Contents: strings.Join(contents, "\n"), diff --git a/handlers/sshd_config/indexes/indexes.go b/handlers/sshd_config/indexes/indexes.go index 8ba416d..bd7f07e 100644 --- a/handlers/sshd_config/indexes/indexes.go +++ b/handlers/sshd_config/indexes/indexes.go @@ -3,37 +3,24 @@ package indexes import ( "config-lsp/common" "config-lsp/handlers/sshd_config/ast" + "config-lsp/handlers/sshd_config/fields" "errors" "fmt" "regexp" ) -var allowedDoubleOptions = map[string]struct{}{ - "AllowGroups": {}, - "AllowUsers": {}, - "DenyGroups": {}, - "DenyUsers": {}, - "ListenAddress": {}, - "Match": {}, - "Port": {}, -} - -type SSHIndexKey struct { - Option string - MatchBlock *ast.SSHDMatchBlock -} - -type SSHIndexAllOption struct { - MatchBlock *ast.SSHDMatchBlock - Option *ast.SSHDOption -} - type ValidPath string func (v ValidPath) AsURI() string { return "file://" + string(v) } +// SSHIndexIncludeValue Used to store the individual includes +// An `Include` statement can have multiple paths, +// each [SSHIndexIncludeValue] represents a single entered path. +// Note that an entered path can represent multiple real paths, as +// the path can contain wildcards. +// All true paths are stored in the [Paths] field. type SSHIndexIncludeValue struct { common.LocationRange Value string @@ -43,31 +30,37 @@ type SSHIndexIncludeValue struct { } type SSHIndexIncludeLine struct { - Values []*SSHIndexIncludeValue - Option *SSHIndexAllOption + Values []*SSHIndexIncludeValue + Option *ast.SSHDOption + MatchBlock *ast.SSHDMatchBlock } type SSHIndexes struct { - // Contains a map of `Option name + MatchBlock` to a list of options with that name - // This means an option may be specified inside a match block, and to get this - // option you need to know the match block it was specified in - // If you want to get all options for a specific name, you can use the `AllOptionsPerName` field - OptionsPerRelativeKey map[SSHIndexKey][]*ast.SSHDOption - // This is a map of `Option name` to a list of options with that name - AllOptionsPerName map[string]map[uint32]*SSHIndexAllOption + AllOptionsPerName map[*ast.SSHDMatchBlock](map[string]([]*ast.SSHDOption)) Includes map[uint32]*SSHIndexIncludeLine } +func (i SSHIndexes) GetAllOptionsForName(name string) map[*ast.SSHDMatchBlock][]*ast.SSHDOption { + allOptions := make(map[*ast.SSHDMatchBlock][]*ast.SSHDOption) + + for matchBlock, options := range i.AllOptionsPerName { + if opts, found := options[name]; found { + allOptions[matchBlock] = opts + } + } + + return allOptions +} + var whitespacePattern = regexp.MustCompile(`\S+`) func CreateIndexes(config ast.SSHDConfig) (*SSHIndexes, []common.LSPError) { errs := make([]common.LSPError, 0) indexes := &SSHIndexes{ - OptionsPerRelativeKey: make(map[SSHIndexKey][]*ast.SSHDOption), - AllOptionsPerName: make(map[string]map[uint32]*SSHIndexAllOption), - Includes: make(map[uint32]*SSHIndexIncludeLine), + AllOptionsPerName: make(map[*ast.SSHDMatchBlock](map[string]([]*ast.SSHDOption))), + Includes: make(map[uint32]*SSHIndexIncludeLine), } it := config.Options.Iterator() @@ -94,8 +87,9 @@ func CreateIndexes(config ast.SSHDConfig) (*SSHIndexes, []common.LSPError) { } // Add Includes - for _, includeOption := range indexes.AllOptionsPerName["Include"] { - rawValue := includeOption.Option.OptionValue.Value + for matchBlock, options := range indexes.GetAllOptionsForName("Include") { + includeOption := options[0] + rawValue := includeOption.OptionValue.Value.Value pathIndexes := whitespacePattern.FindAllStringIndex(rawValue, -1) paths := make([]*SSHIndexIncludeValue, 0) @@ -105,15 +99,15 @@ func CreateIndexes(config ast.SSHDConfig) (*SSHIndexes, []common.LSPError) { rawPath := rawValue[startIndex:endIndex] - offset := includeOption.Option.OptionValue.Start.Character + offset := includeOption.OptionValue.Start.Character path := SSHIndexIncludeValue{ LocationRange: common.LocationRange{ Start: common.Location{ - Line: includeOption.Option.Start.Line, + Line: includeOption.Start.Line, Character: uint32(startIndex) + offset, }, End: common.Location{ - Line: includeOption.Option.Start.Line, + Line: includeOption.Start.Line, Character: uint32(endIndex) + offset - 1, }, }, @@ -124,9 +118,10 @@ func CreateIndexes(config ast.SSHDConfig) (*SSHIndexes, []common.LSPError) { paths = append(paths, &path) } - indexes.Includes[includeOption.Option.Start.Line] = &SSHIndexIncludeLine{ - Values: paths, - Option: includeOption, + indexes.Includes[includeOption.Start.Line] = &SSHIndexIncludeLine{ + Values: paths, + Option: includeOption, + MatchBlock: matchBlock, } } @@ -140,35 +135,33 @@ func addOption( ) []common.LSPError { var errs []common.LSPError - indexEntry := SSHIndexKey{ - Option: option.Key.Value, - MatchBlock: matchBlock, - } - - if existingEntry, found := i.OptionsPerRelativeKey[indexEntry]; found { - if _, found := allowedDoubleOptions[option.Key.Value]; found { - // Double value, but doubles are allowed - i.OptionsPerRelativeKey[indexEntry] = append(existingEntry, option) + if optionsMap, found := i.AllOptionsPerName[matchBlock]; found { + if options, found := optionsMap[option.Key.Key]; found { + if _, duplicatesAllowed := fields.AllowedDuplicateOptions[option.Key.Key]; !duplicatesAllowed { + firstDefinedOption := options[0] + errs = append(errs, common.LSPError{ + Range: option.Key.LocationRange, + Err: errors.New(fmt.Sprintf( + "Option '%s' has already been defined on line %d", + option.Key.Key, + firstDefinedOption.Start.Line, + )), + }) + } else { + i.AllOptionsPerName[matchBlock][option.Key.Key] = append( + i.AllOptionsPerName[matchBlock][option.Key.Key], + option, + ) + } } else { - errs = append(errs, common.LSPError{ - Range: option.Key.LocationRange, - Err: errors.New(fmt.Sprintf("Option %s is already defined on line %d", option.Key.Value, existingEntry[0].Start.Line+1)), - }) + i.AllOptionsPerName[matchBlock][option.Key.Key] = []*ast.SSHDOption{ + option, + } } } else { - i.OptionsPerRelativeKey[indexEntry] = []*ast.SSHDOption{option} - } - - if _, found := i.AllOptionsPerName[option.Key.Value]; found { - i.AllOptionsPerName[option.Key.Value][option.Start.Line] = &SSHIndexAllOption{ - MatchBlock: matchBlock, - Option: option, - } - } else { - i.AllOptionsPerName[option.Key.Value] = map[uint32]*SSHIndexAllOption{ - option.Start.Line: { - MatchBlock: matchBlock, - Option: option, + i.AllOptionsPerName[matchBlock] = map[string]([]*ast.SSHDOption){ + option.Key.Key: { + option, }, } } diff --git a/handlers/sshd_config/indexes/indexes_test.go b/handlers/sshd_config/indexes/indexes_test.go index 9d69b92..f2f8691 100644 --- a/handlers/sshd_config/indexes/indexes_test.go +++ b/handlers/sshd_config/indexes/indexes_test.go @@ -6,44 +6,6 @@ import ( "testing" ) -func TestSimpleExample( - t *testing.T, -) { - input := utils.Dedent(` -PermitRootLogin yes -RootLogin yes -PermitRootLogin no -`) - config := ast.NewSSHConfig() - errors := config.Parse(input) - - if len(errors) > 0 { - t.Fatalf("Unexpected errors: %v", errors) - } - - indexes, errors := CreateIndexes(*config) - - if !(len(errors) == 1) { - t.Fatalf("Expected 1 error, but got %v", len(errors)) - } - - indexEntry := SSHIndexKey{ - Option: "PermitRootLogin", - MatchBlock: nil, - } - if !(indexes.OptionsPerRelativeKey[indexEntry][0].Value == "PermitRootLogin yes" && indexes.OptionsPerRelativeKey[indexEntry][0].Start.Line == 0) { - t.Errorf("Expected 'PermitRootLogin yes', but got %v", indexes.OptionsPerRelativeKey[indexEntry][0].Value) - } - - indexEntry = SSHIndexKey{ - Option: "RootLogin", - MatchBlock: nil, - } - if !(indexes.OptionsPerRelativeKey[indexEntry][0].Value == "RootLogin yes" && indexes.OptionsPerRelativeKey[indexEntry][0].Start.Line == 1) { - t.Errorf("Expected 'RootLogin yes', but got %v", indexes.OptionsPerRelativeKey[indexEntry][0].Value) - } -} - func TestComplexExample( t *testing.T, ) { @@ -68,52 +30,20 @@ Match Address 192.168.0.1/24 indexes, errors := CreateIndexes(*config) if !(len(errors) == 1) { - t.Fatalf("Expected no errors, but got %v", len(errors)) - } - - indexEntry := SSHIndexKey{ - Option: "PermitRootLogin", - MatchBlock: nil, - } - if !(indexes.OptionsPerRelativeKey[indexEntry][0].Value == "PermitRootLogin yes" && indexes.OptionsPerRelativeKey[indexEntry][0].Start.Line == 0) { - t.Errorf("Expected 'PermitRootLogin yes' on line 0, but got %v on line %v", indexes.OptionsPerRelativeKey[indexEntry][0].Value, indexes.OptionsPerRelativeKey[indexEntry][0].Start.Line) + t.Fatalf("Expected one errors, but got %v", len(errors)) } firstMatchBlock := config.FindMatchBlock(uint32(6)) - indexEntry = SSHIndexKey{ - Option: "PermitRootLogin", - MatchBlock: firstMatchBlock, - } - if !(indexes.OptionsPerRelativeKey[indexEntry][0].Value == "\tPermitRootLogin no" && indexes.OptionsPerRelativeKey[indexEntry][0].Start.Line == 6) { - t.Errorf("Expected 'PermitRootLogin no' on line 6, but got %v on line %v", indexes.OptionsPerRelativeKey[indexEntry][0].Value, indexes.OptionsPerRelativeKey[indexEntry][0].Start.Line) - } - - // Double check - indexEntry = SSHIndexKey{ - Option: "Port", - MatchBlock: nil, - } - if !(indexes.OptionsPerRelativeKey[indexEntry][0].Value == "Port 22" && - indexes.OptionsPerRelativeKey[indexEntry][0].Start.Line == 1 && - len(indexes.OptionsPerRelativeKey[indexEntry]) == 3 && - indexes.OptionsPerRelativeKey[indexEntry][1].Value == "Port 2022" && - indexes.OptionsPerRelativeKey[indexEntry][1].Start.Line == 2 && - indexes.OptionsPerRelativeKey[indexEntry][2].Value == "Port 2024" && - indexes.OptionsPerRelativeKey[indexEntry][2].Start.Line == 3) { - t.Errorf("Expected 'Port 22' on line 1, but got %v on line %v", indexes.OptionsPerRelativeKey[indexEntry][0].Value, indexes.OptionsPerRelativeKey[indexEntry][0].Start.Line) - } - - if !(len(indexes.AllOptionsPerName["PermitRootLogin"]) == 3 && - indexes.AllOptionsPerName["PermitRootLogin"][0].Option.Value == "PermitRootLogin yes" && - indexes.AllOptionsPerName["PermitRootLogin"][0].Option.Start.Line == 0 && - indexes.AllOptionsPerName["PermitRootLogin"][0].MatchBlock == nil && - indexes.AllOptionsPerName["PermitRootLogin"][6].Option.Value == "\tPermitRootLogin no" && - indexes.AllOptionsPerName["PermitRootLogin"][6].Option.Start.Line == 6 && - indexes.AllOptionsPerName["PermitRootLogin"][6].MatchBlock == firstMatchBlock && - indexes.AllOptionsPerName["PermitRootLogin"][8].Option.Value == "\tPermitRootLogin yes" && - indexes.AllOptionsPerName["PermitRootLogin"][8].Option.Start.Line == 8 && - indexes.AllOptionsPerName["PermitRootLogin"][8].MatchBlock == firstMatchBlock) { - t.Errorf("Expected 3 PermitRootLogin options, but got %v", indexes.AllOptionsPerName["PermitRootLogin"]) + opts := indexes.GetAllOptionsForName("PermitRootLogin") + if !(len(opts) == 2 && + len(opts[nil]) == 1 && + opts[nil][0].Value.Value == "PermitRootLogin yes" && + opts[nil][0].Start.Line == 0 && + len(opts[firstMatchBlock]) == 1 && + opts[firstMatchBlock][0].Value.Value == "\tPermitRootLogin no" && + opts[firstMatchBlock][0].Start.Line == 6 && + opts[firstMatchBlock][0].Key.Key == "PermitRootLogin") { + t.Errorf("Expected 3 PermitRootLogin options, but got %v", opts) } } diff --git a/handlers/sshd_config/lsp/text-document-completion.go b/handlers/sshd_config/lsp/text-document-completion.go index c0d3e37..e91deaf 100644 --- a/handlers/sshd_config/lsp/text-document-completion.go +++ b/handlers/sshd_config/lsp/text-document-completion.go @@ -33,7 +33,7 @@ func TextDocumentCompletion(context *glsp.Context, params *protocol.CompletionPa d, matchBlock, // Empty line, or currently typing a new key - entry == nil || isEmptyPattern.Match([]byte(entry.Value[cursor:])), + entry == nil || isEmptyPattern.Match([]byte(entry.Value.Value[cursor:])), ) } diff --git a/handlers/sshd_config/lsp/text-document-definition.go b/handlers/sshd_config/lsp/text-document-definition.go index 7ccdb66..627c400 100644 --- a/handlers/sshd_config/lsp/text-document-definition.go +++ b/handlers/sshd_config/lsp/text-document-definition.go @@ -14,7 +14,7 @@ func TextDocumentDefinition(context *glsp.Context, params *protocol.DefinitionPa line := params.Position.Line if include, found := d.Indexes.Includes[line]; found { - relativeCursor := cursor - include.Option.Option.LocationRange.Start.Character + relativeCursor := cursor - include.Option.LocationRange.Start.Character return handlers.GetIncludeOptionLocation(include, relativeCursor), nil } From 7bb34c32b4972867a3ee953409e619cf2dbb332c Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Tue, 17 Sep 2024 23:27:09 +0200 Subject: [PATCH 048/133] fix(sshd_config): Some bugfixes --- handlers/sshd_config/handlers/completions.go | 2 +- handlers/sshd_config/indexes/indexes.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/handlers/sshd_config/handlers/completions.go b/handlers/sshd_config/handlers/completions.go index 034a30e..e076030 100644 --- a/handlers/sshd_config/handlers/completions.go +++ b/handlers/sshd_config/handlers/completions.go @@ -79,6 +79,6 @@ func GetOptionCompletions( line := entry.OptionValue.Value.Raw return option.FetchCompletions( line, - common.CursorToCharacterIndex(cursor)-entry.OptionValue.Start.Character, + common.CursorToCharacterIndex(cursor-entry.OptionValue.Start.Character), ), nil } diff --git a/handlers/sshd_config/indexes/indexes.go b/handlers/sshd_config/indexes/indexes.go index bd7f07e..37247c4 100644 --- a/handlers/sshd_config/indexes/indexes.go +++ b/handlers/sshd_config/indexes/indexes.go @@ -144,7 +144,7 @@ func addOption( Err: errors.New(fmt.Sprintf( "Option '%s' has already been defined on line %d", option.Key.Key, - firstDefinedOption.Start.Line, + firstDefinedOption.Start.Line+1, )), }) } else { From 35c722995d51ae6f119621d887f82bb7c7b321b7 Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Tue, 17 Sep 2024 23:33:32 +0200 Subject: [PATCH 049/133] fix(sshd_config): Improve indexes structure --- handlers/sshd_config/analyzer/match.go | 2 +- handlers/sshd_config/handlers/definition.go | 4 +- handlers/sshd_config/indexes/handlers.go | 125 ++++++++++++++++ handlers/sshd_config/indexes/indexes.go | 147 +------------------ handlers/sshd_config/indexes/indexes_test.go | 2 +- handlers/sshd_config/shared.go | 2 +- 6 files changed, 138 insertions(+), 144 deletions(-) create mode 100644 handlers/sshd_config/indexes/handlers.go diff --git a/handlers/sshd_config/analyzer/match.go b/handlers/sshd_config/analyzer/match.go index c773004..cf1491e 100644 --- a/handlers/sshd_config/analyzer/match.go +++ b/handlers/sshd_config/analyzer/match.go @@ -15,7 +15,7 @@ func analyzeMatchBlocks( ) []common.LSPError { errs := make([]common.LSPError, 0) - for matchBlock, options := range d.Indexes.GetAllOptionsForName("Match") { + for matchBlock, options := range d.Indexes.AllOptionsPerName["Match"] { option := options[0] // Check if the match block has filled out all fields if matchBlock == nil || matchBlock.MatchValue == nil || len(matchBlock.MatchValue.Entries) == 0 { diff --git a/handlers/sshd_config/handlers/definition.go b/handlers/sshd_config/handlers/definition.go index 19449c3..50de94d 100644 --- a/handlers/sshd_config/handlers/definition.go +++ b/handlers/sshd_config/handlers/definition.go @@ -10,13 +10,13 @@ import ( ) func GetIncludeOptionLocation( - include *indexes.SSHIndexIncludeLine, + include *indexes.SSHDIndexIncludeLine, cursor uint32, ) []protocol.Location { index, found := slices.BinarySearchFunc( include.Values, cursor, - func(i *indexes.SSHIndexIncludeValue, cursor uint32) int { + func(i *indexes.SSHDIndexIncludeValue, cursor uint32) int { if cursor < i.Start.Character { return -1 } diff --git a/handlers/sshd_config/indexes/handlers.go b/handlers/sshd_config/indexes/handlers.go new file mode 100644 index 0000000..371a200 --- /dev/null +++ b/handlers/sshd_config/indexes/handlers.go @@ -0,0 +1,125 @@ +package indexes + +import ( + "config-lsp/common" + "config-lsp/handlers/sshd_config/ast" + "config-lsp/handlers/sshd_config/fields" + "errors" + "fmt" + "regexp" +) + +var whitespacePattern = regexp.MustCompile(`\S+`) + +func CreateIndexes(config ast.SSHDConfig) (*SSHDIndexes, []common.LSPError) { + errs := make([]common.LSPError, 0) + indexes := &SSHDIndexes{ + AllOptionsPerName: make(map[string](map[*ast.SSHDMatchBlock]([]*ast.SSHDOption))), + Includes: make(map[uint32]*SSHDIndexIncludeLine), + } + + it := config.Options.Iterator() + for it.Next() { + entry := it.Value().(ast.SSHDEntry) + + switch entry.(type) { + case *ast.SSHDOption: + option := entry.(*ast.SSHDOption) + + errs = append(errs, addOption(indexes, option, nil)...) + case *ast.SSHDMatchBlock: + matchBlock := entry.(*ast.SSHDMatchBlock) + + errs = append(errs, addOption(indexes, matchBlock.MatchEntry, matchBlock)...) + + it := matchBlock.Options.Iterator() + for it.Next() { + option := it.Value().(*ast.SSHDOption) + + errs = append(errs, addOption(indexes, option, matchBlock)...) + } + } + } + + // Add Includes + for matchBlock, options := range indexes.AllOptionsPerName["Include"] { + includeOption := options[0] + rawValue := includeOption.OptionValue.Value.Value + pathIndexes := whitespacePattern.FindAllStringIndex(rawValue, -1) + paths := make([]*SSHDIndexIncludeValue, 0) + + for _, pathIndex := range pathIndexes { + startIndex := pathIndex[0] + endIndex := pathIndex[1] + + rawPath := rawValue[startIndex:endIndex] + + offset := includeOption.OptionValue.Start.Character + path := SSHDIndexIncludeValue{ + LocationRange: common.LocationRange{ + Start: common.Location{ + Line: includeOption.Start.Line, + Character: uint32(startIndex) + offset, + }, + End: common.Location{ + Line: includeOption.Start.Line, + Character: uint32(endIndex) + offset - 1, + }, + }, + Value: rawPath, + Paths: make([]ValidPath, 0), + } + + paths = append(paths, &path) + } + + indexes.Includes[includeOption.Start.Line] = &SSHDIndexIncludeLine{ + Values: paths, + Option: includeOption, + MatchBlock: matchBlock, + } + } + + return indexes, errs +} + +func addOption( + i *SSHDIndexes, + option *ast.SSHDOption, + matchBlock *ast.SSHDMatchBlock, +) []common.LSPError { + var errs []common.LSPError + + if optionsMap, found := i.AllOptionsPerName[option.Key.Key]; found { + if options, found := optionsMap[matchBlock]; found { + if _, duplicatesAllowed := fields.AllowedDuplicateOptions[option.Key.Key]; !duplicatesAllowed { + firstDefinedOption := options[0] + errs = append(errs, common.LSPError{ + Range: option.Key.LocationRange, + Err: errors.New(fmt.Sprintf( + "Option '%s' has already been defined on line %d", + option.Key.Key, + firstDefinedOption.Start.Line+1, + )), + }) + } else { + i.AllOptionsPerName[option.Key.Key][matchBlock] = append( + i.AllOptionsPerName[option.Key.Key][matchBlock], + option, + ) + } + } else { + i.AllOptionsPerName[option.Key.Key][matchBlock] = []*ast.SSHDOption{ + option, + } + } + } else { + i.AllOptionsPerName[option.Key.Key] = map[*ast.SSHDMatchBlock]([]*ast.SSHDOption){ + matchBlock: { + option, + }, + } + } + + return errs +} diff --git a/handlers/sshd_config/indexes/indexes.go b/handlers/sshd_config/indexes/indexes.go index 37247c4..4e8db6f 100644 --- a/handlers/sshd_config/indexes/indexes.go +++ b/handlers/sshd_config/indexes/indexes.go @@ -3,10 +3,6 @@ package indexes import ( "config-lsp/common" "config-lsp/handlers/sshd_config/ast" - "config-lsp/handlers/sshd_config/fields" - "errors" - "fmt" - "regexp" ) type ValidPath string @@ -15,13 +11,13 @@ func (v ValidPath) AsURI() string { return "file://" + string(v) } -// SSHIndexIncludeValue Used to store the individual includes +// SSHDIndexIncludeValue Used to store the individual includes // An `Include` statement can have multiple paths, -// each [SSHIndexIncludeValue] represents a single entered path. +// each [SSHDIndexIncludeValue] represents a single entered path. // Note that an entered path can represent multiple real paths, as // the path can contain wildcards. // All true paths are stored in the [Paths] field. -type SSHIndexIncludeValue struct { +type SSHDIndexIncludeValue struct { common.LocationRange Value string @@ -29,142 +25,15 @@ type SSHIndexIncludeValue struct { Paths []ValidPath } -type SSHIndexIncludeLine struct { - Values []*SSHIndexIncludeValue +type SSHDIndexIncludeLine struct { + Values []*SSHDIndexIncludeValue Option *ast.SSHDOption MatchBlock *ast.SSHDMatchBlock } -type SSHIndexes struct { +type SSHDIndexes struct { // This is a map of `Option name` to a list of options with that name - AllOptionsPerName map[*ast.SSHDMatchBlock](map[string]([]*ast.SSHDOption)) + AllOptionsPerName map[string](map[*ast.SSHDMatchBlock]([]*ast.SSHDOption)) - Includes map[uint32]*SSHIndexIncludeLine -} - -func (i SSHIndexes) GetAllOptionsForName(name string) map[*ast.SSHDMatchBlock][]*ast.SSHDOption { - allOptions := make(map[*ast.SSHDMatchBlock][]*ast.SSHDOption) - - for matchBlock, options := range i.AllOptionsPerName { - if opts, found := options[name]; found { - allOptions[matchBlock] = opts - } - } - - return allOptions -} - -var whitespacePattern = regexp.MustCompile(`\S+`) - -func CreateIndexes(config ast.SSHDConfig) (*SSHIndexes, []common.LSPError) { - errs := make([]common.LSPError, 0) - indexes := &SSHIndexes{ - AllOptionsPerName: make(map[*ast.SSHDMatchBlock](map[string]([]*ast.SSHDOption))), - Includes: make(map[uint32]*SSHIndexIncludeLine), - } - - it := config.Options.Iterator() - for it.Next() { - entry := it.Value().(ast.SSHDEntry) - - switch entry.(type) { - case *ast.SSHDOption: - option := entry.(*ast.SSHDOption) - - errs = append(errs, addOption(indexes, option, nil)...) - case *ast.SSHDMatchBlock: - matchBlock := entry.(*ast.SSHDMatchBlock) - - errs = append(errs, addOption(indexes, matchBlock.MatchEntry, matchBlock)...) - - it := matchBlock.Options.Iterator() - for it.Next() { - option := it.Value().(*ast.SSHDOption) - - errs = append(errs, addOption(indexes, option, matchBlock)...) - } - } - } - - // Add Includes - for matchBlock, options := range indexes.GetAllOptionsForName("Include") { - includeOption := options[0] - rawValue := includeOption.OptionValue.Value.Value - pathIndexes := whitespacePattern.FindAllStringIndex(rawValue, -1) - paths := make([]*SSHIndexIncludeValue, 0) - - for _, pathIndex := range pathIndexes { - startIndex := pathIndex[0] - endIndex := pathIndex[1] - - rawPath := rawValue[startIndex:endIndex] - - offset := includeOption.OptionValue.Start.Character - path := SSHIndexIncludeValue{ - LocationRange: common.LocationRange{ - Start: common.Location{ - Line: includeOption.Start.Line, - Character: uint32(startIndex) + offset, - }, - End: common.Location{ - Line: includeOption.Start.Line, - Character: uint32(endIndex) + offset - 1, - }, - }, - Value: rawPath, - Paths: make([]ValidPath, 0), - } - - paths = append(paths, &path) - } - - indexes.Includes[includeOption.Start.Line] = &SSHIndexIncludeLine{ - Values: paths, - Option: includeOption, - MatchBlock: matchBlock, - } - } - - return indexes, errs -} - -func addOption( - i *SSHIndexes, - option *ast.SSHDOption, - matchBlock *ast.SSHDMatchBlock, -) []common.LSPError { - var errs []common.LSPError - - if optionsMap, found := i.AllOptionsPerName[matchBlock]; found { - if options, found := optionsMap[option.Key.Key]; found { - if _, duplicatesAllowed := fields.AllowedDuplicateOptions[option.Key.Key]; !duplicatesAllowed { - firstDefinedOption := options[0] - errs = append(errs, common.LSPError{ - Range: option.Key.LocationRange, - Err: errors.New(fmt.Sprintf( - "Option '%s' has already been defined on line %d", - option.Key.Key, - firstDefinedOption.Start.Line+1, - )), - }) - } else { - i.AllOptionsPerName[matchBlock][option.Key.Key] = append( - i.AllOptionsPerName[matchBlock][option.Key.Key], - option, - ) - } - } else { - i.AllOptionsPerName[matchBlock][option.Key.Key] = []*ast.SSHDOption{ - option, - } - } - } else { - i.AllOptionsPerName[matchBlock] = map[string]([]*ast.SSHDOption){ - option.Key.Key: { - option, - }, - } - } - - return errs + Includes map[uint32]*SSHDIndexIncludeLine } diff --git a/handlers/sshd_config/indexes/indexes_test.go b/handlers/sshd_config/indexes/indexes_test.go index f2f8691..7992ba0 100644 --- a/handlers/sshd_config/indexes/indexes_test.go +++ b/handlers/sshd_config/indexes/indexes_test.go @@ -34,7 +34,7 @@ Match Address 192.168.0.1/24 } firstMatchBlock := config.FindMatchBlock(uint32(6)) - opts := indexes.GetAllOptionsForName("PermitRootLogin") + opts := indexes.AllOptionsPerName["PermitRootLogin"] if !(len(opts) == 2 && len(opts[nil]) == 1 && opts[nil][0].Value.Value == "PermitRootLogin yes" && diff --git a/handlers/sshd_config/shared.go b/handlers/sshd_config/shared.go index 66e133f..aa2d56f 100644 --- a/handlers/sshd_config/shared.go +++ b/handlers/sshd_config/shared.go @@ -9,7 +9,7 @@ import ( type SSHDocument struct { Config *ast.SSHDConfig - Indexes *indexes.SSHIndexes + Indexes *indexes.SSHDIndexes } var DocumentParserMap = map[protocol.DocumentUri]*SSHDocument{} From 9ed983bf81bac7254a40b006fd79ee55f367249c Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Tue, 17 Sep 2024 23:34:39 +0200 Subject: [PATCH 050/133] fix(sshd_config): Rename match_parser -> matchparser --- handlers/sshd_config/analyzer/match.go | 6 ++-- handlers/sshd_config/ast/listener.go | 6 ++-- .../fields/match-parser/error-listener.go | 2 +- .../fields/match-parser/listener.go | 2 +- .../fields/match-parser/match_ast.go | 2 +- .../fields/match-parser/match_fields.go | 2 +- .../sshd_config/fields/match-parser/parser.go | 2 +- .../fields/match-parser/parser_test.go | 2 +- .../sshd_config/handlers/completions_match.go | 34 +++++++++---------- 9 files changed, 29 insertions(+), 29 deletions(-) diff --git a/handlers/sshd_config/analyzer/match.go b/handlers/sshd_config/analyzer/match.go index cf1491e..68d4769 100644 --- a/handlers/sshd_config/analyzer/match.go +++ b/handlers/sshd_config/analyzer/match.go @@ -3,7 +3,7 @@ package analyzer import ( "config-lsp/common" sshdconfig "config-lsp/handlers/sshd_config" - match_parser "config-lsp/handlers/sshd_config/fields/match-parser" + matchparser "config-lsp/handlers/sshd_config/fields/match-parser" "config-lsp/utils" "errors" "fmt" @@ -54,7 +54,7 @@ func analyzeMatchBlocks( } func analyzeMatchValueNegation( - value *match_parser.MatchValue, + value *matchparser.MatchValue, ) []common.LSPError { errs := make([]common.LSPError, 0) @@ -83,7 +83,7 @@ func analyzeMatchValueNegation( } func analyzeMatchValuesContainsPositiveValue( - values *match_parser.MatchValues, + values *matchparser.MatchValues, ) []common.LSPError { if len(values.Values) == 0 { return nil diff --git a/handlers/sshd_config/ast/listener.go b/handlers/sshd_config/ast/listener.go index 27fa37a..aa744d8 100644 --- a/handlers/sshd_config/ast/listener.go +++ b/handlers/sshd_config/ast/listener.go @@ -4,7 +4,7 @@ import ( "config-lsp/common" commonparser "config-lsp/common/parser" "config-lsp/handlers/sshd_config/ast/parser" - match_parser "config-lsp/handlers/sshd_config/fields/match-parser" + matchparser "config-lsp/handlers/sshd_config/fields/match-parser" "strings" "github.com/emirpasic/gods/maps/treemap" @@ -109,10 +109,10 @@ func (s *sshParserListener) ExitEntry(ctx *parser.EntryContext) { if s.sshContext.isKeyAMatchBlock { // Add new match block - var match *match_parser.Match + var match *matchparser.Match if s.sshContext.currentOption.OptionValue != nil { - matchParser := match_parser.NewMatch() + matchParser := matchparser.NewMatch() errors := matchParser.Parse( s.sshContext.currentOption.OptionValue.Value.Raw, location.Start.Line, diff --git a/handlers/sshd_config/fields/match-parser/error-listener.go b/handlers/sshd_config/fields/match-parser/error-listener.go index fd9e4bb..e7264b0 100644 --- a/handlers/sshd_config/fields/match-parser/error-listener.go +++ b/handlers/sshd_config/fields/match-parser/error-listener.go @@ -1,4 +1,4 @@ -package match_parser +package matchparser import ( "config-lsp/common" diff --git a/handlers/sshd_config/fields/match-parser/listener.go b/handlers/sshd_config/fields/match-parser/listener.go index 01f6fb4..ce5e130 100644 --- a/handlers/sshd_config/fields/match-parser/listener.go +++ b/handlers/sshd_config/fields/match-parser/listener.go @@ -1,4 +1,4 @@ -package match_parser +package matchparser import ( "config-lsp/common" diff --git a/handlers/sshd_config/fields/match-parser/match_ast.go b/handlers/sshd_config/fields/match-parser/match_ast.go index 1d80f78..d45105e 100644 --- a/handlers/sshd_config/fields/match-parser/match_ast.go +++ b/handlers/sshd_config/fields/match-parser/match_ast.go @@ -1,4 +1,4 @@ -package match_parser +package matchparser import ( "config-lsp/common" diff --git a/handlers/sshd_config/fields/match-parser/match_fields.go b/handlers/sshd_config/fields/match-parser/match_fields.go index dca690d..3dc12dd 100644 --- a/handlers/sshd_config/fields/match-parser/match_fields.go +++ b/handlers/sshd_config/fields/match-parser/match_fields.go @@ -1,4 +1,4 @@ -package match_parser +package matchparser import "slices" diff --git a/handlers/sshd_config/fields/match-parser/parser.go b/handlers/sshd_config/fields/match-parser/parser.go index abbc2f7..d81f73c 100644 --- a/handlers/sshd_config/fields/match-parser/parser.go +++ b/handlers/sshd_config/fields/match-parser/parser.go @@ -1,4 +1,4 @@ -package match_parser +package matchparser import ( "config-lsp/common" diff --git a/handlers/sshd_config/fields/match-parser/parser_test.go b/handlers/sshd_config/fields/match-parser/parser_test.go index 2dbdb8a..558ce21 100644 --- a/handlers/sshd_config/fields/match-parser/parser_test.go +++ b/handlers/sshd_config/fields/match-parser/parser_test.go @@ -1,4 +1,4 @@ -package match_parser +package matchparser import ( "testing" diff --git a/handlers/sshd_config/handlers/completions_match.go b/handlers/sshd_config/handlers/completions_match.go index 462afa4..773727f 100644 --- a/handlers/sshd_config/handlers/completions_match.go +++ b/handlers/sshd_config/handlers/completions_match.go @@ -3,14 +3,14 @@ package handlers import ( sshdconfig "config-lsp/handlers/sshd_config" "config-lsp/handlers/sshd_config/fields" - match_parser "config-lsp/handlers/sshd_config/fields/match-parser" + matchparser "config-lsp/handlers/sshd_config/fields/match-parser" protocol "github.com/tliron/glsp/protocol_3_16" ) func getMatchCompletions( d *sshdconfig.SSHDocument, - match *match_parser.Match, + match *matchparser.Match, cursor uint32, ) ([]protocol.CompletionItem, error) { if match == nil || len(match.Entries) == 0 { @@ -34,31 +34,31 @@ func getMatchCriteriaCompletions() []protocol.CompletionItem { return []protocol.CompletionItem{ { - Label: string(match_parser.MatchCriteriaTypeUser), + Label: string(matchparser.MatchCriteriaTypeUser), Kind: &kind, }, { - Label: string(match_parser.MatchCriteriaTypeGroup), + Label: string(matchparser.MatchCriteriaTypeGroup), Kind: &kind, }, { - Label: string(match_parser.MatchCriteriaTypeHost), + Label: string(matchparser.MatchCriteriaTypeHost), Kind: &kind, }, { - Label: string(match_parser.MatchCriteriaTypeAddress), + Label: string(matchparser.MatchCriteriaTypeAddress), Kind: &kind, }, { - Label: string(match_parser.MatchCriteriaTypeLocalAddress), + Label: string(matchparser.MatchCriteriaTypeLocalAddress), Kind: &kind, }, { - Label: string(match_parser.MatchCriteriaTypeLocalPort), + Label: string(matchparser.MatchCriteriaTypeLocalPort), Kind: &kind, }, { - Label: string(match_parser.MatchCriteriaTypeRDomain), + Label: string(matchparser.MatchCriteriaTypeRDomain), Kind: &kind, }, } @@ -74,7 +74,7 @@ func getMatchAllKeywordCompletion() protocol.CompletionItem { } func getMatchValueCompletions( - entry *match_parser.MatchEntry, + entry *matchparser.MatchEntry, cursor uint32, ) []protocol.CompletionItem { value := entry.GetValueByCursor(entry.End.Character) @@ -91,19 +91,19 @@ func getMatchValueCompletions( } switch entry.Criteria.Type { - case match_parser.MatchCriteriaTypeUser: + case matchparser.MatchCriteriaTypeUser: return fields.MatchUserField.FetchCompletions(line, relativeCursor) - case match_parser.MatchCriteriaTypeGroup: + case matchparser.MatchCriteriaTypeGroup: return fields.MatchGroupField.FetchCompletions(line, relativeCursor) - case match_parser.MatchCriteriaTypeHost: + case matchparser.MatchCriteriaTypeHost: return fields.MatchHostField.FetchCompletions(line, relativeCursor) - case match_parser.MatchCriteriaTypeAddress: + case matchparser.MatchCriteriaTypeAddress: return fields.MatchAddressField.FetchCompletions(line, relativeCursor) - case match_parser.MatchCriteriaTypeLocalAddress: + case matchparser.MatchCriteriaTypeLocalAddress: return fields.MatchLocalAddressField.FetchCompletions(line, relativeCursor) - case match_parser.MatchCriteriaTypeLocalPort: + case matchparser.MatchCriteriaTypeLocalPort: return fields.MatchLocalPortField.FetchCompletions(line, relativeCursor) - case match_parser.MatchCriteriaTypeRDomain: + case matchparser.MatchCriteriaTypeRDomain: return fields.MatchRDomainField.FetchCompletions(line, relativeCursor) } From 99339f3edd406f6fc2dc41cd74ae5c082fe75561 Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Tue, 17 Sep 2024 23:50:50 +0200 Subject: [PATCH 051/133] chore(sshd_config): Add some documentation --- handlers/sshd_config/README.md | 6 ++++++ handlers/sshd_config/analyzer/README.md | 3 +++ handlers/sshd_config/ast/README.md | 16 ++++++++++++++++ handlers/sshd_config/fields/README.md | 7 +++++++ handlers/sshd_config/handlers/README.md | 5 +++++ handlers/sshd_config/indexes/README.md | 9 +++++++++ handlers/sshd_config/lsp/README.md | 7 +++++++ 7 files changed, 53 insertions(+) create mode 100644 handlers/sshd_config/README.md create mode 100644 handlers/sshd_config/analyzer/README.md create mode 100644 handlers/sshd_config/ast/README.md create mode 100644 handlers/sshd_config/fields/README.md create mode 100644 handlers/sshd_config/handlers/README.md create mode 100644 handlers/sshd_config/indexes/README.md create mode 100644 handlers/sshd_config/lsp/README.md diff --git a/handlers/sshd_config/README.md b/handlers/sshd_config/README.md new file mode 100644 index 0000000..36acfb0 --- /dev/null +++ b/handlers/sshd_config/README.md @@ -0,0 +1,6 @@ +# /sshd_config + +This is the root directory for each of the handlers. +This folder should only contain the antlr grammar file, +shared libraries, variables, etc. and folders for each +logic part. \ No newline at end of file diff --git a/handlers/sshd_config/analyzer/README.md b/handlers/sshd_config/analyzer/README.md new file mode 100644 index 0000000..dfd445c --- /dev/null +++ b/handlers/sshd_config/analyzer/README.md @@ -0,0 +1,3 @@ +# /sshd_config/analyzer + +This folder analyzes the config file and returns errors, warnings, and suggestions. \ No newline at end of file diff --git a/handlers/sshd_config/ast/README.md b/handlers/sshd_config/ast/README.md new file mode 100644 index 0000000..dea10a4 --- /dev/null +++ b/handlers/sshd_config/ast/README.md @@ -0,0 +1,16 @@ +# /sshd_config/ast + +This folder contains the AST (Abstract Syntax Tree) for the handlers. +The AST is defined in a filename that's the same as the handler's name. + +Each AST node must extend the following fields: + +```go +type ASTNode struct { + common.LocationRange + Value commonparser.ParsedString +} +``` + +Each node should use a shared prefix for the node name, +e.g. `SSHDConfig`, `SSDKey` for the `sshd_config` handler. \ No newline at end of file diff --git a/handlers/sshd_config/fields/README.md b/handlers/sshd_config/fields/README.md new file mode 100644 index 0000000..00637d9 --- /dev/null +++ b/handlers/sshd_config/fields/README.md @@ -0,0 +1,7 @@ +# /sshd_config/fields + +This folder contains the glue between the config documentation and +our language server. + +`fields.go` usually contains a list of all the available options / fields +the config file offers. \ No newline at end of file diff --git a/handlers/sshd_config/handlers/README.md b/handlers/sshd_config/handlers/README.md new file mode 100644 index 0000000..1d8e185 --- /dev/null +++ b/handlers/sshd_config/handlers/README.md @@ -0,0 +1,5 @@ +# /sshd_config/handlers + +This folder contains the actual logic for the LSP commands. +Stuff like fetching completions, executing commands, getting hover +definitions, etc. should be done here. \ No newline at end of file diff --git a/handlers/sshd_config/indexes/README.md b/handlers/sshd_config/indexes/README.md new file mode 100644 index 0000000..116a37f --- /dev/null +++ b/handlers/sshd_config/indexes/README.md @@ -0,0 +1,9 @@ +# /sshd_config/indexers + +This folder contains logic for indexing the AST. + +Creating the indexer fulfills two purposes: +* Creating actual indexes +* Validating some logic + +The indexer also validates stuff like checking for duplicate values, etc. \ No newline at end of file diff --git a/handlers/sshd_config/lsp/README.md b/handlers/sshd_config/lsp/README.md new file mode 100644 index 0000000..2aa9542 --- /dev/null +++ b/handlers/sshd_config/lsp/README.md @@ -0,0 +1,7 @@ +# /sshd_config/lsp + +This folder is the glue between our language server and the LSP +clients. +This folder only contains LSP commands. +It only handles very little actual logic, and instead calls +the handlers from `../handlers`. \ No newline at end of file From 942e2477e2bf906bc89b7f4142a6bcc92d066d68 Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Tue, 17 Sep 2024 23:51:09 +0200 Subject: [PATCH 052/133] fix(sshd_config): Rename indexes -> i to avoid ambiguity with package --- handlers/sshd_config/analyzer/analyzer.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/handlers/sshd_config/analyzer/analyzer.go b/handlers/sshd_config/analyzer/analyzer.go index 36944aa..571d548 100644 --- a/handlers/sshd_config/analyzer/analyzer.go +++ b/handlers/sshd_config/analyzer/analyzer.go @@ -18,9 +18,9 @@ func Analyze( return errsToDiagnostics(errors) } - indexes, indexErrors := indexes.CreateIndexes(*d.Config) + i, indexErrors := indexes.CreateIndexes(*d.Config) - d.Indexes = indexes + d.Indexes = i errors = append(errors, indexErrors...) From 06182ddda76863616f7f4e0ea4a29ccb3562fb8b Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Wed, 18 Sep 2024 00:13:43 +0200 Subject: [PATCH 053/133] fix(sshd_config): Bugfixes --- common/lsp.go | 2 +- .../sshd_config/ast/sshd_config_fields.go | 24 +++++++++++++++++ handlers/sshd_config/handlers/completions.go | 27 ++++++++++++++----- .../lsp/text-document-completion.go | 3 +-- 4 files changed, 47 insertions(+), 9 deletions(-) diff --git a/common/lsp.go b/common/lsp.go index eede1be..29c0279 100644 --- a/common/lsp.go +++ b/common/lsp.go @@ -1,5 +1,5 @@ package common func CursorToCharacterIndex(cursor uint32) uint32 { - return max(0, cursor-1) + return max(1, cursor) - 1 } diff --git a/handlers/sshd_config/ast/sshd_config_fields.go b/handlers/sshd_config/ast/sshd_config_fields.go index ce760bd..97cb4b7 100644 --- a/handlers/sshd_config/ast/sshd_config_fields.go +++ b/handlers/sshd_config/ast/sshd_config_fields.go @@ -64,3 +64,27 @@ func (c SSHDConfig) FindOption(line uint32) (*SSHDOption, *SSHDMatchBlock) { return nil, nil } + +func (c SSHDConfig) GetAllOptions() []*SSHDOption { + options := make( + []*SSHDOption, + 0, + // Approximation, this does not need to be exact + c.Options.Size()+10, + ) + + for _, rawEntry := range c.Options.Values() { + switch entry := rawEntry.(type) { + case *SSHDOption: + options = append(options, entry) + case *SSHDMatchBlock: + options = append(options, entry.MatchEntry) + + for _, rawOption := range entry.Options.Values() { + options = append(options, rawOption.(*SSHDOption)) + } + } + } + + return options +} diff --git a/handlers/sshd_config/handlers/completions.go b/handlers/sshd_config/handlers/completions.go index e076030..aafbb99 100644 --- a/handlers/sshd_config/handlers/completions.go +++ b/handlers/sshd_config/handlers/completions.go @@ -18,16 +18,31 @@ func GetRootCompletions( ) ([]protocol.CompletionItem, error) { kind := protocol.CompletionItemKindField - availableOptions := make(map[string]docvalues.DocumentationValue) + availableOptions := make(map[string]docvalues.DocumentationValue, 0) if parentMatchBlock == nil { - availableOptions = fields.Options - } else { - for option := range fields.MatchAllowedOptions { - if opt, found := fields.Options[option]; found { - availableOptions[option] = opt + for key, option := range fields.Options { + if _, found := d.Indexes.AllOptionsPerName[key]; !found { + availableOptions[key] = option } } + } else { + for key := range fields.MatchAllowedOptions { + if option, found := fields.Options[key]; found { + if _, found := d.Indexes.AllOptionsPerName[key]; !found { + availableOptions[key] = option + } + } + } + } + + // Remove all fields that are already present and are not allowed to be duplicated + for _, option := range d.Config.GetAllOptions() { + if _, found := fields.AllowedDuplicateOptions[option.Key.Key]; found { + continue + } + + delete(availableOptions, option.Key.Key) } return utils.MapMapToSlice( diff --git a/handlers/sshd_config/lsp/text-document-completion.go b/handlers/sshd_config/lsp/text-document-completion.go index e91deaf..fa13229 100644 --- a/handlers/sshd_config/lsp/text-document-completion.go +++ b/handlers/sshd_config/lsp/text-document-completion.go @@ -1,7 +1,6 @@ package lsp import ( - "config-lsp/common" sshdconfig "config-lsp/handlers/sshd_config" "config-lsp/handlers/sshd_config/handlers" "regexp" @@ -14,7 +13,7 @@ var isEmptyPattern = regexp.MustCompile(`^\s*$`) func TextDocumentCompletion(context *glsp.Context, params *protocol.CompletionParams) (any, error) { line := params.Position.Line - cursor := common.CursorToCharacterIndex(params.Position.Character) + cursor := params.Position.Character d := sshdconfig.DocumentParserMap[params.TextDocument.URI] From 590786e84410b4e1b31d0b337afcbca9ae73e3a1 Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Wed, 18 Sep 2024 00:17:26 +0200 Subject: [PATCH 054/133] feat(doc-values): Check if value starts with a prefix before suggesting prefix completions --- doc-values/value-prefix.go | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/doc-values/value-prefix.go b/doc-values/value-prefix.go index 80ed331..d0c1e88 100644 --- a/doc-values/value-prefix.go +++ b/doc-values/value-prefix.go @@ -46,14 +46,26 @@ func (v PrefixWithMeaningValue) FetchCompletions(line string, cursor uint32) []p textFormat := protocol.InsertTextFormatPlainText kind := protocol.CompletionItemKindText - prefixCompletions := utils.Map(v.Prefixes, func(prefix Prefix) protocol.CompletionItem { - return protocol.CompletionItem{ - Label: prefix.Prefix, - Detail: &prefix.Meaning, - InsertTextFormat: &textFormat, - Kind: &kind, + // Check if the line starts with a prefix + startsWithPrefix := false + for _, prefix := range v.Prefixes { + if strings.HasPrefix(line, prefix.Prefix) { + startsWithPrefix = true + break } - }) + } + + var prefixCompletions []protocol.CompletionItem + if !startsWithPrefix { + prefixCompletions = utils.Map(v.Prefixes, func(prefix Prefix) protocol.CompletionItem { + return protocol.CompletionItem{ + Label: prefix.Prefix, + Detail: &prefix.Meaning, + InsertTextFormat: &textFormat, + Kind: &kind, + } + }) + } return append(prefixCompletions, v.SubValue.FetchCompletions(line, cursor)...) } From 1a70a5ad573c0db3dd343acb9d9acf65cf44ac21 Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Wed, 18 Sep 2024 20:46:33 +0200 Subject: [PATCH 055/133] fix(aliases): Improve rename when definition entry is not available --- handlers/aliases/handlers/rename.go | 20 ++++++++++++-------- handlers/aliases/lsp/text-document-rename.go | 15 ++++++++++----- 2 files changed, 22 insertions(+), 13 deletions(-) diff --git a/handlers/aliases/handlers/rename.go b/handlers/aliases/handlers/rename.go index 9b1cfab..7a29537 100644 --- a/handlers/aliases/handlers/rename.go +++ b/handlers/aliases/handlers/rename.go @@ -1,7 +1,6 @@ package handlers import ( - "config-lsp/handlers/aliases/ast" "config-lsp/handlers/aliases/indexes" protocol "github.com/tliron/glsp/protocol_3_16" @@ -9,17 +8,22 @@ import ( func RenameAlias( i indexes.AliasesIndexes, - oldEntry *ast.AliasEntry, + oldName string, newName string, ) []protocol.TextEdit { - occurrences := i.UserOccurrences[indexes.NormalizeKey(oldEntry.Key.Value)] + normalizedName := indexes.NormalizeKey(oldName) + definitionEntry := i.Keys[normalizedName] + occurrences := i.UserOccurrences[normalizedName] + changes := make([]protocol.TextEdit, 0, len(occurrences)) - // Own rename - changes = append(changes, protocol.TextEdit{ - Range: oldEntry.Key.Location.ToLSPRange(), - NewText: newName, - }) + if definitionEntry != nil { + // Own rename + changes = append(changes, protocol.TextEdit{ + Range: definitionEntry.Key.Location.ToLSPRange(), + NewText: newName, + }) + } // Other AliasValueUser occurrences for _, value := range occurrences { diff --git a/handlers/aliases/lsp/text-document-rename.go b/handlers/aliases/lsp/text-document-rename.go index be529ed..da53577 100644 --- a/handlers/aliases/lsp/text-document-rename.go +++ b/handlers/aliases/lsp/text-document-rename.go @@ -4,7 +4,6 @@ import ( "config-lsp/handlers/aliases" "config-lsp/handlers/aliases/ast" "config-lsp/handlers/aliases/handlers" - "config-lsp/handlers/aliases/indexes" "github.com/tliron/glsp" protocol "github.com/tliron/glsp/protocol_3_16" @@ -24,7 +23,11 @@ func TextDocumentRename(context *glsp.Context, params *protocol.RenameParams) (* entry := rawEntry.(*ast.AliasEntry) if character >= entry.Key.Location.Start.Character && character <= entry.Key.Location.End.Character { - changes := handlers.RenameAlias(*d.Indexes, entry, params.NewName) + changes := handlers.RenameAlias( + *d.Indexes, + entry.Key.Value, + params.NewName, + ) return &protocol.WorkspaceEdit{ Changes: map[protocol.DocumentUri][]protocol.TextEdit{ @@ -44,9 +47,11 @@ func TextDocumentRename(context *glsp.Context, params *protocol.RenameParams) (* case ast.AliasValueUser: userValue := (*rawValue).(ast.AliasValueUser) - definitionEntry := d.Indexes.Keys[indexes.NormalizeKey(userValue.Value)] - - changes := handlers.RenameAlias(*d.Indexes, definitionEntry, params.NewName) + changes := handlers.RenameAlias( + *d.Indexes, + userValue.Value, + params.NewName, + ) return &protocol.WorkspaceEdit{ Changes: map[protocol.DocumentUri][]protocol.TextEdit{ From ea2e53139324491906c2b521c8927a33c3dc5c08 Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Wed, 18 Sep 2024 21:26:24 +0200 Subject: [PATCH 056/133] test(aliases): Add more rename tests --- handlers/aliases/handlers/rename_test.go | 37 +++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/handlers/aliases/handlers/rename_test.go b/handlers/aliases/handlers/rename_test.go index eb6606a..9a07d32 100644 --- a/handlers/aliases/handlers/rename_test.go +++ b/handlers/aliases/handlers/rename_test.go @@ -28,7 +28,7 @@ support: alice, bob t.Fatalf("Expected no errors, but got: %v", errors) } - edits := RenameAlias(i, i.Keys["alice"], "amelie") + edits := RenameAlias(i, "alice", "amelie") if !(len(edits) == 3) { t.Errorf("Expected 2 edits, but got %v", len(edits)) @@ -46,3 +46,38 @@ support: alice, bob t.Errorf("Unexpected edit: %v", edits[2]) } } + +func TestRenameWithoutDefinitionEntry( + t *testing.T, +) { + input := utils.Dedent(` +bob: root +support: root, bob +`) + parser := ast.NewAliasesParser() + errors := parser.Parse(input) + + if len(errors) > 0 { + t.Fatalf("Unexpected errors: %v", errors) + } + + i, errors := indexes.CreateIndexes(parser) + + if len(errors) > 0 { + t.Fatalf("Expected no errors, but got: %v", errors) + } + + edits := RenameAlias(i, "root", "amelie") + + if !(len(edits) == 2) { + t.Errorf("Expected 2 edits, but got %v", len(edits)) + } + + if !(edits[0].Range.Start.Line == 0 && edits[0].Range.Start.Character == 5 && edits[0].Range.End.Line == 0 && edits[0].Range.End.Character == 9) { + t.Errorf("Unexpected edit: %v", edits[0]) + } + + if !(edits[1].Range.Start.Line == 1 && edits[1].Range.Start.Character == 9 && edits[1].Range.End.Line == 1 && edits[1].Range.End.Character == 13) { + t.Errorf("Unexpected edit: %v", edits[1]) + } +} From 31c3d755a2abe6293d694911218126dadb750ec7 Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Sat, 21 Sep 2024 09:34:05 +0200 Subject: [PATCH 057/133] fix: Fix BinarySearchFunc handling --- handlers/aliases/handlers/get-value.go | 12 +- .../fields/match-parser/full_test.go | 74 ++++++++++++ .../fields/match-parser/match_fields.go | 12 +- handlers/sshd_config/handlers/definition.go | 10 +- handlers/sshd_config/handlers/formatting.go | 38 +++++++ .../sshd_config/handlers/formatting_nodes.go | 107 ++++++++++++++++++ .../sshd_config/handlers/formatting_test.go | 62 ++++++++++ .../lsp/text-document-range-formatting.go | 22 ++++ 8 files changed, 320 insertions(+), 17 deletions(-) create mode 100644 handlers/sshd_config/fields/match-parser/full_test.go create mode 100644 handlers/sshd_config/handlers/formatting.go create mode 100644 handlers/sshd_config/handlers/formatting_nodes.go create mode 100644 handlers/sshd_config/handlers/formatting_test.go create mode 100644 handlers/sshd_config/lsp/text-document-range-formatting.go diff --git a/handlers/aliases/handlers/get-value.go b/handlers/aliases/handlers/get-value.go index 3e2347b..d9c0d12 100644 --- a/handlers/aliases/handlers/get-value.go +++ b/handlers/aliases/handlers/get-value.go @@ -16,15 +16,15 @@ func GetValueAtCursor( index, found := slices.BinarySearchFunc( entry.Values.Values, cursor, - func(entry ast.AliasValueInterface, pos uint32) int { - value := entry.GetAliasValue() + func(current ast.AliasValueInterface, target uint32) int { + value := current.GetAliasValue() - if pos > value.Location.End.Character { - return -1 + if target < value.Location.Start.Character { + return 1 } - if pos < value.Location.Start.Character { - return 1 + if target > value.Location.End.Character { + return -1 } return 0 diff --git a/handlers/sshd_config/fields/match-parser/full_test.go b/handlers/sshd_config/fields/match-parser/full_test.go new file mode 100644 index 0000000..33121ad --- /dev/null +++ b/handlers/sshd_config/fields/match-parser/full_test.go @@ -0,0 +1,74 @@ +package matchparser + +import ( + "testing" +) + +func TestFullExample( + t *testing.T, +) { + input := "User alice,adam Address 192.168.1.1 Host *.example.com" + match := NewMatch() + errs := match.Parse(input, 0, 0) + + if len(errs) > 0 { + t.Fatalf("Failed to parse match: %v", errs) + } + + entry := match.GetEntryByCursor(0) + if !(entry == match.Entries[0]) { + t.Errorf("Expected entry at 0 to be %v, but got %v", match.Entries[0], entry) + } + + entry = match.GetEntryByCursor(5) + if !(entry == match.Entries[0]) { + t.Errorf("Expected entry at 5 to be %v, but got %v", match.Entries[0], entry) + } + + entry = match.GetEntryByCursor(13) + if !(entry == match.Entries[0]) { + t.Errorf("Expected entry at 13 to be %v, but got %v", match.Entries[1], entry) + } + + entry = match.GetEntryByCursor(16) + if !(entry == match.Entries[1]) { + t.Errorf("Expected entry at 16 to be %v, but got %v", match.Entries[1], entry) + } + + entry = match.GetEntryByCursor(24) + if !(entry == match.Entries[1]) { + t.Errorf("Expected entry at 24 to be %v, but got %v", match.Entries[2], entry) + } + + entry = match.GetEntryByCursor(36) + if !(entry == match.Entries[2]) { + t.Errorf("Expected entry at 36 to be %v, but got %v", match.Entries[2], entry) + } +} + +func TestGetEntryForIncompleteExample( + t *testing.T, +) { + input := "User " + match := NewMatch() + errs := match.Parse(input, 0, 0) + + if len(errs) > 0 { + t.Fatalf("Failed to parse match: %v", errs) + } + + entry := match.GetEntryByCursor(0) + if !(entry == match.Entries[0]) { + t.Errorf("Expected entry at 0 to be %v, but got %v", match.Entries[0], entry) + } + + entry = match.GetEntryByCursor(4) + if !(entry == match.Entries[0]) { + t.Errorf("Expected entry at 4 to be %v, but got %v", match.Entries[0], entry) + } + + entry = match.GetEntryByCursor(5) + if !(entry == match.Entries[0]) { + t.Errorf("Expected entry at 5 to be %v, but got %v", match.Entries[0], entry) + } +} diff --git a/handlers/sshd_config/fields/match-parser/match_fields.go b/handlers/sshd_config/fields/match-parser/match_fields.go index 3dc12dd..f9c2d4a 100644 --- a/handlers/sshd_config/fields/match-parser/match_fields.go +++ b/handlers/sshd_config/fields/match-parser/match_fields.go @@ -6,12 +6,12 @@ func (m Match) GetEntryByCursor(cursor uint32) *MatchEntry { index, found := slices.BinarySearchFunc( m.Entries, cursor, - func(entry *MatchEntry, cursor uint32) int { - if cursor < entry.Start.Character { + func(current *MatchEntry, target uint32) int { + if target < current.Start.Character { return 1 } - if cursor > entry.End.Character { + if target > current.End.Character { return -1 } @@ -40,12 +40,12 @@ func (e MatchEntry) GetValueByCursor(cursor uint32) *MatchValue { index, found := slices.BinarySearchFunc( e.Values.Values, cursor, - func(value *MatchValue, cursor uint32) int { - if cursor < value.Start.Character { + func(current *MatchValue, target uint32) int { + if target < current.Start.Character { return 1 } - if cursor > value.End.Character { + if target > current.End.Character { return -1 } diff --git a/handlers/sshd_config/handlers/definition.go b/handlers/sshd_config/handlers/definition.go index 50de94d..bec6955 100644 --- a/handlers/sshd_config/handlers/definition.go +++ b/handlers/sshd_config/handlers/definition.go @@ -16,13 +16,13 @@ func GetIncludeOptionLocation( index, found := slices.BinarySearchFunc( include.Values, cursor, - func(i *indexes.SSHDIndexIncludeValue, cursor uint32) int { - if cursor < i.Start.Character { - return -1 + func(current *indexes.SSHDIndexIncludeValue, target uint32) int { + if target < current.Start.Character { + return 1 } - if cursor > i.End.Character { - return 1 + if target > current.End.Character { + return -1 } return 0 diff --git a/handlers/sshd_config/handlers/formatting.go b/handlers/sshd_config/handlers/formatting.go new file mode 100644 index 0000000..4fcc2de --- /dev/null +++ b/handlers/sshd_config/handlers/formatting.go @@ -0,0 +1,38 @@ +package handlers + +import ( + sshdconfig "config-lsp/handlers/sshd_config" + "config-lsp/handlers/sshd_config/ast" + + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func FormatDocument( + d *sshdconfig.SSHDocument, + textRange protocol.Range, + options protocol.FormattingOptions, +) ([]protocol.TextEdit, error) { + edits := make([]protocol.TextEdit, 0) + + it := d.Config.Options.Iterator() + for it.Next() { + line := it.Key().(uint32) + entry := it.Value().(ast.SSHDEntry) + + if !(line >= textRange.Start.Line && line <= textRange.End.Line) { + continue + } + + switch entry.(type) { + case *ast.SSHDOption: + option := entry.(*ast.SSHDOption) + edits = append(edits, formatSSHDOption(option, options)...) + case *ast.SSHDMatchBlock: + matchBlock := entry.(*ast.SSHDMatchBlock) + + edits = formatSSHDMatchBlock(matchBlock, options) + } + } + + return edits, nil +} diff --git a/handlers/sshd_config/handlers/formatting_nodes.go b/handlers/sshd_config/handlers/formatting_nodes.go new file mode 100644 index 0000000..da84cba --- /dev/null +++ b/handlers/sshd_config/handlers/formatting_nodes.go @@ -0,0 +1,107 @@ +package handlers + +import ( + "config-lsp/common/formatting" + "config-lsp/handlers/sshd_config/ast" + matchparser "config-lsp/handlers/sshd_config/fields/match-parser" + "config-lsp/utils" + "fmt" + "strings" + + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func formatSSHDOption( + option *ast.SSHDOption, + options protocol.FormattingOptions, +) []protocol.TextEdit { + template := formatting.FormatTemplate( + "%s/t%s", + ) + + var key string + + if option.Key != nil { + key = option.Key.Key + } else { + key = "" + } + + var value string + + if option.OptionValue != nil { + value = option.OptionValue.Value.Raw + } else { + value = "" + } + + return []protocol.TextEdit{ + { + Range: option.ToLSPRange(), + NewText: template.Format(options, key, value), + }, + } +} + +func formatSSHDMatchBlock( + matchBlock *ast.SSHDMatchBlock, + options protocol.FormattingOptions, +) []protocol.TextEdit { + edits := make([]protocol.TextEdit, 0) + + template := formatting.FormatTemplate( + "%s/t%s", + ) + edits = append(edits, protocol.TextEdit{ + Range: matchBlock.ToLSPRange(), + NewText: template.Format(options, matchBlock.MatchEntry.Key.Key, formatMatchToString(matchBlock.MatchValue, options)), + }) + + it := matchBlock.Options.Iterator() + for it.Next() { + option := it.Value().(*ast.SSHDOption) + + edits = append(edits, formatSSHDOption(option, options)...) + } + + return edits +} + +func formatMatchToString( + match *matchparser.Match, + options protocol.FormattingOptions, +) string { + entriesAsStrings := utils.Map( + match.Entries, + func(entry *matchparser.MatchEntry) string { + return formatMatchEntryToString(entry, options) + }, + ) + + return strings.Join(entriesAsStrings, " ") +} + +func formatMatchEntryToString( + entry *matchparser.MatchEntry, + options protocol.FormattingOptions, +) string { + return fmt.Sprintf( + "%s %s", + string(entry.Criteria.Type), + formatMatchValuesToString(entry.Values, options), + ) +} + +func formatMatchValuesToString( + values *matchparser.MatchValues, + options protocol.FormattingOptions, +) string { + valuesAsStrings := utils.Map( + values.Values, + func(value *matchparser.MatchValue) string { + return value.Value.Raw + }, + ) + + return strings.Join(valuesAsStrings, ",") +} diff --git a/handlers/sshd_config/handlers/formatting_test.go b/handlers/sshd_config/handlers/formatting_test.go new file mode 100644 index 0000000..3a15d89 --- /dev/null +++ b/handlers/sshd_config/handlers/formatting_test.go @@ -0,0 +1,62 @@ +package handlers + +import ( + sshdconfig "config-lsp/handlers/sshd_config" + "config-lsp/handlers/sshd_config/ast" + "config-lsp/handlers/sshd_config/indexes" + "config-lsp/utils" + "testing" + + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func TestSimpleFormattingExampleWorks( + t *testing.T, +) { + input := utils.Dedent(` + PermitRootLogin yes +a b +`) + config := ast.NewSSHConfig() + errors := config.Parse(input) + + if len(errors) > 0 { + t.Fatalf("Failed to parse SSHD config: %v", errors) + } + + i, errors := indexes.CreateIndexes(*config) + + if len(errors) > 0 { + t.Fatalf("Failed to create indexes: %v", errors) + } + + d := sshdconfig.SSHDocument{ + Config: config, + Indexes: i, + } + + options := protocol.FormattingOptions{} + options["insertSpaces"] = true + options["tabSize"] = float64(4) + + edits, err := FormatDocument( + &d, + protocol.Range{ + Start: protocol.Position{ + Line: 0, + Character: protocol.UInteger(0), + }, + End: protocol.Position{ + Line: 1, + Character: protocol.UInteger(0), + }, + }, + options, + ) + + if err != nil { + t.Errorf("Failed to format document: %v", err) + } + + _ = edits +} diff --git a/handlers/sshd_config/lsp/text-document-range-formatting.go b/handlers/sshd_config/lsp/text-document-range-formatting.go new file mode 100644 index 0000000..aeb76f8 --- /dev/null +++ b/handlers/sshd_config/lsp/text-document-range-formatting.go @@ -0,0 +1,22 @@ +package lsp + +import ( + sshdconfig "config-lsp/handlers/sshd_config" + "config-lsp/handlers/sshd_config/handlers" + + "github.com/tliron/glsp" + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func TextDocumentRangeFormatting( + context *glsp.Context, + params *protocol.DocumentRangeFormattingParams, +) ([]protocol.TextEdit, error) { + d := sshdconfig.DocumentParserMap[params.TextDocument.URI] + + return handlers.FormatDocument( + d, + params.Range, + params.Options, + ) +} From 3ffd1f4c4b1383967c48a58e52978b19476692cd Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Sat, 21 Sep 2024 09:35:17 +0200 Subject: [PATCH 058/133] feat: Add missing FormatTemplate --- common/formatting/formatting.go | 69 ++++++++++++++++++++++++ common/formatting/formatting_test.go | 81 ++++++++++++++++++++++++++++ 2 files changed, 150 insertions(+) create mode 100644 common/formatting/formatting.go create mode 100644 common/formatting/formatting_test.go diff --git a/common/formatting/formatting.go b/common/formatting/formatting.go new file mode 100644 index 0000000..3400aaf --- /dev/null +++ b/common/formatting/formatting.go @@ -0,0 +1,69 @@ +package formatting + +import ( + "fmt" + "strings" + + protocol "github.com/tliron/glsp/protocol_3_16" +) + +type FormatTemplate string + +func (f FormatTemplate) Format( + options protocol.FormattingOptions, + a ...any, +) string { + trimTrailingSpace := true + + if shouldTrim, found := options["trimTrailingWhitespace"]; found { + trimTrailingSpace = shouldTrim.(bool) + } + + value := "" + value = fmt.Sprintf( + string( + f.replace("/t", getTab(options)), + ), + a..., + ) + + if trimTrailingSpace { + value = strings.TrimRight(value, " ") + value = strings.TrimRight(value, "\t") + } + + return value +} + +func (f FormatTemplate) replace(format string, replacement string) FormatTemplate { + value := string(f) + currentIndex := 0 + + for { + position := strings.Index(value[currentIndex:], format) + + if position == -1 { + break + } + + position = position + currentIndex + currentIndex = position + + if position == 0 || value[position-1] != '\\' { + value = value[:position] + replacement + value[position+len(format):] + } + } + + return FormatTemplate(value) +} + +func getTab(options protocol.FormattingOptions) string { + tabSize := options["tabSize"].(float64) + insertSpace := options["insertSpaces"].(bool) + + if insertSpace { + return strings.Repeat(" ", int(tabSize)) + } else { + return "\t" + } +} diff --git a/common/formatting/formatting_test.go b/common/formatting/formatting_test.go new file mode 100644 index 0000000..290d41f --- /dev/null +++ b/common/formatting/formatting_test.go @@ -0,0 +1,81 @@ +package formatting + +import ( + "testing" + + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func TestSimpleTabExampleWithTabOptions( + t *testing.T, +) { + template := FormatTemplate("%s/t%s") + + options := protocol.FormattingOptions{ + "tabSize": float64(4), + "insertSpaces": false, + } + + result := template.Format(options, "PermitRootLogin", "yes") + expected := "PermitRootLogin\tyes" + + if result != expected { + t.Errorf("Expected %q but got %q", expected, result) + } +} + +func TestSimpleTabExampleWithSpaceOptions( + t *testing.T, +) { + template := FormatTemplate("%s/t%s") + + options := protocol.FormattingOptions{ + "tabSize": float64(4), + "insertSpaces": true, + } + + result := template.Format(options, "PermitRootLogin", "yes") + expected := "PermitRootLogin yes" + + if result != expected { + t.Errorf("Expected %q but got %q", expected, result) + } +} + +func TestSimpleExampleWhiteSpaceAtEndShouldTrim( + t *testing.T, +) { + template := FormatTemplate("%s/t%s") + + options := protocol.FormattingOptions{ + "tabSize": float64(4), + "insertSpaces": false, + "trimTrailingWhitespace": true, + } + + result := template.Format(options, "PermitRootLogin", "yes ") + expected := "PermitRootLogin\tyes" + + if result != expected { + t.Errorf("Expected %q but got %q", expected, result) + } +} + +func TestSimpleExampleWhiteSpaceAtEndShouldNOTTrim( + t *testing.T, +) { + template := FormatTemplate("%s/t%s") + + options := protocol.FormattingOptions{ + "tabSize": float64(4), + "insertSpaces": false, + "trimTrailingWhitespace": false, + } + + result := template.Format(options, "PermitRootLogin", "yes ") + expected := "PermitRootLogin\tyes " + + if result != expected { + t.Errorf("Expected %q but got %q", expected, result) + } +} From ad8311d0c6aa4db386a752330b87ba7ade283d64 Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Sat, 21 Sep 2024 09:36:44 +0200 Subject: [PATCH 059/133] feat: Add root handler for text document range formatting --- .../text-document-range-formatting.go | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 root-handler/text-document-range-formatting.go diff --git a/root-handler/text-document-range-formatting.go b/root-handler/text-document-range-formatting.go new file mode 100644 index 0000000..6b4cff6 --- /dev/null +++ b/root-handler/text-document-range-formatting.go @@ -0,0 +1,39 @@ +package roothandler + +import ( + sshdconfig "config-lsp/handlers/sshd_config/lsp" + "github.com/tliron/glsp" + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func TextDocumentRangeFormattingFunc( + context *glsp.Context, + params *protocol.DocumentRangeFormattingParams, +) ([]protocol.TextEdit, error) { + language := rootHandler.GetLanguageForDocument(params.TextDocument.URI) + + if language == nil { + showParseError( + context, + params.TextDocument.URI, + undetectableError, + ) + + return nil, undetectableError.Err + } + + switch *language { + case LanguageHosts: + return nil, nil + case LanguageSSHDConfig: + return sshdconfig.TextDocumentRangeFormatting(context, params) + case LanguageFstab: + return nil, nil + case LanguageWireguard: + return nil, nil + case LanguageAliases: + return nil, nil + } + + panic("root-handler/TextDocumentRangeFormattingFunc: unexpected language" + *language) +} From 41472c1a58f6fd9654e88d19d48fda0f649e30d3 Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Sat, 21 Sep 2024 11:49:09 +0200 Subject: [PATCH 060/133] refactor(sshd_config): Migrating cursor to index position --- handlers/sshd_config/ast/parser_test.go | 18 +++++++++--------- .../fields/match-parser/match_fields.go | 13 ++++++++----- .../fields/match-parser/parser_test.go | 12 ++++++------ handlers/sshd_config/handlers/completions.go | 10 +++++++--- .../sshd_config/handlers/completions_match.go | 12 ++++++++---- handlers/sshd_config/handlers/definition.go | 17 ++++++++--------- .../sshd_config/handlers/formatting_nodes.go | 9 +++------ handlers/sshd_config/handlers/hover.go | 14 +++++++++----- handlers/sshd_config/indexes/handlers.go | 2 +- handlers/sshd_config/indexes/indexes_test.go | 4 ++-- .../lsp/text-document-completion.go | 7 ++++--- .../lsp/text-document-definition.go | 10 ++++++---- .../sshd_config/lsp/text-document-hover.go | 5 +++-- 13 files changed, 74 insertions(+), 59 deletions(-) diff --git a/handlers/sshd_config/ast/parser_test.go b/handlers/sshd_config/ast/parser_test.go index 46c6338..2a024d5 100644 --- a/handlers/sshd_config/ast/parser_test.go +++ b/handlers/sshd_config/ast/parser_test.go @@ -31,13 +31,13 @@ PasswordAuthentication yes firstEntry.LocationRange.Start.Line == 0 && firstEntry.LocationRange.End.Line == 0 && firstEntry.LocationRange.Start.Character == 0 && - firstEntry.LocationRange.End.Character == 17 && + firstEntry.LocationRange.End.Character == 18 && firstEntry.Key.Value.Value == "PermitRootLogin" && firstEntry.Key.LocationRange.Start.Character == 0 && - firstEntry.Key.LocationRange.End.Character == 14 && + firstEntry.Key.LocationRange.End.Character == 15 && firstEntry.OptionValue.Value.Value == "no" && firstEntry.OptionValue.LocationRange.Start.Character == 16 && - firstEntry.OptionValue.LocationRange.End.Character == 17) { + firstEntry.OptionValue.LocationRange.End.Character == 18) { t.Errorf("Expected first entry to be PermitRootLogin no, but got: %v", firstEntry) } @@ -48,13 +48,13 @@ PasswordAuthentication yes secondEntry.LocationRange.Start.Line == 1 && secondEntry.LocationRange.End.Line == 1 && secondEntry.LocationRange.Start.Character == 0 && - secondEntry.LocationRange.End.Character == 25 && + secondEntry.LocationRange.End.Character == 26 && secondEntry.Key.Value.Value == "PasswordAuthentication" && secondEntry.Key.LocationRange.Start.Character == 0 && - secondEntry.Key.LocationRange.End.Character == 21 && + secondEntry.Key.LocationRange.End.Character == 22 && secondEntry.OptionValue.Value.Value == "yes" && secondEntry.OptionValue.LocationRange.Start.Character == 23 && - secondEntry.OptionValue.LocationRange.End.Character == 25) { + secondEntry.OptionValue.LocationRange.End.Character == 26) { t.Errorf("Expected second entry to be PasswordAuthentication yes, but got: %v", secondEntry) } } @@ -92,7 +92,7 @@ Match Address 192.168.0.1 t.Errorf("Expected second entry to be 'Match Address 192.168.0.1', but got: %v", secondEntry.MatchEntry.Value) } - if !(secondEntry.Start.Line == 2 && secondEntry.Start.Character == 0 && secondEntry.End.Line == 3 && secondEntry.End.Character == 26) { + if !(secondEntry.Start.Line == 2 && secondEntry.Start.Character == 0 && secondEntry.End.Line == 3 && secondEntry.End.Character == 27) { t.Errorf("Expected second entry's location to be 2:0-3:25, but got: %v", secondEntry.LocationRange) } @@ -240,14 +240,14 @@ Match Address 192.168.0.2 t.Errorf("Expected match option to be 'Match User lena', but got: %v, %v", matchOption, matchBlock) } - if !(matchOption.Start.Line == 2 && matchOption.End.Line == 2 && matchOption.Start.Character == 0 && matchOption.End.Character == 14) { + if !(matchOption.Start.Line == 2 && matchOption.End.Line == 2 && matchOption.Start.Character == 0 && matchOption.End.Character == 15) { t.Errorf("Expected match option to be at 2:0-14, but got: %v", matchOption.LocationRange) } if !(matchBlock.Start.Line == 2 && matchBlock.Start.Character == 0 && matchBlock.End.Line == 4 && - matchBlock.End.Character == 20) { + matchBlock.End.Character == 21) { t.Errorf("Expected match block to be at 2:0-4:20, but got: %v", matchBlock.LocationRange) } } diff --git a/handlers/sshd_config/fields/match-parser/match_fields.go b/handlers/sshd_config/fields/match-parser/match_fields.go index f9c2d4a..547986d 100644 --- a/handlers/sshd_config/fields/match-parser/match_fields.go +++ b/handlers/sshd_config/fields/match-parser/match_fields.go @@ -1,17 +1,20 @@ package matchparser -import "slices" +import ( + "config-lsp/common" + "slices" +) -func (m Match) GetEntryByCursor(cursor uint32) *MatchEntry { +func (m Match) GetEntryByCursor(cursor common.CursorPosition) *MatchEntry { index, found := slices.BinarySearchFunc( m.Entries, cursor, - func(current *MatchEntry, target uint32) int { - if target < current.Start.Character { + func(current *MatchEntry, target common.CursorPosition) int { + if current.Start.IsAfterCursorPosition(target) { return 1 } - if target > current.End.Character { + if current.End.IsBeforeCursorPosition(target) { return -1 } diff --git a/handlers/sshd_config/fields/match-parser/parser_test.go b/handlers/sshd_config/fields/match-parser/parser_test.go index 558ce21..e35647f 100644 --- a/handlers/sshd_config/fields/match-parser/parser_test.go +++ b/handlers/sshd_config/fields/match-parser/parser_test.go @@ -25,15 +25,15 @@ func TestComplexExample( t.Fatalf("Expected User, but got %v", match.Entries[0]) } - if !(match.Entries[0].Values.Values[0].Value.Value == "root" && match.Entries[0].Values.Values[0].Start.Character == 5+offset && match.Entries[0].Values.Values[0].End.Character == 8+offset && match.Entries[0].Start.Character == 0+offset && match.Entries[0].End.Character == 20+offset) { + if !(match.Entries[0].Values.Values[0].Value.Value == "root" && match.Entries[0].Values.Values[0].Start.Character == 5+offset && match.Entries[0].Values.Values[0].End.Character == 8+offset+1 && match.Entries[0].Start.Character == 0+offset && match.Entries[0].End.Character == 20+offset+1) { t.Errorf("Expected root, but got %v", match.Entries[0].Values.Values[0]) } - if !(match.Entries[0].Values.Values[1].Value.Value == "admin" && match.Entries[0].Values.Values[1].Start.Character == 10+offset && match.Entries[0].Values.Values[1].End.Character == 14+offset) { + if !(match.Entries[0].Values.Values[1].Value.Value == "admin" && match.Entries[0].Values.Values[1].Start.Character == 10+offset && match.Entries[0].Values.Values[1].End.Character == 14+offset+1) { t.Errorf("Expected admin, but got %v", match.Entries[0].Values.Values[1]) } - if !(match.Entries[0].Values.Values[2].Value.Value == "alice" && match.Entries[0].Values.Values[2].Start.Character == 16+offset && match.Entries[0].Values.Values[2].End.Character == 20+offset) { + if !(match.Entries[0].Values.Values[2].Value.Value == "alice" && match.Entries[0].Values.Values[2].Start.Character == 16+offset && match.Entries[0].Values.Values[2].End.Character == 20+offset+1) { t.Errorf("Expected alice, but got %v", match.Entries[0].Values.Values[2]) } @@ -41,11 +41,11 @@ func TestComplexExample( t.Errorf("Expected Address, but got %v", match.Entries[1]) } - if !(match.Entries[1].Values.Values[0].Value.Value == "*" && match.Entries[1].Values.Values[0].Start.Character == 30+offset && match.Entries[1].Values.Values[0].End.Character == 30+offset) { + if !(match.Entries[1].Values.Values[0].Value.Value == "*" && match.Entries[1].Values.Values[0].Start.Character == 30+offset && match.Entries[1].Values.Values[0].End.Character == 30+offset+1) { t.Errorf("Expected *, but got %v", match.Entries[1].Values.Values[0]) } - if !(match.Entries[1].Values.Values[1].Value.Value == "!192.168.0.1" && match.Entries[1].Values.Values[1].Start.Character == 32+offset && match.Entries[1].Values.Values[1].End.Character == 43+offset) { + if !(match.Entries[1].Values.Values[1].Value.Value == "!192.168.0.1" && match.Entries[1].Values.Values[1].Start.Character == 32+offset && match.Entries[1].Values.Values[1].End.Character == 43+offset+1) { t.Errorf("Expected !192.168.0.1, but got %v", match.Entries[1].Values.Values[1]) } } @@ -103,7 +103,7 @@ func TestIncompleteBetweenEntriesExample( t.Errorf("Expected 3 values, but got %v", len(match.Entries[0].Values.Values)) } - if !(match.Entries[0].Start.Character == 0 && match.Entries[0].End.Character == 20) { + if !(match.Entries[0].Start.Character == 0 && match.Entries[0].End.Character == 21) { t.Errorf("Expected 0-20, but got %v", match.Entries[0]) } } diff --git a/handlers/sshd_config/handlers/completions.go b/handlers/sshd_config/handlers/completions.go index aafbb99..bd1c7e6 100644 --- a/handlers/sshd_config/handlers/completions.go +++ b/handlers/sshd_config/handlers/completions.go @@ -71,7 +71,7 @@ func GetOptionCompletions( d *sshdconfig.SSHDocument, entry *ast.SSHDOption, matchBlock *ast.SSHDMatchBlock, - cursor uint32, + cursor common.CursorPosition, ) ([]protocol.CompletionItem, error) { option, found := fields.Options[entry.Key.Key] @@ -82,8 +82,8 @@ func GetOptionCompletions( if entry.Key.Key == "Match" { return getMatchCompletions( d, + cursor, matchBlock.MatchValue, - cursor-matchBlock.MatchEntry.Start.Character, ) } @@ -92,8 +92,12 @@ func GetOptionCompletions( } line := entry.OptionValue.Value.Raw + // NEW: docvalues index return option.FetchCompletions( line, - common.CursorToCharacterIndex(cursor-entry.OptionValue.Start.Character), + common.DeprecatedImprovedCursorToIndex( + entry.OptionValue.Start.GetRelativeCursorPosition(cursor), + line, + ), ), nil } diff --git a/handlers/sshd_config/handlers/completions_match.go b/handlers/sshd_config/handlers/completions_match.go index 773727f..17a8900 100644 --- a/handlers/sshd_config/handlers/completions_match.go +++ b/handlers/sshd_config/handlers/completions_match.go @@ -1,6 +1,7 @@ package handlers import ( + "config-lsp/common" sshdconfig "config-lsp/handlers/sshd_config" "config-lsp/handlers/sshd_config/fields" matchparser "config-lsp/handlers/sshd_config/fields/match-parser" @@ -10,8 +11,8 @@ import ( func getMatchCompletions( d *sshdconfig.SSHDocument, + cursor common.CursorPosition, match *matchparser.Match, - cursor uint32, ) ([]protocol.CompletionItem, error) { if match == nil || len(match.Entries) == 0 { completions := getMatchCriteriaCompletions() @@ -22,7 +23,7 @@ func getMatchCompletions( entry := match.GetEntryByCursor(cursor) - if entry == nil || entry.Criteria.IsCursorBetween(cursor) { + if entry == nil || entry.Criteria.ContainsCursorPosition(cursor) { return getMatchCriteriaCompletions(), nil } @@ -75,7 +76,7 @@ func getMatchAllKeywordCompletion() protocol.CompletionItem { func getMatchValueCompletions( entry *matchparser.MatchEntry, - cursor uint32, + cursor common.CursorPosition, ) []protocol.CompletionItem { value := entry.GetValueByCursor(entry.End.Character) @@ -84,7 +85,10 @@ func getMatchValueCompletions( if value != nil { line = value.Value.Raw - relativeCursor = cursor - value.Start.Character + relativeCursor = common.DeprecatedImprovedCursorToIndex( + value.Start.GetRelativeCursorPosition(cursor), + line, + ) } else { line = "" relativeCursor = 0 diff --git a/handlers/sshd_config/handlers/definition.go b/handlers/sshd_config/handlers/definition.go index bec6955..02cf5de 100644 --- a/handlers/sshd_config/handlers/definition.go +++ b/handlers/sshd_config/handlers/definition.go @@ -1,9 +1,9 @@ package handlers import ( + "config-lsp/common" "config-lsp/handlers/sshd_config/indexes" "config-lsp/utils" - "fmt" "slices" protocol "github.com/tliron/glsp/protocol_3_16" @@ -11,17 +11,17 @@ import ( func GetIncludeOptionLocation( include *indexes.SSHDIndexIncludeLine, - cursor uint32, + index common.IndexPosition, ) []protocol.Location { - index, found := slices.BinarySearchFunc( + foundIndex, found := slices.BinarySearchFunc( include.Values, - cursor, - func(current *indexes.SSHDIndexIncludeValue, target uint32) int { - if target < current.Start.Character { + index, + func(current *indexes.SSHDIndexIncludeValue, target common.IndexPosition) int { + if current.Start.IsAfterIndexPosition(target) { return 1 } - if target > current.End.Character { + if current.End.IsBeforeIndexPosition(target) { return -1 } @@ -33,8 +33,7 @@ func GetIncludeOptionLocation( return nil } - path := include.Values[index] - println("paths", fmt.Sprintf("%v", path.Paths)) + path := include.Values[foundIndex] return utils.Map( path.Paths, diff --git a/handlers/sshd_config/handlers/formatting_nodes.go b/handlers/sshd_config/handlers/formatting_nodes.go index da84cba..4045b36 100644 --- a/handlers/sshd_config/handlers/formatting_nodes.go +++ b/handlers/sshd_config/handlers/formatting_nodes.go @@ -54,7 +54,7 @@ func formatSSHDMatchBlock( ) edits = append(edits, protocol.TextEdit{ Range: matchBlock.ToLSPRange(), - NewText: template.Format(options, matchBlock.MatchEntry.Key.Key, formatMatchToString(matchBlock.MatchValue, options)), + NewText: template.Format(options, matchBlock.MatchEntry.Key.Key, formatMatchToString(matchBlock.MatchValue)), }) it := matchBlock.Options.Iterator() @@ -69,12 +69,11 @@ func formatSSHDMatchBlock( func formatMatchToString( match *matchparser.Match, - options protocol.FormattingOptions, ) string { entriesAsStrings := utils.Map( match.Entries, func(entry *matchparser.MatchEntry) string { - return formatMatchEntryToString(entry, options) + return formatMatchEntryToString(entry) }, ) @@ -83,18 +82,16 @@ func formatMatchToString( func formatMatchEntryToString( entry *matchparser.MatchEntry, - options protocol.FormattingOptions, ) string { return fmt.Sprintf( "%s %s", string(entry.Criteria.Type), - formatMatchValuesToString(entry.Values, options), + formatMatchValuesToString(entry.Values), ) } func formatMatchValuesToString( values *matchparser.MatchValues, - options protocol.FormattingOptions, ) string { valuesAsStrings := utils.Map( values.Values, diff --git a/handlers/sshd_config/handlers/hover.go b/handlers/sshd_config/handlers/hover.go index f8ad890..8e41121 100644 --- a/handlers/sshd_config/handlers/hover.go +++ b/handlers/sshd_config/handlers/hover.go @@ -1,6 +1,7 @@ package handlers import ( + "config-lsp/common" docvalues "config-lsp/doc-values" "config-lsp/handlers/sshd_config/ast" "config-lsp/handlers/sshd_config/fields" @@ -13,7 +14,7 @@ func GetHoverInfoForOption( option *ast.SSHDOption, matchBlock *ast.SSHDMatchBlock, line uint32, - cursor uint32, + index common.IndexPosition, ) (*protocol.Hover, error) { var docValue *docvalues.DocumentationValue @@ -28,7 +29,7 @@ func GetHoverInfoForOption( } } - if cursor >= option.Key.Start.Character && cursor <= option.Key.End.Character { + if option.Key.ContainsIndexPosition(index) { if docValue != nil { contents := []string{ "## " + option.Key.Key, @@ -52,9 +53,12 @@ func GetHoverInfoForOption( } } - if option.OptionValue != nil && cursor >= option.OptionValue.Start.Character && cursor <= option.OptionValue.End.Character { - relativeCursor := cursor - option.OptionValue.Start.Character - contents := docValue.FetchHoverInfo(option.OptionValue.Value.Raw, relativeCursor) + if option.OptionValue != nil && option.OptionValue.ContainsIndexPosition(index) { + line := option.OptionValue.Value.Raw + contents := docValue.FetchHoverInfo( + line, + uint32(option.OptionValue.Start.GetRelativeIndexPosition(index)), + ) return &protocol.Hover{ Contents: strings.Join(contents, "\n"), diff --git a/handlers/sshd_config/indexes/handlers.go b/handlers/sshd_config/indexes/handlers.go index 371a200..533825c 100644 --- a/handlers/sshd_config/indexes/handlers.go +++ b/handlers/sshd_config/indexes/handlers.go @@ -63,7 +63,7 @@ func CreateIndexes(config ast.SSHDConfig) (*SSHDIndexes, []common.LSPError) { }, End: common.Location{ Line: includeOption.Start.Line, - Character: uint32(endIndex) + offset - 1, + Character: uint32(endIndex) + offset, }, }, Value: rawPath, diff --git a/handlers/sshd_config/indexes/indexes_test.go b/handlers/sshd_config/indexes/indexes_test.go index 7992ba0..cc4be38 100644 --- a/handlers/sshd_config/indexes/indexes_test.go +++ b/handlers/sshd_config/indexes/indexes_test.go @@ -79,7 +79,7 @@ Include /etc/ssh/sshd_config.d/*.conf hello_world indexes.Includes[1].Values[0].Start.Line == 1 && indexes.Includes[1].Values[0].End.Line == 1 && indexes.Includes[1].Values[0].Start.Character == 8 && - indexes.Includes[1].Values[0].End.Character == 36) { + indexes.Includes[1].Values[0].End.Character == 37) { t.Errorf("Expected '/etc/ssh/sshd_config.d/*.conf' on line 1, but got %v on line %v", indexes.Includes[1].Values[0].Value, indexes.Includes[1].Values[0].Start.Line) } @@ -87,7 +87,7 @@ Include /etc/ssh/sshd_config.d/*.conf hello_world indexes.Includes[1].Values[1].Start.Line == 1 && indexes.Includes[1].Values[1].End.Line == 1 && indexes.Includes[1].Values[1].Start.Character == 38 && - indexes.Includes[1].Values[1].End.Character == 48) { + indexes.Includes[1].Values[1].End.Character == 49) { t.Errorf("Expected 'hello_world' on line 1, but got %v on line %v", indexes.Includes[1].Values[1].Value, indexes.Includes[1].Values[1].Start.Line) } } diff --git a/handlers/sshd_config/lsp/text-document-completion.go b/handlers/sshd_config/lsp/text-document-completion.go index fa13229..24e592a 100644 --- a/handlers/sshd_config/lsp/text-document-completion.go +++ b/handlers/sshd_config/lsp/text-document-completion.go @@ -1,6 +1,7 @@ package lsp import ( + "config-lsp/common" sshdconfig "config-lsp/handlers/sshd_config" "config-lsp/handlers/sshd_config/handlers" "regexp" @@ -13,7 +14,7 @@ var isEmptyPattern = regexp.MustCompile(`^\s*$`) func TextDocumentCompletion(context *glsp.Context, params *protocol.CompletionParams) (any, error) { line := params.Position.Line - cursor := params.Position.Character + cursor := common.LSPCharacterAsCursorPosition(params.Position.Character) d := sshdconfig.DocumentParserMap[params.TextDocument.URI] @@ -26,7 +27,7 @@ func TextDocumentCompletion(context *glsp.Context, params *protocol.CompletionPa if entry == nil || entry.Separator == nil || entry.Key == nil || - cursor <= entry.Key.End.Character { + entry.Key.Start.IsAfterCursorPosition(cursor) { return handlers.GetRootCompletions( d, @@ -36,7 +37,7 @@ func TextDocumentCompletion(context *glsp.Context, params *protocol.CompletionPa ) } - if entry.Separator != nil && cursor >= entry.Separator.End.Character { + if entry.Separator != nil && entry.Separator.End.IsBeforeCursorPosition(cursor) { return handlers.GetOptionCompletions( d, entry, diff --git a/handlers/sshd_config/lsp/text-document-definition.go b/handlers/sshd_config/lsp/text-document-definition.go index 627c400..118f46c 100644 --- a/handlers/sshd_config/lsp/text-document-definition.go +++ b/handlers/sshd_config/lsp/text-document-definition.go @@ -1,6 +1,7 @@ package lsp import ( + "config-lsp/common" sshdconfig "config-lsp/handlers/sshd_config" "config-lsp/handlers/sshd_config/handlers" @@ -10,13 +11,14 @@ import ( func TextDocumentDefinition(context *glsp.Context, params *protocol.DefinitionParams) ([]protocol.Location, error) { d := sshdconfig.DocumentParserMap[params.TextDocument.URI] - cursor := params.Position.Character + index := common.LSPCharacterAsIndexPosition(params.Position.Character) line := params.Position.Line if include, found := d.Indexes.Includes[line]; found { - relativeCursor := cursor - include.Option.LocationRange.Start.Character - - return handlers.GetIncludeOptionLocation(include, relativeCursor), nil + return handlers.GetIncludeOptionLocation( + include, + index, + ), nil } return nil, nil diff --git a/handlers/sshd_config/lsp/text-document-hover.go b/handlers/sshd_config/lsp/text-document-hover.go index 1782116..93bfd81 100644 --- a/handlers/sshd_config/lsp/text-document-hover.go +++ b/handlers/sshd_config/lsp/text-document-hover.go @@ -1,6 +1,7 @@ package lsp import ( + "config-lsp/common" sshdconfig "config-lsp/handlers/sshd_config" "config-lsp/handlers/sshd_config/handlers" @@ -13,7 +14,7 @@ func TextDocumentHover( params *protocol.HoverParams, ) (*protocol.Hover, error) { line := params.Position.Line - cursor := params.Position.Character + index := common.LSPCharacterAsIndexPosition(params.Position.Character) d := sshdconfig.DocumentParserMap[params.TextDocument.URI] @@ -28,6 +29,6 @@ func TextDocumentHover( option, matchBlock, line, - cursor, + index, ) } From 3cff613620556d8527e0f62d918501eebaaedf3f Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Sat, 21 Sep 2024 13:30:45 +0200 Subject: [PATCH 061/133] refactor(sshd_config): Migrating cursor to index position --- handlers/sshd_config/ast/parser_test.go | 16 +++++++++ .../fields/match-parser/full_test.go | 19 +++++----- .../fields/match-parser/match_fields.go | 36 ++++++++----------- handlers/sshd_config/handlers/completions.go | 4 ++- .../sshd_config/handlers/completions_match.go | 9 ++--- handlers/sshd_config/handlers/definition.go | 8 ++--- handlers/sshd_config/handlers/hover.go | 4 +-- .../lsp/text-document-completion.go | 4 +-- 8 files changed, 56 insertions(+), 44 deletions(-) diff --git a/handlers/sshd_config/ast/parser_test.go b/handlers/sshd_config/ast/parser_test.go index 2a024d5..b309380 100644 --- a/handlers/sshd_config/ast/parser_test.go +++ b/handlers/sshd_config/ast/parser_test.go @@ -303,6 +303,22 @@ Sample } +func TestIncompleteExample( + t *testing.T, +) { + input := utils.Dedent(` +MACs +`) + p := NewSSHConfig() + errors := p.Parse(input) + + if len(errors) != 0 { + t.Fatalf("Expected no errors, got %v", errors) + } + + println(p) +} + func TestComplexExample( t *testing.T, ) { diff --git a/handlers/sshd_config/fields/match-parser/full_test.go b/handlers/sshd_config/fields/match-parser/full_test.go index 33121ad..4f37c87 100644 --- a/handlers/sshd_config/fields/match-parser/full_test.go +++ b/handlers/sshd_config/fields/match-parser/full_test.go @@ -1,6 +1,7 @@ package matchparser import ( + "config-lsp/common" "testing" ) @@ -15,32 +16,32 @@ func TestFullExample( t.Fatalf("Failed to parse match: %v", errs) } - entry := match.GetEntryByCursor(0) + entry := match.GetEntryAtPosition(common.LSPCharacterAsCursorPosition(0)) if !(entry == match.Entries[0]) { t.Errorf("Expected entry at 0 to be %v, but got %v", match.Entries[0], entry) } - entry = match.GetEntryByCursor(5) + entry = match.GetEntryAtPosition(common.LSPCharacterAsCursorPosition(5)) if !(entry == match.Entries[0]) { t.Errorf("Expected entry at 5 to be %v, but got %v", match.Entries[0], entry) } - entry = match.GetEntryByCursor(13) + entry = match.GetEntryAtPosition(common.LSPCharacterAsCursorPosition(13)) if !(entry == match.Entries[0]) { t.Errorf("Expected entry at 13 to be %v, but got %v", match.Entries[1], entry) } - entry = match.GetEntryByCursor(16) + entry = match.GetEntryAtPosition(common.LSPCharacterAsCursorPosition(16)) if !(entry == match.Entries[1]) { t.Errorf("Expected entry at 16 to be %v, but got %v", match.Entries[1], entry) } - entry = match.GetEntryByCursor(24) + entry = match.GetEntryAtPosition(common.LSPCharacterAsCursorPosition(24)) if !(entry == match.Entries[1]) { t.Errorf("Expected entry at 24 to be %v, but got %v", match.Entries[2], entry) } - entry = match.GetEntryByCursor(36) + entry = match.GetEntryAtPosition(common.LSPCharacterAsCursorPosition(36)) if !(entry == match.Entries[2]) { t.Errorf("Expected entry at 36 to be %v, but got %v", match.Entries[2], entry) } @@ -57,17 +58,17 @@ func TestGetEntryForIncompleteExample( t.Fatalf("Failed to parse match: %v", errs) } - entry := match.GetEntryByCursor(0) + entry := match.GetEntryAtPosition(common.LSPCharacterAsCursorPosition(0)) if !(entry == match.Entries[0]) { t.Errorf("Expected entry at 0 to be %v, but got %v", match.Entries[0], entry) } - entry = match.GetEntryByCursor(4) + entry = match.GetEntryAtPosition(common.LSPCharacterAsCursorPosition(4)) if !(entry == match.Entries[0]) { t.Errorf("Expected entry at 4 to be %v, but got %v", match.Entries[0], entry) } - entry = match.GetEntryByCursor(5) + entry = match.GetEntryAtPosition(common.LSPCharacterAsCursorPosition(5)) if !(entry == match.Entries[0]) { t.Errorf("Expected entry at 5 to be %v, but got %v", match.Entries[0], entry) } diff --git a/handlers/sshd_config/fields/match-parser/match_fields.go b/handlers/sshd_config/fields/match-parser/match_fields.go index 547986d..ab30390 100644 --- a/handlers/sshd_config/fields/match-parser/match_fields.go +++ b/handlers/sshd_config/fields/match-parser/match_fields.go @@ -5,17 +5,17 @@ import ( "slices" ) -func (m Match) GetEntryByCursor(cursor common.CursorPosition) *MatchEntry { +func (m Match) GetEntryAtPosition(position common.Position) *MatchEntry { index, found := slices.BinarySearchFunc( m.Entries, - cursor, - func(current *MatchEntry, target common.CursorPosition) int { - if current.Start.IsAfterCursorPosition(target) { - return 1 + position, + func(current *MatchEntry, target common.Position) int { + if current.IsPositionAfterEnd(target) { + return -1 } - if current.End.IsBeforeCursorPosition(target) { - return -1 + if current.IsPositionBeforeStart(target) { + return 1 } return 0 @@ -31,25 +31,21 @@ func (m Match) GetEntryByCursor(cursor common.CursorPosition) *MatchEntry { return entry } -func (c MatchCriteria) IsCursorBetween(cursor uint32) bool { - return cursor >= c.Start.Character && cursor <= c.End.Character -} - -func (e MatchEntry) GetValueByCursor(cursor uint32) *MatchValue { +func (e MatchEntry) GetValueAtPosition(position common.Position) *MatchValue { if e.Values == nil { return nil } index, found := slices.BinarySearchFunc( e.Values.Values, - cursor, - func(current *MatchValue, target uint32) int { - if target < current.Start.Character { - return 1 + position, + func(current *MatchValue, target common.Position) int { + if current.IsPositionAfterEnd(target) { + return -1 } - if target > current.End.Character { - return -1 + if current.IsPositionBeforeStart(target) { + return 1 } return 0 @@ -64,7 +60,3 @@ func (e MatchEntry) GetValueByCursor(cursor uint32) *MatchValue { return value } - -func (v MatchValues) IsCursorBetween(cursor uint32) bool { - return cursor >= v.Start.Character && cursor <= v.End.Character -} diff --git a/handlers/sshd_config/handlers/completions.go b/handlers/sshd_config/handlers/completions.go index bd1c7e6..8314f3c 100644 --- a/handlers/sshd_config/handlers/completions.go +++ b/handlers/sshd_config/handlers/completions.go @@ -91,13 +91,15 @@ func GetOptionCompletions( return option.FetchCompletions("", 0), nil } + // Hello wo|rld line := entry.OptionValue.Value.Raw // NEW: docvalues index return option.FetchCompletions( line, common.DeprecatedImprovedCursorToIndex( - entry.OptionValue.Start.GetRelativeCursorPosition(cursor), + cursor, line, + entry.OptionValue.Start.Character, ), ), nil } diff --git a/handlers/sshd_config/handlers/completions_match.go b/handlers/sshd_config/handlers/completions_match.go index 17a8900..4c4707b 100644 --- a/handlers/sshd_config/handlers/completions_match.go +++ b/handlers/sshd_config/handlers/completions_match.go @@ -21,9 +21,9 @@ func getMatchCompletions( return completions, nil } - entry := match.GetEntryByCursor(cursor) + entry := match.GetEntryAtPosition(cursor) - if entry == nil || entry.Criteria.ContainsCursorPosition(cursor) { + if entry == nil || entry.Criteria.ContainsPosition(cursor) { return getMatchCriteriaCompletions(), nil } @@ -78,7 +78,7 @@ func getMatchValueCompletions( entry *matchparser.MatchEntry, cursor common.CursorPosition, ) []protocol.CompletionItem { - value := entry.GetValueByCursor(entry.End.Character) + value := entry.GetValueAtPosition(cursor) var line string var relativeCursor uint32 @@ -86,8 +86,9 @@ func getMatchValueCompletions( if value != nil { line = value.Value.Raw relativeCursor = common.DeprecatedImprovedCursorToIndex( - value.Start.GetRelativeCursorPosition(cursor), + cursor, line, + value.Start.Character, ) } else { line = "" diff --git a/handlers/sshd_config/handlers/definition.go b/handlers/sshd_config/handlers/definition.go index 02cf5de..ad064ea 100644 --- a/handlers/sshd_config/handlers/definition.go +++ b/handlers/sshd_config/handlers/definition.go @@ -17,12 +17,12 @@ func GetIncludeOptionLocation( include.Values, index, func(current *indexes.SSHDIndexIncludeValue, target common.IndexPosition) int { - if current.Start.IsAfterIndexPosition(target) { - return 1 + if current.IsPositionAfterEnd(target) { + return -1 } - if current.End.IsBeforeIndexPosition(target) { - return -1 + if current.IsPositionBeforeStart(target) { + return 1 } return 0 diff --git a/handlers/sshd_config/handlers/hover.go b/handlers/sshd_config/handlers/hover.go index 8e41121..0a56632 100644 --- a/handlers/sshd_config/handlers/hover.go +++ b/handlers/sshd_config/handlers/hover.go @@ -29,7 +29,7 @@ func GetHoverInfoForOption( } } - if option.Key.ContainsIndexPosition(index) { + if option.Key.ContainsPosition(index) { if docValue != nil { contents := []string{ "## " + option.Key.Key, @@ -53,7 +53,7 @@ func GetHoverInfoForOption( } } - if option.OptionValue != nil && option.OptionValue.ContainsIndexPosition(index) { + if option.OptionValue != nil && option.OptionValue.ContainsPosition(index) { line := option.OptionValue.Value.Raw contents := docValue.FetchHoverInfo( line, diff --git a/handlers/sshd_config/lsp/text-document-completion.go b/handlers/sshd_config/lsp/text-document-completion.go index 24e592a..d779ba2 100644 --- a/handlers/sshd_config/lsp/text-document-completion.go +++ b/handlers/sshd_config/lsp/text-document-completion.go @@ -27,7 +27,7 @@ func TextDocumentCompletion(context *glsp.Context, params *protocol.CompletionPa if entry == nil || entry.Separator == nil || entry.Key == nil || - entry.Key.Start.IsAfterCursorPosition(cursor) { + entry.Key.IsPositionBeforeEnd(cursor) { return handlers.GetRootCompletions( d, @@ -37,7 +37,7 @@ func TextDocumentCompletion(context *glsp.Context, params *protocol.CompletionPa ) } - if entry.Separator != nil && entry.Separator.End.IsBeforeCursorPosition(cursor) { + if entry.Separator != nil && entry.OptionValue.IsPositionAfterStart(cursor) { return handlers.GetOptionCompletions( d, entry, From ff08c3c5b1d9f8586b606d6d7e38b534a9d8b030 Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Sat, 21 Sep 2024 13:30:56 +0200 Subject: [PATCH 062/133] refactor(aliases): Migrating cursor to index position --- handlers/aliases/ast/parser_test.go | 4 ++-- handlers/aliases/handlers/completions.go | 18 +++++------------- handlers/aliases/handlers/get-value.go | 19 ++++++++++--------- handlers/aliases/handlers/signature_help.go | 8 +++++--- .../aliases/lsp/text-document-completion.go | 9 +++++---- .../aliases/lsp/text-document-definition.go | 7 ++++--- handlers/aliases/lsp/text-document-hover.go | 9 +++++---- .../lsp/text-document-prepare-rename.go | 9 +++++---- handlers/aliases/lsp/text-document-rename.go | 9 +++++---- .../lsp/text-document-signature-help.go | 10 +++++----- 10 files changed, 51 insertions(+), 51 deletions(-) diff --git a/handlers/aliases/ast/parser_test.go b/handlers/aliases/ast/parser_test.go index 17351ea..9ad9165 100644 --- a/handlers/aliases/ast/parser_test.go +++ b/handlers/aliases/ast/parser_test.go @@ -105,11 +105,11 @@ luke: :include:/etc/other_aliases t.Fatalf("Expected path to be '/etc/other_aliases', got %v", includeValue.Path.Path) } - if !(includeValue.Location.Start.Character == 6 && includeValue.Location.End.Character == 32) { + if !(includeValue.Location.Start.Character == 6 && includeValue.Location.End.Character == 33) { t.Fatalf("Expected location to be 6-33, got %v-%v", includeValue.Location.Start.Character, includeValue.Location.End.Character) } - if !(includeValue.Path.Location.Start.Character == 15 && includeValue.Path.Location.End.Character == 32) { + if !(includeValue.Path.Location.Start.Character == 15 && includeValue.Path.Location.End.Character == 33) { t.Fatalf("Expected path location to be 15-33, got %v-%v", includeValue.Path.Location.Start.Character, includeValue.Path.Location.End.Character) } } diff --git a/handlers/aliases/handlers/completions.go b/handlers/aliases/handlers/completions.go index 246c219..b7d43a7 100644 --- a/handlers/aliases/handlers/completions.go +++ b/handlers/aliases/handlers/completions.go @@ -1,6 +1,7 @@ package handlers import ( + "config-lsp/common" "config-lsp/handlers/aliases/analyzer" "config-lsp/handlers/aliases/ast" "config-lsp/handlers/aliases/fetchers" @@ -38,7 +39,7 @@ func GetAliasesCompletions( } func GetCompletionsForEntry( - cursor uint32, + cursor common.CursorPosition, entry *ast.AliasEntry, i *indexes.AliasesIndexes, ) ([]protocol.CompletionItem, error) { @@ -48,8 +49,7 @@ func GetCompletionsForEntry( return completions, nil } - value := GetValueAtCursor(cursor, entry) - relativeCursor := cursor - entry.Key.Location.Start.Character + value := GetValueAtPosition(cursor, entry) excludedUsers := getUsersFromEntry(entry) @@ -61,8 +61,6 @@ func GetCompletionsForEntry( completions = append(completions, getUserCompletions( i, excludedUsers, - "", - 0, )...) return completions, nil @@ -70,21 +68,17 @@ func GetCompletionsForEntry( switch (*value).(type) { case ast.AliasValueUser: - userValue := (*value).(ast.AliasValueUser) - return getUserCompletions( i, excludedUsers, - userValue.Value, - relativeCursor, ), nil case ast.AliasValueError: errorValue := (*value).(ast.AliasValueError) isAtErrorCode := errorValue.Code == nil && - relativeCursor >= errorValue.Location.Start.Character && + errorValue.Location.IsPositionAfterStart(cursor) && (errorValue.Message == nil || - relativeCursor <= errorValue.Message.Location.Start.Character) + errorValue.Message.Location.IsPositionBeforeEnd(cursor)) if isAtErrorCode { kind := protocol.CompletionItemKindValue @@ -160,8 +154,6 @@ func getErrorCompletion() protocol.CompletionItem { func getUserCompletions( i *indexes.AliasesIndexes, excluded map[string]struct{}, - line string, - cursor uint32, ) []protocol.CompletionItem { users := fetchers.GetAvailableUserValues(i) diff --git a/handlers/aliases/handlers/get-value.go b/handlers/aliases/handlers/get-value.go index d9c0d12..ce6219b 100644 --- a/handlers/aliases/handlers/get-value.go +++ b/handlers/aliases/handlers/get-value.go @@ -1,12 +1,13 @@ package handlers import ( + "config-lsp/common" "config-lsp/handlers/aliases/ast" "slices" ) -func GetValueAtCursor( - cursor uint32, +func GetValueAtPosition( + position common.Position, entry *ast.AliasEntry, ) *ast.AliasValueInterface { if entry.Values == nil || len(entry.Values.Values) == 0 { @@ -15,16 +16,16 @@ func GetValueAtCursor( index, found := slices.BinarySearchFunc( entry.Values.Values, - cursor, - func(current ast.AliasValueInterface, target uint32) int { - value := current.GetAliasValue() + position, + func(rawCurrent ast.AliasValueInterface, target common.Position) int { + current := rawCurrent.GetAliasValue() - if target < value.Location.Start.Character { - return 1 + if current.Location.IsPositionAfterEnd(target) { + return -1 } - if target > value.Location.End.Character { - return -1 + if current.Location.IsPositionBeforeStart(target) { + return 1 } return 0 diff --git a/handlers/aliases/handlers/signature_help.go b/handlers/aliases/handlers/signature_help.go index 7da7f06..b85bf73 100644 --- a/handlers/aliases/handlers/signature_help.go +++ b/handlers/aliases/handlers/signature_help.go @@ -1,6 +1,7 @@ package handlers import ( + "config-lsp/common" "config-lsp/handlers/aliases/ast" "strings" @@ -125,8 +126,8 @@ func GetAllValuesSignatureHelp() *protocol.SignatureHelp { } func GetValueSignatureHelp( + cursor common.CursorPosition, value ast.AliasValueInterface, - cursor uint32, ) *protocol.SignatureHelp { switch value.(type) { case ast.AliasValueUser: @@ -166,7 +167,8 @@ func GetValueSignatureHelp( }, } case ast.AliasValueEmail: - isBeforeAtSymbol := cursor <= uint32(strings.Index(value.GetAliasValue().Value, "@")) + indexPosition := common.LSPCharacterAsIndexPosition(uint32(strings.Index(value.GetAliasValue().Value, "@"))) + isBeforeAtSymbol := cursor.IsBeforeIndexPosition(indexPosition) var index uint32 @@ -269,7 +271,7 @@ func GetValueSignatureHelp( errorValue := value.(ast.AliasValueError) var index uint32 - if errorValue.Code == nil || cursor <= errorValue.Code.Location.End.Character { + if errorValue.Code == nil || errorValue.Code.Location.IsPositionBeforeEnd(cursor) { index = 1 } else { index = 2 diff --git a/handlers/aliases/lsp/text-document-completion.go b/handlers/aliases/lsp/text-document-completion.go index 0240c8f..1d5d429 100644 --- a/handlers/aliases/lsp/text-document-completion.go +++ b/handlers/aliases/lsp/text-document-completion.go @@ -1,6 +1,7 @@ package lsp import ( + "config-lsp/common" "config-lsp/handlers/aliases" "config-lsp/handlers/aliases/ast" "config-lsp/handlers/aliases/handlers" @@ -11,7 +12,7 @@ import ( func TextDocumentCompletion(context *glsp.Context, params *protocol.CompletionParams) (any, error) { d := aliases.DocumentParserMap[params.TextDocument.URI] - cursor := params.Position.Character + cursor := common.LSPCharacterAsCursorPosition(params.Position.Character) line := params.Position.Line if _, found := d.Parser.CommentLines[line]; found { @@ -31,15 +32,15 @@ func TextDocumentCompletion(context *glsp.Context, params *protocol.CompletionPa return handlers.GetAliasesCompletions(d.Indexes), nil } - if cursor >= entry.Key.Location.Start.Character && cursor <= entry.Key.Location.End.Character { + if entry.Key.Location.ContainsPosition(cursor) { return handlers.GetAliasesCompletions(d.Indexes), nil } - if entry.Separator == nil && cursor > entry.Key.Location.End.Character { + if entry.Separator == nil && entry.Key.Location.IsPositionBeforeEnd(cursor) { return nil, nil } - if cursor > entry.Separator.End.Character { + if entry.Separator.IsPositionBeforeEnd(cursor) { return handlers.GetCompletionsForEntry( cursor, entry, diff --git a/handlers/aliases/lsp/text-document-definition.go b/handlers/aliases/lsp/text-document-definition.go index 4798e16..5976f5d 100644 --- a/handlers/aliases/lsp/text-document-definition.go +++ b/handlers/aliases/lsp/text-document-definition.go @@ -1,6 +1,7 @@ package lsp import ( + "config-lsp/common" "config-lsp/handlers/aliases" "config-lsp/handlers/aliases/ast" "config-lsp/handlers/aliases/handlers" @@ -11,7 +12,7 @@ import ( func TextDocumentDefinition(context *glsp.Context, params *protocol.DefinitionParams) ([]protocol.Location, error) { d := aliases.DocumentParserMap[params.TextDocument.URI] - character := params.Position.Character + index := common.LSPCharacterAsIndexPosition(params.Position.Character) line := params.Position.Line rawEntry, found := d.Parser.Aliases.Get(line) @@ -22,8 +23,8 @@ func TextDocumentDefinition(context *glsp.Context, params *protocol.DefinitionPa entry := rawEntry.(*ast.AliasEntry) - if entry.Values != nil && character >= entry.Values.Location.Start.Character && character <= entry.Values.Location.End.Character { - rawValue := handlers.GetValueAtCursor(character, entry) + if entry.Values != nil && entry.Values.Location.ContainsPosition(index) { + rawValue := handlers.GetValueAtPosition(index, entry) if rawValue == nil { return nil, nil diff --git a/handlers/aliases/lsp/text-document-hover.go b/handlers/aliases/lsp/text-document-hover.go index 51acd2c..a1c97fd 100644 --- a/handlers/aliases/lsp/text-document-hover.go +++ b/handlers/aliases/lsp/text-document-hover.go @@ -1,6 +1,7 @@ package lsp import ( + "config-lsp/common" "config-lsp/handlers/aliases" "config-lsp/handlers/aliases/ast" "config-lsp/handlers/aliases/handlers" @@ -17,7 +18,7 @@ func TextDocumentHover( document := aliases.DocumentParserMap[params.TextDocument.URI] line := params.Position.Line - character := params.Position.Character + index := common.LSPCharacterAsIndexPosition(params.Position.Character) if _, found := document.Parser.CommentLines[line]; found { // Comment @@ -32,7 +33,7 @@ func TextDocumentHover( entry := rawEntry.(*ast.AliasEntry) - if entry.Key != nil && character >= entry.Key.Location.Start.Character && character <= entry.Key.Location.End.Character { + if entry.Key != nil && entry.Key.Location.ContainsPosition(index) { text := handlers.GetAliasHoverInfo(*document.Indexes, *entry) return &protocol.Hover{ @@ -40,8 +41,8 @@ func TextDocumentHover( }, nil } - if entry.Values != nil && character >= entry.Values.Location.Start.Character && character <= entry.Values.Location.End.Character { - value := handlers.GetValueAtCursor(character, entry) + if entry.Values != nil && entry.Values.Location.ContainsPosition(index) { + value := handlers.GetValueAtPosition(index, entry) if value == nil { return nil, nil diff --git a/handlers/aliases/lsp/text-document-prepare-rename.go b/handlers/aliases/lsp/text-document-prepare-rename.go index 2b2d03e..56e2dd1 100644 --- a/handlers/aliases/lsp/text-document-prepare-rename.go +++ b/handlers/aliases/lsp/text-document-prepare-rename.go @@ -1,6 +1,7 @@ package lsp import ( + "config-lsp/common" "config-lsp/handlers/aliases" "config-lsp/handlers/aliases/ast" "config-lsp/handlers/aliases/handlers" @@ -11,7 +12,7 @@ import ( func TextDocumentPrepareRename(context *glsp.Context, params *protocol.PrepareRenameParams) (any, error) { d := aliases.DocumentParserMap[params.TextDocument.URI] - character := params.Position.Character + index := common.LSPCharacterAsIndexPosition(params.Position.Character) line := params.Position.Line rawEntry, found := d.Parser.Aliases.Get(line) @@ -22,12 +23,12 @@ func TextDocumentPrepareRename(context *glsp.Context, params *protocol.PrepareRe entry := rawEntry.(*ast.AliasEntry) - if character >= entry.Key.Location.Start.Character && character <= entry.Key.Location.End.Character { + if entry.Key.Location.ContainsPosition(index) { return entry.Key.Location.ToLSPRange(), nil } - if entry.Values != nil && character >= entry.Values.Location.Start.Character && character <= entry.Values.Location.End.Character { - rawValue := handlers.GetValueAtCursor(character, entry) + if entry.Values != nil && entry.Values.Location.ContainsPosition(index) { + rawValue := handlers.GetValueAtPosition(index, entry) if rawValue == nil { return nil, nil diff --git a/handlers/aliases/lsp/text-document-rename.go b/handlers/aliases/lsp/text-document-rename.go index da53577..d51f092 100644 --- a/handlers/aliases/lsp/text-document-rename.go +++ b/handlers/aliases/lsp/text-document-rename.go @@ -1,6 +1,7 @@ package lsp import ( + "config-lsp/common" "config-lsp/handlers/aliases" "config-lsp/handlers/aliases/ast" "config-lsp/handlers/aliases/handlers" @@ -11,7 +12,7 @@ import ( func TextDocumentRename(context *glsp.Context, params *protocol.RenameParams) (*protocol.WorkspaceEdit, error) { d := aliases.DocumentParserMap[params.TextDocument.URI] - character := params.Position.Character + index := common.LSPCharacterAsIndexPosition(params.Position.Character) line := params.Position.Line rawEntry, found := d.Parser.Aliases.Get(line) @@ -22,7 +23,7 @@ func TextDocumentRename(context *glsp.Context, params *protocol.RenameParams) (* entry := rawEntry.(*ast.AliasEntry) - if character >= entry.Key.Location.Start.Character && character <= entry.Key.Location.End.Character { + if entry.Key.Location.ContainsPosition(index) { changes := handlers.RenameAlias( *d.Indexes, entry.Key.Value, @@ -36,8 +37,8 @@ func TextDocumentRename(context *glsp.Context, params *protocol.RenameParams) (* }, nil } - if entry.Values != nil && character >= entry.Values.Location.Start.Character && character <= entry.Values.Location.End.Character { - rawValue := handlers.GetValueAtCursor(character, entry) + if entry.Values != nil && entry.Values.Location.ContainsPosition(index) { + rawValue := handlers.GetValueAtPosition(index, entry) if rawValue == nil { return nil, nil diff --git a/handlers/aliases/lsp/text-document-signature-help.go b/handlers/aliases/lsp/text-document-signature-help.go index 6408f50..913fe62 100644 --- a/handlers/aliases/lsp/text-document-signature-help.go +++ b/handlers/aliases/lsp/text-document-signature-help.go @@ -14,7 +14,7 @@ func TextDocumentSignatureHelp(context *glsp.Context, params *protocol.Signature document := aliases.DocumentParserMap[params.TextDocument.URI] line := params.Position.Line - character := common.CursorToCharacterIndex(params.Position.Character) + cursor := common.LSPCharacterAsCursorPosition(common.CursorToCharacterIndex(params.Position.Character)) if _, found := document.Parser.CommentLines[line]; found { // Comment @@ -29,12 +29,12 @@ func TextDocumentSignatureHelp(context *glsp.Context, params *protocol.Signature entry := rawEntry.(*ast.AliasEntry) - if entry.Key != nil && character >= entry.Key.Location.Start.Character && character <= entry.Key.Location.End.Character { + if entry.Key != nil && entry.Key.Location.ContainsPosition(cursor) { return handlers.GetRootSignatureHelp(0), nil } - if entry.Values != nil && character >= entry.Values.Location.Start.Character && character <= entry.Values.Location.End.Character { - value := handlers.GetValueAtCursor(character, entry) + if entry.Values != nil && entry.Values.Location.ContainsPosition(cursor) { + value := handlers.GetValueAtPosition(cursor, entry) if value == nil { // For some reason, this does not really work, @@ -46,7 +46,7 @@ func TextDocumentSignatureHelp(context *glsp.Context, params *protocol.Signature return nil, nil } - return handlers.GetValueSignatureHelp(*value, character), nil + return handlers.GetValueSignatureHelp(cursor, *value), nil } return nil, nil From 795ce32e8989e19dfc05556f91f1dad268cb1c67 Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Sat, 21 Sep 2024 14:20:46 +0200 Subject: [PATCH 063/133] refactor(hosts): Migrating cursor to index position --- handlers/hosts/analyzer/handler_test.go | 4 ++-- handlers/hosts/handlers/hover.go | 11 ++++++----- handlers/hosts/lsp/text-document-hover.go | 20 ++++++++++++++------ 3 files changed, 22 insertions(+), 13 deletions(-) diff --git a/handlers/hosts/analyzer/handler_test.go b/handlers/hosts/analyzer/handler_test.go index 4705c95..b7182a2 100644 --- a/handlers/hosts/analyzer/handler_test.go +++ b/handlers/hosts/analyzer/handler_test.go @@ -51,7 +51,7 @@ func TestValidSimpleExampleWorks( t.Errorf("Expected start to be 0, but got %v", entry.Location.Start) } - if !(entry.Location.End.Character == 16) { + if !(entry.Location.End.Character == 17) { t.Errorf("Expected end to be 17, but got %v", entry.Location.End.Character) } @@ -63,7 +63,7 @@ func TestValidSimpleExampleWorks( t.Errorf("Expected IP address start to be 0, but got %v", entry.IPAddress.Location.Start.Character) } - if !(entry.IPAddress.Location.End.Character == 6) { + if !(entry.IPAddress.Location.End.Character == 7) { t.Errorf("Expected IP address end to be 7, but got %v", entry.IPAddress.Location.End.Character) } diff --git a/handlers/hosts/handlers/hover.go b/handlers/hosts/handlers/hover.go index 50cc9cd..52b330b 100644 --- a/handlers/hosts/handlers/hover.go +++ b/handlers/hosts/handlers/hover.go @@ -1,6 +1,7 @@ package handlers import ( + "config-lsp/common" "config-lsp/handlers/hosts" "config-lsp/handlers/hosts/ast" "fmt" @@ -15,21 +16,21 @@ const ( ) func GetHoverTargetInEntry( + index common.IndexPosition, e ast.HostsEntry, - cursor uint32, ) *HoverTarget { - if e.IPAddress != nil && e.IPAddress.Location.ContainsCursorByCharacter(cursor) { + if e.IPAddress != nil && e.IPAddress.Location.ContainsPosition(index) { target := HoverTargetIPAddress return &target } - if e.Hostname != nil && e.Hostname.Location.ContainsCursorByCharacter(cursor) { + if e.Hostname != nil && e.Hostname.Location.ContainsPosition(index) { target := HoverTargetHostname return &target } for _, alias := range e.Aliases { - if alias.Location.ContainsCursorByCharacter(cursor) { + if alias.Location.ContainsPosition(index) { target := HoverTargetAlias return &target } @@ -39,9 +40,9 @@ func GetHoverTargetInEntry( } func GetHoverInfoForHostname( + index common.IndexPosition, d hosts.HostsDocument, hostname ast.HostsHostname, - cursor uint32, ) []string { ipAddress := d.Indexes.Resolver.Entries[hostname.Value] diff --git a/handlers/hosts/lsp/text-document-hover.go b/handlers/hosts/lsp/text-document-hover.go index 53ceb61..ca2530b 100644 --- a/handlers/hosts/lsp/text-document-hover.go +++ b/handlers/hosts/lsp/text-document-hover.go @@ -1,6 +1,7 @@ package lsp import ( + "config-lsp/common" "config-lsp/handlers/hosts" "config-lsp/handlers/hosts/ast" "config-lsp/handlers/hosts/fields" @@ -18,7 +19,7 @@ func TextDocumentHover( document := hosts.DocumentParserMap[params.TextDocument.URI] line := params.Position.Line - character := params.Position.Character + index := common.LSPCharacterAsIndexPosition(params.Position.Character) if _, found := document.Parser.CommentLines[line]; found { // Comment @@ -33,14 +34,15 @@ func TextDocumentHover( } entry := rawEntry.(*ast.HostsEntry) - target := handlers.GetHoverTargetInEntry(*entry, character) + target := handlers.GetHoverTargetInEntry(index, *entry) var hostname *ast.HostsHostname switch *target { case handlers.HoverTargetIPAddress: - relativeCursor := character - entry.IPAddress.Location.Start.Character - hover := fields.IPAddressField.FetchHoverInfo(entry.IPAddress.Value.String(), relativeCursor) + line := entry.IPAddress.Value.String() + relativeCursor := uint32(entry.IPAddress.Location.Start.GetRelativeIndexPosition(index)) + hover := fields.IPAddressField.FetchHoverInfo(line, relativeCursor) return &protocol.Hover{ Contents: hover, @@ -49,7 +51,7 @@ func TextDocumentHover( hostname = entry.Hostname case handlers.HoverTargetAlias: for _, alias := range entry.Aliases { - if character >= alias.Location.Start.Character && character <= alias.Location.End.Character { + if alias.Location.ContainsPosition(index) { hostname = alias break } @@ -76,7 +78,13 @@ func TextDocumentHover( ) contents = append( contents, - handlers.GetHoverInfoForHostname(*document, *hostname, character)..., + []string{ + "", + }..., + ) + contents = append( + contents, + handlers.GetHoverInfoForHostname(index, *document, *hostname)..., ) return &protocol.Hover{ From 91dff8a7a0d15a3d3ca421e98fb97e4b6aae6504 Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Sat, 21 Sep 2024 15:30:05 +0200 Subject: [PATCH 064/133] fix(sshd_config): Improve formatting --- .../sshd_config/fields/match-parser/Match.g4 | 2 +- .../fields/match-parser/parser/Match.interp | 2 +- .../match-parser/parser/match_parser.go | 75 ++++++++++--------- .../sshd_config/handlers/formatting_nodes.go | 15 ++-- 4 files changed, 49 insertions(+), 45 deletions(-) diff --git a/handlers/sshd_config/fields/match-parser/Match.g4 b/handlers/sshd_config/fields/match-parser/Match.g4 index d7b77a4..10aa6eb 100644 --- a/handlers/sshd_config/fields/match-parser/Match.g4 +++ b/handlers/sshd_config/fields/match-parser/Match.g4 @@ -17,7 +17,7 @@ criteria ; values - : value (COMMA value?)* + : value? (COMMA value?)* ; value diff --git a/handlers/sshd_config/fields/match-parser/parser/Match.interp b/handlers/sshd_config/fields/match-parser/parser/Match.interp index 1291067..d188f93 100644 --- a/handlers/sshd_config/fields/match-parser/parser/Match.interp +++ b/handlers/sshd_config/fields/match-parser/parser/Match.interp @@ -34,4 +34,4 @@ value atn: -[4, 1, 10, 50, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 2, 5, 7, 5, 1, 0, 3, 0, 14, 8, 0, 1, 0, 1, 0, 3, 0, 18, 8, 0, 5, 0, 20, 8, 0, 10, 0, 12, 0, 23, 9, 0, 1, 0, 1, 0, 1, 1, 1, 1, 3, 1, 29, 8, 1, 1, 1, 3, 1, 32, 8, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, 1, 4, 1, 4, 3, 4, 41, 8, 4, 5, 4, 43, 8, 4, 10, 4, 12, 4, 46, 9, 4, 1, 5, 1, 5, 1, 5, 0, 0, 6, 0, 2, 4, 6, 8, 10, 0, 1, 1, 0, 1, 7, 50, 0, 13, 1, 0, 0, 0, 2, 26, 1, 0, 0, 0, 4, 33, 1, 0, 0, 0, 6, 35, 1, 0, 0, 0, 8, 37, 1, 0, 0, 0, 10, 47, 1, 0, 0, 0, 12, 14, 3, 2, 1, 0, 13, 12, 1, 0, 0, 0, 13, 14, 1, 0, 0, 0, 14, 21, 1, 0, 0, 0, 15, 17, 5, 10, 0, 0, 16, 18, 3, 2, 1, 0, 17, 16, 1, 0, 0, 0, 17, 18, 1, 0, 0, 0, 18, 20, 1, 0, 0, 0, 19, 15, 1, 0, 0, 0, 20, 23, 1, 0, 0, 0, 21, 19, 1, 0, 0, 0, 21, 22, 1, 0, 0, 0, 22, 24, 1, 0, 0, 0, 23, 21, 1, 0, 0, 0, 24, 25, 5, 0, 0, 1, 25, 1, 1, 0, 0, 0, 26, 28, 3, 6, 3, 0, 27, 29, 3, 4, 2, 0, 28, 27, 1, 0, 0, 0, 28, 29, 1, 0, 0, 0, 29, 31, 1, 0, 0, 0, 30, 32, 3, 8, 4, 0, 31, 30, 1, 0, 0, 0, 31, 32, 1, 0, 0, 0, 32, 3, 1, 0, 0, 0, 33, 34, 5, 10, 0, 0, 34, 5, 1, 0, 0, 0, 35, 36, 7, 0, 0, 0, 36, 7, 1, 0, 0, 0, 37, 44, 3, 10, 5, 0, 38, 40, 5, 8, 0, 0, 39, 41, 3, 10, 5, 0, 40, 39, 1, 0, 0, 0, 40, 41, 1, 0, 0, 0, 41, 43, 1, 0, 0, 0, 42, 38, 1, 0, 0, 0, 43, 46, 1, 0, 0, 0, 44, 42, 1, 0, 0, 0, 44, 45, 1, 0, 0, 0, 45, 9, 1, 0, 0, 0, 46, 44, 1, 0, 0, 0, 47, 48, 5, 9, 0, 0, 48, 11, 1, 0, 0, 0, 7, 13, 17, 21, 28, 31, 40, 44] \ No newline at end of file +[4, 1, 10, 52, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 2, 5, 7, 5, 1, 0, 3, 0, 14, 8, 0, 1, 0, 1, 0, 3, 0, 18, 8, 0, 5, 0, 20, 8, 0, 10, 0, 12, 0, 23, 9, 0, 1, 0, 1, 0, 1, 1, 1, 1, 3, 1, 29, 8, 1, 1, 1, 3, 1, 32, 8, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, 3, 4, 39, 8, 4, 1, 4, 1, 4, 3, 4, 43, 8, 4, 5, 4, 45, 8, 4, 10, 4, 12, 4, 48, 9, 4, 1, 5, 1, 5, 1, 5, 0, 0, 6, 0, 2, 4, 6, 8, 10, 0, 1, 1, 0, 1, 7, 53, 0, 13, 1, 0, 0, 0, 2, 26, 1, 0, 0, 0, 4, 33, 1, 0, 0, 0, 6, 35, 1, 0, 0, 0, 8, 38, 1, 0, 0, 0, 10, 49, 1, 0, 0, 0, 12, 14, 3, 2, 1, 0, 13, 12, 1, 0, 0, 0, 13, 14, 1, 0, 0, 0, 14, 21, 1, 0, 0, 0, 15, 17, 5, 10, 0, 0, 16, 18, 3, 2, 1, 0, 17, 16, 1, 0, 0, 0, 17, 18, 1, 0, 0, 0, 18, 20, 1, 0, 0, 0, 19, 15, 1, 0, 0, 0, 20, 23, 1, 0, 0, 0, 21, 19, 1, 0, 0, 0, 21, 22, 1, 0, 0, 0, 22, 24, 1, 0, 0, 0, 23, 21, 1, 0, 0, 0, 24, 25, 5, 0, 0, 1, 25, 1, 1, 0, 0, 0, 26, 28, 3, 6, 3, 0, 27, 29, 3, 4, 2, 0, 28, 27, 1, 0, 0, 0, 28, 29, 1, 0, 0, 0, 29, 31, 1, 0, 0, 0, 30, 32, 3, 8, 4, 0, 31, 30, 1, 0, 0, 0, 31, 32, 1, 0, 0, 0, 32, 3, 1, 0, 0, 0, 33, 34, 5, 10, 0, 0, 34, 5, 1, 0, 0, 0, 35, 36, 7, 0, 0, 0, 36, 7, 1, 0, 0, 0, 37, 39, 3, 10, 5, 0, 38, 37, 1, 0, 0, 0, 38, 39, 1, 0, 0, 0, 39, 46, 1, 0, 0, 0, 40, 42, 5, 8, 0, 0, 41, 43, 3, 10, 5, 0, 42, 41, 1, 0, 0, 0, 42, 43, 1, 0, 0, 0, 43, 45, 1, 0, 0, 0, 44, 40, 1, 0, 0, 0, 45, 48, 1, 0, 0, 0, 46, 44, 1, 0, 0, 0, 46, 47, 1, 0, 0, 0, 47, 9, 1, 0, 0, 0, 48, 46, 1, 0, 0, 0, 49, 50, 5, 9, 0, 0, 50, 11, 1, 0, 0, 0, 8, 13, 17, 21, 28, 31, 38, 42, 46] \ No newline at end of file diff --git a/handlers/sshd_config/fields/match-parser/parser/match_parser.go b/handlers/sshd_config/fields/match-parser/parser/match_parser.go index 79f54ba..ae15253 100644 --- a/handlers/sshd_config/fields/match-parser/parser/match_parser.go +++ b/handlers/sshd_config/fields/match-parser/parser/match_parser.go @@ -44,26 +44,27 @@ func matchParserInit() { } staticData.PredictionContextCache = antlr.NewPredictionContextCache() staticData.serializedATN = []int32{ - 4, 1, 10, 50, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, + 4, 1, 10, 52, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 2, 5, 7, 5, 1, 0, 3, 0, 14, 8, 0, 1, 0, 1, 0, 3, 0, 18, 8, 0, 5, 0, 20, 8, 0, 10, 0, 12, 0, 23, 9, 0, 1, 0, 1, 0, 1, 1, 1, 1, 3, 1, 29, 8, - 1, 1, 1, 3, 1, 32, 8, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, 1, 4, 1, 4, 3, 4, - 41, 8, 4, 5, 4, 43, 8, 4, 10, 4, 12, 4, 46, 9, 4, 1, 5, 1, 5, 1, 5, 0, - 0, 6, 0, 2, 4, 6, 8, 10, 0, 1, 1, 0, 1, 7, 50, 0, 13, 1, 0, 0, 0, 2, 26, - 1, 0, 0, 0, 4, 33, 1, 0, 0, 0, 6, 35, 1, 0, 0, 0, 8, 37, 1, 0, 0, 0, 10, - 47, 1, 0, 0, 0, 12, 14, 3, 2, 1, 0, 13, 12, 1, 0, 0, 0, 13, 14, 1, 0, 0, - 0, 14, 21, 1, 0, 0, 0, 15, 17, 5, 10, 0, 0, 16, 18, 3, 2, 1, 0, 17, 16, - 1, 0, 0, 0, 17, 18, 1, 0, 0, 0, 18, 20, 1, 0, 0, 0, 19, 15, 1, 0, 0, 0, - 20, 23, 1, 0, 0, 0, 21, 19, 1, 0, 0, 0, 21, 22, 1, 0, 0, 0, 22, 24, 1, - 0, 0, 0, 23, 21, 1, 0, 0, 0, 24, 25, 5, 0, 0, 1, 25, 1, 1, 0, 0, 0, 26, - 28, 3, 6, 3, 0, 27, 29, 3, 4, 2, 0, 28, 27, 1, 0, 0, 0, 28, 29, 1, 0, 0, - 0, 29, 31, 1, 0, 0, 0, 30, 32, 3, 8, 4, 0, 31, 30, 1, 0, 0, 0, 31, 32, - 1, 0, 0, 0, 32, 3, 1, 0, 0, 0, 33, 34, 5, 10, 0, 0, 34, 5, 1, 0, 0, 0, - 35, 36, 7, 0, 0, 0, 36, 7, 1, 0, 0, 0, 37, 44, 3, 10, 5, 0, 38, 40, 5, - 8, 0, 0, 39, 41, 3, 10, 5, 0, 40, 39, 1, 0, 0, 0, 40, 41, 1, 0, 0, 0, 41, - 43, 1, 0, 0, 0, 42, 38, 1, 0, 0, 0, 43, 46, 1, 0, 0, 0, 44, 42, 1, 0, 0, - 0, 44, 45, 1, 0, 0, 0, 45, 9, 1, 0, 0, 0, 46, 44, 1, 0, 0, 0, 47, 48, 5, - 9, 0, 0, 48, 11, 1, 0, 0, 0, 7, 13, 17, 21, 28, 31, 40, 44, + 1, 1, 1, 3, 1, 32, 8, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, 3, 4, 39, 8, 4, + 1, 4, 1, 4, 3, 4, 43, 8, 4, 5, 4, 45, 8, 4, 10, 4, 12, 4, 48, 9, 4, 1, + 5, 1, 5, 1, 5, 0, 0, 6, 0, 2, 4, 6, 8, 10, 0, 1, 1, 0, 1, 7, 53, 0, 13, + 1, 0, 0, 0, 2, 26, 1, 0, 0, 0, 4, 33, 1, 0, 0, 0, 6, 35, 1, 0, 0, 0, 8, + 38, 1, 0, 0, 0, 10, 49, 1, 0, 0, 0, 12, 14, 3, 2, 1, 0, 13, 12, 1, 0, 0, + 0, 13, 14, 1, 0, 0, 0, 14, 21, 1, 0, 0, 0, 15, 17, 5, 10, 0, 0, 16, 18, + 3, 2, 1, 0, 17, 16, 1, 0, 0, 0, 17, 18, 1, 0, 0, 0, 18, 20, 1, 0, 0, 0, + 19, 15, 1, 0, 0, 0, 20, 23, 1, 0, 0, 0, 21, 19, 1, 0, 0, 0, 21, 22, 1, + 0, 0, 0, 22, 24, 1, 0, 0, 0, 23, 21, 1, 0, 0, 0, 24, 25, 5, 0, 0, 1, 25, + 1, 1, 0, 0, 0, 26, 28, 3, 6, 3, 0, 27, 29, 3, 4, 2, 0, 28, 27, 1, 0, 0, + 0, 28, 29, 1, 0, 0, 0, 29, 31, 1, 0, 0, 0, 30, 32, 3, 8, 4, 0, 31, 30, + 1, 0, 0, 0, 31, 32, 1, 0, 0, 0, 32, 3, 1, 0, 0, 0, 33, 34, 5, 10, 0, 0, + 34, 5, 1, 0, 0, 0, 35, 36, 7, 0, 0, 0, 36, 7, 1, 0, 0, 0, 37, 39, 3, 10, + 5, 0, 38, 37, 1, 0, 0, 0, 38, 39, 1, 0, 0, 0, 39, 46, 1, 0, 0, 0, 40, 42, + 5, 8, 0, 0, 41, 43, 3, 10, 5, 0, 42, 41, 1, 0, 0, 0, 42, 43, 1, 0, 0, 0, + 43, 45, 1, 0, 0, 0, 44, 40, 1, 0, 0, 0, 45, 48, 1, 0, 0, 0, 46, 44, 1, + 0, 0, 0, 46, 47, 1, 0, 0, 0, 47, 9, 1, 0, 0, 0, 48, 46, 1, 0, 0, 0, 49, + 50, 5, 9, 0, 0, 50, 11, 1, 0, 0, 0, 8, 13, 17, 21, 28, 31, 38, 42, 46, } deserializer := antlr.NewATNDeserializer(nil) staticData.atn = deserializer.Deserialize(staticData.serializedATN) @@ -446,8 +447,6 @@ func (s *MatchEntryContext) ExitRule(listener antlr.ParseTreeListener) { func (p *MatchParser) MatchEntry() (localctx IMatchEntryContext) { localctx = NewMatchEntryContext(p, p.GetParserRuleContext(), p.GetState()) p.EnterRule(localctx, 2, MatchParserRULE_matchEntry) - var _la int - p.EnterOuterAlt(localctx, 1) { p.SetState(26) @@ -467,17 +466,15 @@ func (p *MatchParser) MatchEntry() (localctx IMatchEntryContext) { } p.SetState(31) p.GetErrorHandler().Sync(p) - if p.HasError() { - goto errorExit - } - _la = p.GetTokenStream().LA(1) - if _la == MatchParserSTRING { + if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 4, p.GetParserRuleContext()) == 1 { { p.SetState(30) p.Values() } + } else if p.HasError() { // JIM + goto errorExit } errorExit: @@ -844,11 +841,21 @@ func (p *MatchParser) Values() (localctx IValuesContext) { var _la int p.EnterOuterAlt(localctx, 1) - { - p.SetState(37) - p.Value() + p.SetState(38) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit } - p.SetState(44) + _la = p.GetTokenStream().LA(1) + + if _la == MatchParserSTRING { + { + p.SetState(37) + p.Value() + } + + } + p.SetState(46) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -857,14 +864,14 @@ func (p *MatchParser) Values() (localctx IValuesContext) { for _la == MatchParserCOMMA { { - p.SetState(38) + p.SetState(40) p.Match(MatchParserCOMMA) if p.HasError() { // Recognition error - abort rule goto errorExit } } - p.SetState(40) + p.SetState(42) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -873,13 +880,13 @@ func (p *MatchParser) Values() (localctx IValuesContext) { if _la == MatchParserSTRING { { - p.SetState(39) + p.SetState(41) p.Value() } } - p.SetState(46) + p.SetState(48) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -975,7 +982,7 @@ func (p *MatchParser) Value() (localctx IValueContext) { p.EnterRule(localctx, 10, MatchParserRULE_value) p.EnterOuterAlt(localctx, 1) { - p.SetState(47) + p.SetState(49) p.Match(MatchParserSTRING) if p.HasError() { // Recognition error - abort rule diff --git a/handlers/sshd_config/handlers/formatting_nodes.go b/handlers/sshd_config/handlers/formatting_nodes.go index 4045b36..02c148e 100644 --- a/handlers/sshd_config/handlers/formatting_nodes.go +++ b/handlers/sshd_config/handlers/formatting_nodes.go @@ -11,14 +11,14 @@ import ( protocol "github.com/tliron/glsp/protocol_3_16" ) +var optionTemplate = formatting.FormatTemplate( + "%s /!'%s/!'", +) + func formatSSHDOption( option *ast.SSHDOption, options protocol.FormattingOptions, ) []protocol.TextEdit { - template := formatting.FormatTemplate( - "%s/t%s", - ) - var key string if option.Key != nil { @@ -38,7 +38,7 @@ func formatSSHDOption( return []protocol.TextEdit{ { Range: option.ToLSPRange(), - NewText: template.Format(options, key, value), + NewText: optionTemplate.Format(options, key, value), }, } } @@ -49,12 +49,9 @@ func formatSSHDMatchBlock( ) []protocol.TextEdit { edits := make([]protocol.TextEdit, 0) - template := formatting.FormatTemplate( - "%s/t%s", - ) edits = append(edits, protocol.TextEdit{ Range: matchBlock.ToLSPRange(), - NewText: template.Format(options, matchBlock.MatchEntry.Key.Key, formatMatchToString(matchBlock.MatchValue)), + NewText: optionTemplate.Format(options, matchBlock.MatchEntry.Key.Key, formatMatchToString(matchBlock.MatchValue)), }) it := matchBlock.Options.Iterator() From dbd82e49395c8781f5f7fe754f77be44d1ee73ce Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Sat, 21 Sep 2024 15:30:34 +0200 Subject: [PATCH 065/133] fix(common): Improve formatting --- common/formatting/formatting.go | 41 ++++++++++++++++++++++++++++ common/formatting/formatting_test.go | 37 +++++++++++++++++++++++++ 2 files changed, 78 insertions(+) diff --git a/common/formatting/formatting.go b/common/formatting/formatting.go index 3400aaf..c72b639 100644 --- a/common/formatting/formatting.go +++ b/common/formatting/formatting.go @@ -32,6 +32,8 @@ func (f FormatTemplate) Format( value = strings.TrimRight(value, "\t") } + value = surroundWithQuotes(value) + return value } @@ -57,6 +59,45 @@ func (f FormatTemplate) replace(format string, replacement string) FormatTemplat return FormatTemplate(value) } +func surroundWithQuotes(s string) string { + value := s + currentIndex := 0 + + for { + startPosition := strings.Index(value[currentIndex:], "/!'") + + if startPosition == -1 { + break + } + + startPosition = startPosition + currentIndex + 3 + currentIndex = startPosition + + endPosition := strings.Index(value[startPosition:], "/!'") + + if endPosition == -1 { + break + } + + endPosition = endPosition + startPosition + currentIndex = endPosition + + innerValue := value[startPosition:endPosition] + + if strings.Contains(innerValue, " ") { + value = value[:startPosition-3] + "\"" + innerValue + "\"" + value[endPosition+3:] + } else { + value = value[:startPosition-3] + innerValue + value[endPosition+3:] + } + + if endPosition+3 >= len(value) { + break + } + } + + return value +} + func getTab(options protocol.FormattingOptions) string { tabSize := options["tabSize"].(float64) insertSpace := options["insertSpaces"].(bool) diff --git a/common/formatting/formatting_test.go b/common/formatting/formatting_test.go index 290d41f..fc606aa 100644 --- a/common/formatting/formatting_test.go +++ b/common/formatting/formatting_test.go @@ -79,3 +79,40 @@ func TestSimpleExampleWhiteSpaceAtEndShouldNOTTrim( t.Errorf("Expected %q but got %q", expected, result) } } + +func TestSurroundWithQuotesExample( + t *testing.T, +) { + template := FormatTemplate("%s /!'%s/!'") + + options := protocol.FormattingOptions{ + "tabSize": float64(4), + "insertSpaces": false, + "trimTrailingWhitespace": true, + } + + result := template.Format(options, "PermitRootLogin", "this is okay") + expected := `PermitRootLogin "this is okay"` + + if result != expected { + t.Errorf("Expected %q but got %q", expected, result) + } +} +func TestSurroundWithQuotesButNoSpaceExample( + t *testing.T, +) { + template := FormatTemplate("%s /!'%s/!'") + + options := protocol.FormattingOptions{ + "tabSize": float64(4), + "insertSpaces": false, + "trimTrailingWhitespace": true, + } + + result := template.Format(options, "PermitRootLogin", "yes") + expected := `PermitRootLogin yes` + + if result != expected { + t.Errorf("Expected %q but got %q", expected, result) + } +} From 5b660d9b609a691b924567828ce4e1fed984b586 Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Sat, 21 Sep 2024 15:30:58 +0200 Subject: [PATCH 066/133] feat(common): Add Position to common --- common/location.go | 107 +++++++++++++++++++++++++++++-- common/location_test.go | 137 ++++++++++++++++++++++++++++++++++++++++ common/lsp.go | 14 ++++ 3 files changed, 252 insertions(+), 6 deletions(-) create mode 100644 common/location_test.go diff --git a/common/location.go b/common/location.go index db050e7..fc62ca5 100644 --- a/common/location.go +++ b/common/location.go @@ -12,11 +12,60 @@ type Location struct { Character uint32 } +func (l Location) GetRelativeIndexPosition(i IndexPosition) IndexPosition { + return i - IndexPosition(l.Character) +} + +// LocationRange: Represents a range of characters in a document +// Locations are zero-based, start-inclusive and end-exclusive +// This approach is preferred over using an index-based range, because +// it allows to check very easily for cursor positions, as well as for +// index-based ranges. type LocationRange struct { Start Location End Location } +func (l LocationRange) ContainsPosition(p Position) bool { + return l.IsPositionAfterStart(p) && l.IsPositionBeforeEnd(p) +} + +// Check if the given position is after the start of the range +// It's like: Position >= Start +// This checks inclusively +func (l LocationRange) IsPositionAfterStart(p Position) bool { + return p.getValue() >= l.Start.Character +} + +func (l LocationRange) IsPositionBeforeStart(p Position) bool { + return p.getValue() < l.Start.Character +} + +// Check if the given position is before the end of the range +// It's like: Position <= End +// This checks inclusively +func (l LocationRange) IsPositionBeforeEnd(p Position) bool { + switch p.(type) { + case CursorPosition: + return p.getValue() <= l.End.Character + case IndexPosition: + return p.getValue() < l.End.Character + } + + return false +} + +func (l LocationRange) IsPositionAfterEnd(p Position) bool { + switch p.(type) { + case CursorPosition: + return p.getValue() > l.End.Character + case IndexPosition: + return p.getValue() >= l.End.Character + } + + return false +} + func (l LocationRange) ShiftHorizontal(offset uint32) LocationRange { return LocationRange{ Start: Location{ @@ -57,7 +106,7 @@ func (l LocationRange) ToLSPRange() protocol.Range { }, End: protocol.Position{ Line: l.End.Line, - Character: l.End.Character + 1, + Character: l.End.Character, }, } } @@ -67,10 +116,6 @@ func (l *LocationRange) ChangeBothLines(newLine uint32) { l.End.Line = newLine } -func (l LocationRange) ContainsCursor(line uint32, character uint32) bool { - return line == l.Start.Line && character >= l.Start.Character && character <= l.End.Character -} - func (l LocationRange) ContainsCursorByCharacter(character uint32) bool { return character >= l.Start.Character && character <= l.End.Character } @@ -115,7 +160,57 @@ func CharacterRangeFromCtx( }, End: Location{ Line: line, - Character: end, + Character: end + 1, }, } } + +type Position interface { + getValue() uint32 +} + +// Use this type if you want to use a cursor based position +// A cursor based position is a position that represents a cursor +// Given the example: +// "PermitRootLogin yes" +// Taking a look at the first character "P" - the index is 0. +// However, the cursor can either be at: +// +// "|P" - 0 or +// "P|" - 1 +// +// This is used for example for textDocument/completion or textDocument/signature +type CursorPosition uint32 + +func (c CursorPosition) getValue() uint32 { + return uint32(c) +} + +func (c CursorPosition) shiftHorizontal(offset uint32) CursorPosition { + return CursorPosition(uint32(c) + offset) +} + +func LSPCharacterAsCursorPosition(character uint32) CursorPosition { + return CursorPosition(character) +} + +func (c CursorPosition) IsBeforeIndexPosition(i IndexPosition) bool { + // |H[e]llo + return uint32(c) < uint32(i) +} + +func (c CursorPosition) IsAfterIndexPosition(i IndexPosition) bool { + // H[e]|llo + return uint32(c) > uint32(i)+1 +} + +// Use this type if you want to use an index based position +type IndexPosition uint32 + +func (i IndexPosition) getValue() uint32 { + return uint32(i) +} + +func LSPCharacterAsIndexPosition(character uint32) IndexPosition { + return IndexPosition(character) +} diff --git a/common/location_test.go b/common/location_test.go new file mode 100644 index 0000000..823b6aa --- /dev/null +++ b/common/location_test.go @@ -0,0 +1,137 @@ +package common + +import ( + "testing" +) + +func TestCursorPosition( + t *testing.T, +) { + // Contains fictive range for the name "Test" in the code: + // func Test() {} + locationRange := LocationRange{ + Start: Location{ + Line: 0, + Character: 5, + }, + End: Location{ + Line: 0, + Character: 9, + }, + } + + if !(locationRange.ContainsPosition(LSPCharacterAsCursorPosition(5)) == true) { + t.Errorf("Expected 5 to be in range, but it wasn't") + } + + if !(locationRange.ContainsPosition(LSPCharacterAsCursorPosition(6)) == true) { + t.Errorf("Expected 6 to be in range, but it wasn't") + } + + if !(locationRange.ContainsPosition(LSPCharacterAsCursorPosition(9)) == true) { + t.Errorf("Expected 9 to be in range, but it wasn't") + } + + if !(locationRange.ContainsPosition(LSPCharacterAsCursorPosition(10)) == false) { + t.Errorf("Expected 10 to not be in range, but it was") + } + + if !(locationRange.ContainsPosition(LSPCharacterAsCursorPosition(4)) == false) { + t.Errorf("Expected 4 to not be in range, but it was") + } + + if !(locationRange.IsPositionBeforeStart(LSPCharacterAsCursorPosition(0)) == true) { + t.Errorf("Expected 0 to be before start, but it wasn't") + } + + if !(locationRange.IsPositionBeforeStart(LSPCharacterAsCursorPosition(4)) == true) { + t.Errorf("Expected 5 to be before start, but it wasn't") + } + + if !(locationRange.IsPositionBeforeStart(LSPCharacterAsCursorPosition(5)) == false) { + t.Errorf("Expected 5 to not be before start, but it was") + } + + if !(locationRange.IsPositionBeforeStart(LSPCharacterAsCursorPosition(10)) == false) { + t.Errorf("Expected 10 to not be before start, but it was") + } + + if !(locationRange.IsPositionAfterEnd(LSPCharacterAsCursorPosition(10)) == true) { + t.Errorf("Expected 10 to be after end, but it wasn't") + } + + if !(locationRange.IsPositionAfterEnd(LSPCharacterAsCursorPosition(11)) == true) { + t.Errorf("Expected 11 to be after end, but it wasn't") + } + + if !(locationRange.IsPositionAfterEnd(LSPCharacterAsCursorPosition(9)) == false) { + t.Errorf("Expected 9 to not be after end, but it was") + } + + if !(locationRange.IsPositionAfterEnd(LSPCharacterAsCursorPosition(5)) == false) { + t.Errorf("Expected 5 to not be after end, but it was") + } +} + +func TestIndexPosition(t *testing.T) { + // Contains fictive range for the name "Test" in the code: + // func Test() {} + locationRange := LocationRange{ + Start: Location{ + Line: 0, + Character: 5, + }, + End: Location{ + Line: 0, + Character: 9, + }, + } + + if !(locationRange.ContainsPosition(LSPCharacterAsIndexPosition(5)) == true) { + t.Errorf("Expected index position 5 to be in range, but it wasn't") + } + + if !(locationRange.ContainsPosition(LSPCharacterAsIndexPosition(6)) == true) { + t.Errorf("Expected index position 6 to be in range, but it wasn't") + } + + if !(locationRange.ContainsPosition(LSPCharacterAsIndexPosition(8)) == true) { + t.Errorf("Expected index position 6 to be in range, but it wasn't") + } + + if !(locationRange.ContainsPosition(LSPCharacterAsIndexPosition(9)) == false) { + t.Errorf("Expected index position 9 to not be in range, but it was") + } + + if !(locationRange.ContainsPosition(LSPCharacterAsIndexPosition(10)) == false) { + t.Errorf("Expected index position 10 to not be in range, but it was") + } + + if !(locationRange.ContainsPosition(LSPCharacterAsIndexPosition(4)) == false) { + t.Errorf("Expected index position 4 to not be in range, but it was") + } + + if !(locationRange.IsPositionBeforeStart(LSPCharacterAsIndexPosition(4)) == true) { + t.Errorf("Expected index position 4 to be before start, but it wasn't") + } + + if !(locationRange.IsPositionBeforeStart(LSPCharacterAsIndexPosition(5)) == false) { + t.Errorf("Expected index position 5 to not be before start, but it was") + } + + if !(locationRange.IsPositionBeforeStart(LSPCharacterAsIndexPosition(10)) == false) { + t.Errorf("Expected index position 10 to not be before start, but it wasn't") + } + + if !(locationRange.IsPositionAfterEnd(LSPCharacterAsIndexPosition(10)) == true) { + t.Errorf("Expected index position 10 to be after end, but it wasn't") + } + + if !(locationRange.IsPositionAfterEnd(LSPCharacterAsIndexPosition(9)) == true) { + t.Errorf("Expected index position 9 to be after end, but it wasn't") + } + + if !(locationRange.IsPositionAfterEnd(LSPCharacterAsIndexPosition(5)) == false) { + t.Errorf("Expected index position 5 to not be after end, but it was") + } +} diff --git a/common/lsp.go b/common/lsp.go index 29c0279..fd2e091 100644 --- a/common/lsp.go +++ b/common/lsp.go @@ -1,5 +1,19 @@ package common +// LSPCharacterAsCursorPosition: +// @deprecated func CursorToCharacterIndex(cursor uint32) uint32 { return max(1, cursor) - 1 } + +func DeprecatedImprovedCursorToIndex( + c CursorPosition, + line string, + offset uint32, +) uint32 { + if len(line) == 0 { + return 0 + } + + return min(uint32(len(line)-1), uint32(c)-offset+1) +} From 91c239b50922606136297b3356136ca3abeeca9f Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Sat, 21 Sep 2024 15:31:18 +0200 Subject: [PATCH 067/133] fix: Add roothandler for range formatting --- root-handler/handler.go | 31 ++++++++++++++++--------------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/root-handler/handler.go b/root-handler/handler.go index fc59b8a..91de471 100644 --- a/root-handler/handler.go +++ b/root-handler/handler.go @@ -17,21 +17,22 @@ var lspHandler protocol.Handler func SetUpRootHandler() { rootHandler = NewRootHandler() lspHandler = protocol.Handler{ - Initialize: initialize, - Initialized: initialized, - Shutdown: shutdown, - SetTrace: setTrace, - TextDocumentDidOpen: TextDocumentDidOpen, - TextDocumentDidChange: TextDocumentDidChange, - TextDocumentCompletion: TextDocumentCompletion, - TextDocumentHover: TextDocumentHover, - TextDocumentDidClose: TextDocumentDidClose, - TextDocumentCodeAction: TextDocumentCodeAction, - TextDocumentDefinition: TextDocumentDefinition, - WorkspaceExecuteCommand: WorkspaceExecuteCommand, - TextDocumentRename: TextDocumentRename, - TextDocumentPrepareRename: TextDocumentPrepareRename, - TextDocumentSignatureHelp: TextDocumentSignatureHelp, + Initialize: initialize, + Initialized: initialized, + Shutdown: shutdown, + SetTrace: setTrace, + TextDocumentDidOpen: TextDocumentDidOpen, + TextDocumentDidChange: TextDocumentDidChange, + TextDocumentCompletion: TextDocumentCompletion, + TextDocumentHover: TextDocumentHover, + TextDocumentDidClose: TextDocumentDidClose, + TextDocumentCodeAction: TextDocumentCodeAction, + TextDocumentDefinition: TextDocumentDefinition, + WorkspaceExecuteCommand: WorkspaceExecuteCommand, + TextDocumentRename: TextDocumentRename, + TextDocumentPrepareRename: TextDocumentPrepareRename, + TextDocumentSignatureHelp: TextDocumentSignatureHelp, + TextDocumentRangeFormatting: TextDocumentRangeFormattingFunc, } server := server.NewServer(&lspHandler, lsName, false) From 564763116949a6400cba7cf0670012ad56dfebc5 Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Sat, 21 Sep 2024 16:15:11 +0200 Subject: [PATCH 068/133] fix(sshd_config): Overall improvements --- .../sshd_config/fields/match-parser/Match.g4 | 30 +---- .../fields/match-parser/parser/Match.interp | 16 +-- .../fields/match-parser/parser/Match.tokens | 15 +-- .../match-parser/parser/MatchLexer.interp | 23 +--- .../match-parser/parser/MatchLexer.tokens | 15 +-- .../fields/match-parser/parser/match_lexer.go | 69 +++-------- .../match-parser/parser/match_parser.go | 115 ++++++------------ handlers/sshd_config/handlers/formatting.go | 6 +- .../sshd_config/handlers/formatting_nodes.go | 23 +++- 9 files changed, 86 insertions(+), 226 deletions(-) diff --git a/handlers/sshd_config/fields/match-parser/Match.g4 b/handlers/sshd_config/fields/match-parser/Match.g4 index 10aa6eb..3db90cd 100644 --- a/handlers/sshd_config/fields/match-parser/Match.g4 +++ b/handlers/sshd_config/fields/match-parser/Match.g4 @@ -13,7 +13,7 @@ separator ; criteria - : (USER | GROUP | HOST| LOCALADDRESS | LOCALPORT | RDOMAIN | ADDRESS) + : STRING ; values @@ -24,34 +24,6 @@ value : STRING ; -USER - : ('U'|'u') ('S'|'s') ('E'|'e') ('R'|'r') - ; - -GROUP - : ('G'|'g') ('R'|'r') ('O'|'o') ('U'|'u') ('P'|'p') - ; - -HOST - : ('H'|'h') ('O'|'o') ('S'|'s') ('T'|'t') - ; - -LOCALADDRESS - : ('L'|'l') ('O'|'o') ('C'|'c') ('A'|'a') ('L'|'l') ('A'|'a') ('D'|'d') ('D'|'d') ('R'|'r') ('E'|'e') ('S'|'s') ('S'|'s') - ; - -LOCALPORT - : ('L'|'l') ('O'|'o') ('C'|'c') ('A'|'a') ('L'|'l') ('P'|'p') ('O'|'o') ('R'|'r') ('T'|'t') - ; - -RDOMAIN - : ('R'|'r') ('D'|'d') ('O'|'o') ('M'|'m') ('A'|'a') ('I'|'i') ('N'|'n') - ; - -ADDRESS - : ('A'|'a') ('D'|'d') ('D'|'d') ('R'|'r') ('E'|'e') ('S'|'s') ('S'|'s') - ; - COMMA : ',' ; diff --git a/handlers/sshd_config/fields/match-parser/parser/Match.interp b/handlers/sshd_config/fields/match-parser/parser/Match.interp index d188f93..491bdd3 100644 --- a/handlers/sshd_config/fields/match-parser/parser/Match.interp +++ b/handlers/sshd_config/fields/match-parser/parser/Match.interp @@ -1,25 +1,11 @@ token literal names: null -null -null -null -null -null -null -null ',' null null token symbolic names: null -USER -GROUP -HOST -LOCALADDRESS -LOCALPORT -RDOMAIN -ADDRESS COMMA STRING WHITESPACE @@ -34,4 +20,4 @@ value atn: -[4, 1, 10, 52, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 2, 5, 7, 5, 1, 0, 3, 0, 14, 8, 0, 1, 0, 1, 0, 3, 0, 18, 8, 0, 5, 0, 20, 8, 0, 10, 0, 12, 0, 23, 9, 0, 1, 0, 1, 0, 1, 1, 1, 1, 3, 1, 29, 8, 1, 1, 1, 3, 1, 32, 8, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, 3, 4, 39, 8, 4, 1, 4, 1, 4, 3, 4, 43, 8, 4, 5, 4, 45, 8, 4, 10, 4, 12, 4, 48, 9, 4, 1, 5, 1, 5, 1, 5, 0, 0, 6, 0, 2, 4, 6, 8, 10, 0, 1, 1, 0, 1, 7, 53, 0, 13, 1, 0, 0, 0, 2, 26, 1, 0, 0, 0, 4, 33, 1, 0, 0, 0, 6, 35, 1, 0, 0, 0, 8, 38, 1, 0, 0, 0, 10, 49, 1, 0, 0, 0, 12, 14, 3, 2, 1, 0, 13, 12, 1, 0, 0, 0, 13, 14, 1, 0, 0, 0, 14, 21, 1, 0, 0, 0, 15, 17, 5, 10, 0, 0, 16, 18, 3, 2, 1, 0, 17, 16, 1, 0, 0, 0, 17, 18, 1, 0, 0, 0, 18, 20, 1, 0, 0, 0, 19, 15, 1, 0, 0, 0, 20, 23, 1, 0, 0, 0, 21, 19, 1, 0, 0, 0, 21, 22, 1, 0, 0, 0, 22, 24, 1, 0, 0, 0, 23, 21, 1, 0, 0, 0, 24, 25, 5, 0, 0, 1, 25, 1, 1, 0, 0, 0, 26, 28, 3, 6, 3, 0, 27, 29, 3, 4, 2, 0, 28, 27, 1, 0, 0, 0, 28, 29, 1, 0, 0, 0, 29, 31, 1, 0, 0, 0, 30, 32, 3, 8, 4, 0, 31, 30, 1, 0, 0, 0, 31, 32, 1, 0, 0, 0, 32, 3, 1, 0, 0, 0, 33, 34, 5, 10, 0, 0, 34, 5, 1, 0, 0, 0, 35, 36, 7, 0, 0, 0, 36, 7, 1, 0, 0, 0, 37, 39, 3, 10, 5, 0, 38, 37, 1, 0, 0, 0, 38, 39, 1, 0, 0, 0, 39, 46, 1, 0, 0, 0, 40, 42, 5, 8, 0, 0, 41, 43, 3, 10, 5, 0, 42, 41, 1, 0, 0, 0, 42, 43, 1, 0, 0, 0, 43, 45, 1, 0, 0, 0, 44, 40, 1, 0, 0, 0, 45, 48, 1, 0, 0, 0, 46, 44, 1, 0, 0, 0, 46, 47, 1, 0, 0, 0, 47, 9, 1, 0, 0, 0, 48, 46, 1, 0, 0, 0, 49, 50, 5, 9, 0, 0, 50, 11, 1, 0, 0, 0, 8, 13, 17, 21, 28, 31, 38, 42, 46] \ No newline at end of file +[4, 1, 3, 52, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 2, 5, 7, 5, 1, 0, 3, 0, 14, 8, 0, 1, 0, 1, 0, 3, 0, 18, 8, 0, 5, 0, 20, 8, 0, 10, 0, 12, 0, 23, 9, 0, 1, 0, 1, 0, 1, 1, 1, 1, 3, 1, 29, 8, 1, 1, 1, 3, 1, 32, 8, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, 3, 4, 39, 8, 4, 1, 4, 1, 4, 3, 4, 43, 8, 4, 5, 4, 45, 8, 4, 10, 4, 12, 4, 48, 9, 4, 1, 5, 1, 5, 1, 5, 0, 0, 6, 0, 2, 4, 6, 8, 10, 0, 0, 53, 0, 13, 1, 0, 0, 0, 2, 26, 1, 0, 0, 0, 4, 33, 1, 0, 0, 0, 6, 35, 1, 0, 0, 0, 8, 38, 1, 0, 0, 0, 10, 49, 1, 0, 0, 0, 12, 14, 3, 2, 1, 0, 13, 12, 1, 0, 0, 0, 13, 14, 1, 0, 0, 0, 14, 21, 1, 0, 0, 0, 15, 17, 5, 3, 0, 0, 16, 18, 3, 2, 1, 0, 17, 16, 1, 0, 0, 0, 17, 18, 1, 0, 0, 0, 18, 20, 1, 0, 0, 0, 19, 15, 1, 0, 0, 0, 20, 23, 1, 0, 0, 0, 21, 19, 1, 0, 0, 0, 21, 22, 1, 0, 0, 0, 22, 24, 1, 0, 0, 0, 23, 21, 1, 0, 0, 0, 24, 25, 5, 0, 0, 1, 25, 1, 1, 0, 0, 0, 26, 28, 3, 6, 3, 0, 27, 29, 3, 4, 2, 0, 28, 27, 1, 0, 0, 0, 28, 29, 1, 0, 0, 0, 29, 31, 1, 0, 0, 0, 30, 32, 3, 8, 4, 0, 31, 30, 1, 0, 0, 0, 31, 32, 1, 0, 0, 0, 32, 3, 1, 0, 0, 0, 33, 34, 5, 3, 0, 0, 34, 5, 1, 0, 0, 0, 35, 36, 5, 2, 0, 0, 36, 7, 1, 0, 0, 0, 37, 39, 3, 10, 5, 0, 38, 37, 1, 0, 0, 0, 38, 39, 1, 0, 0, 0, 39, 46, 1, 0, 0, 0, 40, 42, 5, 1, 0, 0, 41, 43, 3, 10, 5, 0, 42, 41, 1, 0, 0, 0, 42, 43, 1, 0, 0, 0, 43, 45, 1, 0, 0, 0, 44, 40, 1, 0, 0, 0, 45, 48, 1, 0, 0, 0, 46, 44, 1, 0, 0, 0, 46, 47, 1, 0, 0, 0, 47, 9, 1, 0, 0, 0, 48, 46, 1, 0, 0, 0, 49, 50, 5, 2, 0, 0, 50, 11, 1, 0, 0, 0, 8, 13, 17, 21, 28, 31, 38, 42, 46] \ No newline at end of file diff --git a/handlers/sshd_config/fields/match-parser/parser/Match.tokens b/handlers/sshd_config/fields/match-parser/parser/Match.tokens index 21f2b73..9172656 100644 --- a/handlers/sshd_config/fields/match-parser/parser/Match.tokens +++ b/handlers/sshd_config/fields/match-parser/parser/Match.tokens @@ -1,11 +1,4 @@ -USER=1 -GROUP=2 -HOST=3 -LOCALADDRESS=4 -LOCALPORT=5 -RDOMAIN=6 -ADDRESS=7 -COMMA=8 -STRING=9 -WHITESPACE=10 -','=8 +COMMA=1 +STRING=2 +WHITESPACE=3 +','=1 diff --git a/handlers/sshd_config/fields/match-parser/parser/MatchLexer.interp b/handlers/sshd_config/fields/match-parser/parser/MatchLexer.interp index 590b1bb..90a8247 100644 --- a/handlers/sshd_config/fields/match-parser/parser/MatchLexer.interp +++ b/handlers/sshd_config/fields/match-parser/parser/MatchLexer.interp @@ -1,37 +1,16 @@ token literal names: null -null -null -null -null -null -null -null ',' null null token symbolic names: null -USER -GROUP -HOST -LOCALADDRESS -LOCALPORT -RDOMAIN -ADDRESS COMMA STRING WHITESPACE rule names: -USER -GROUP -HOST -LOCALADDRESS -LOCALPORT -RDOMAIN -ADDRESS COMMA STRING WHITESPACE @@ -44,4 +23,4 @@ mode names: DEFAULT_MODE atn: -[4, 0, 10, 88, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 2, 5, 7, 5, 2, 6, 7, 6, 2, 7, 7, 7, 2, 8, 7, 8, 2, 9, 7, 9, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 7, 1, 7, 1, 8, 4, 8, 80, 8, 8, 11, 8, 12, 8, 81, 1, 9, 4, 9, 85, 8, 9, 11, 9, 12, 9, 86, 0, 0, 10, 1, 1, 3, 2, 5, 3, 7, 4, 9, 5, 11, 6, 13, 7, 15, 8, 17, 9, 19, 10, 1, 0, 18, 2, 0, 85, 85, 117, 117, 2, 0, 83, 83, 115, 115, 2, 0, 69, 69, 101, 101, 2, 0, 82, 82, 114, 114, 2, 0, 71, 71, 103, 103, 2, 0, 79, 79, 111, 111, 2, 0, 80, 80, 112, 112, 2, 0, 72, 72, 104, 104, 2, 0, 84, 84, 116, 116, 2, 0, 76, 76, 108, 108, 2, 0, 67, 67, 99, 99, 2, 0, 65, 65, 97, 97, 2, 0, 68, 68, 100, 100, 2, 0, 77, 77, 109, 109, 2, 0, 73, 73, 105, 105, 2, 0, 78, 78, 110, 110, 5, 0, 9, 10, 13, 13, 32, 32, 35, 35, 44, 44, 2, 0, 9, 9, 32, 32, 89, 0, 1, 1, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, 5, 1, 0, 0, 0, 0, 7, 1, 0, 0, 0, 0, 9, 1, 0, 0, 0, 0, 11, 1, 0, 0, 0, 0, 13, 1, 0, 0, 0, 0, 15, 1, 0, 0, 0, 0, 17, 1, 0, 0, 0, 0, 19, 1, 0, 0, 0, 1, 21, 1, 0, 0, 0, 3, 26, 1, 0, 0, 0, 5, 32, 1, 0, 0, 0, 7, 37, 1, 0, 0, 0, 9, 50, 1, 0, 0, 0, 11, 60, 1, 0, 0, 0, 13, 68, 1, 0, 0, 0, 15, 76, 1, 0, 0, 0, 17, 79, 1, 0, 0, 0, 19, 84, 1, 0, 0, 0, 21, 22, 7, 0, 0, 0, 22, 23, 7, 1, 0, 0, 23, 24, 7, 2, 0, 0, 24, 25, 7, 3, 0, 0, 25, 2, 1, 0, 0, 0, 26, 27, 7, 4, 0, 0, 27, 28, 7, 3, 0, 0, 28, 29, 7, 5, 0, 0, 29, 30, 7, 0, 0, 0, 30, 31, 7, 6, 0, 0, 31, 4, 1, 0, 0, 0, 32, 33, 7, 7, 0, 0, 33, 34, 7, 5, 0, 0, 34, 35, 7, 1, 0, 0, 35, 36, 7, 8, 0, 0, 36, 6, 1, 0, 0, 0, 37, 38, 7, 9, 0, 0, 38, 39, 7, 5, 0, 0, 39, 40, 7, 10, 0, 0, 40, 41, 7, 11, 0, 0, 41, 42, 7, 9, 0, 0, 42, 43, 7, 11, 0, 0, 43, 44, 7, 12, 0, 0, 44, 45, 7, 12, 0, 0, 45, 46, 7, 3, 0, 0, 46, 47, 7, 2, 0, 0, 47, 48, 7, 1, 0, 0, 48, 49, 7, 1, 0, 0, 49, 8, 1, 0, 0, 0, 50, 51, 7, 9, 0, 0, 51, 52, 7, 5, 0, 0, 52, 53, 7, 10, 0, 0, 53, 54, 7, 11, 0, 0, 54, 55, 7, 9, 0, 0, 55, 56, 7, 6, 0, 0, 56, 57, 7, 5, 0, 0, 57, 58, 7, 3, 0, 0, 58, 59, 7, 8, 0, 0, 59, 10, 1, 0, 0, 0, 60, 61, 7, 3, 0, 0, 61, 62, 7, 12, 0, 0, 62, 63, 7, 5, 0, 0, 63, 64, 7, 13, 0, 0, 64, 65, 7, 11, 0, 0, 65, 66, 7, 14, 0, 0, 66, 67, 7, 15, 0, 0, 67, 12, 1, 0, 0, 0, 68, 69, 7, 11, 0, 0, 69, 70, 7, 12, 0, 0, 70, 71, 7, 12, 0, 0, 71, 72, 7, 3, 0, 0, 72, 73, 7, 2, 0, 0, 73, 74, 7, 1, 0, 0, 74, 75, 7, 1, 0, 0, 75, 14, 1, 0, 0, 0, 76, 77, 5, 44, 0, 0, 77, 16, 1, 0, 0, 0, 78, 80, 8, 16, 0, 0, 79, 78, 1, 0, 0, 0, 80, 81, 1, 0, 0, 0, 81, 79, 1, 0, 0, 0, 81, 82, 1, 0, 0, 0, 82, 18, 1, 0, 0, 0, 83, 85, 7, 17, 0, 0, 84, 83, 1, 0, 0, 0, 85, 86, 1, 0, 0, 0, 86, 84, 1, 0, 0, 0, 86, 87, 1, 0, 0, 0, 87, 20, 1, 0, 0, 0, 3, 0, 81, 86, 0] \ No newline at end of file +[4, 0, 3, 19, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 1, 0, 1, 0, 1, 1, 4, 1, 11, 8, 1, 11, 1, 12, 1, 12, 1, 2, 4, 2, 16, 8, 2, 11, 2, 12, 2, 17, 0, 0, 3, 1, 1, 3, 2, 5, 3, 1, 0, 2, 5, 0, 9, 10, 13, 13, 32, 32, 35, 35, 44, 44, 2, 0, 9, 9, 32, 32, 20, 0, 1, 1, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, 5, 1, 0, 0, 0, 1, 7, 1, 0, 0, 0, 3, 10, 1, 0, 0, 0, 5, 15, 1, 0, 0, 0, 7, 8, 5, 44, 0, 0, 8, 2, 1, 0, 0, 0, 9, 11, 8, 0, 0, 0, 10, 9, 1, 0, 0, 0, 11, 12, 1, 0, 0, 0, 12, 10, 1, 0, 0, 0, 12, 13, 1, 0, 0, 0, 13, 4, 1, 0, 0, 0, 14, 16, 7, 1, 0, 0, 15, 14, 1, 0, 0, 0, 16, 17, 1, 0, 0, 0, 17, 15, 1, 0, 0, 0, 17, 18, 1, 0, 0, 0, 18, 6, 1, 0, 0, 0, 3, 0, 12, 17, 0] \ No newline at end of file diff --git a/handlers/sshd_config/fields/match-parser/parser/MatchLexer.tokens b/handlers/sshd_config/fields/match-parser/parser/MatchLexer.tokens index 21f2b73..9172656 100644 --- a/handlers/sshd_config/fields/match-parser/parser/MatchLexer.tokens +++ b/handlers/sshd_config/fields/match-parser/parser/MatchLexer.tokens @@ -1,11 +1,4 @@ -USER=1 -GROUP=2 -HOST=3 -LOCALADDRESS=4 -LOCALPORT=5 -RDOMAIN=6 -ADDRESS=7 -COMMA=8 -STRING=9 -WHITESPACE=10 -','=8 +COMMA=1 +STRING=2 +WHITESPACE=3 +','=1 diff --git a/handlers/sshd_config/fields/match-parser/parser/match_lexer.go b/handlers/sshd_config/fields/match-parser/parser/match_lexer.go index 0c61e79..361c298 100644 --- a/handlers/sshd_config/fields/match-parser/parser/match_lexer.go +++ b/handlers/sshd_config/fields/match-parser/parser/match_lexer.go @@ -43,58 +43,26 @@ func matchlexerLexerInit() { "DEFAULT_MODE", } staticData.LiteralNames = []string{ - "", "", "", "", "", "", "", "", "','", + "", "','", } staticData.SymbolicNames = []string{ - "", "USER", "GROUP", "HOST", "LOCALADDRESS", "LOCALPORT", "RDOMAIN", - "ADDRESS", "COMMA", "STRING", "WHITESPACE", + "", "COMMA", "STRING", "WHITESPACE", } staticData.RuleNames = []string{ - "USER", "GROUP", "HOST", "LOCALADDRESS", "LOCALPORT", "RDOMAIN", "ADDRESS", "COMMA", "STRING", "WHITESPACE", } staticData.PredictionContextCache = antlr.NewPredictionContextCache() staticData.serializedATN = []int32{ - 4, 0, 10, 88, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, - 4, 7, 4, 2, 5, 7, 5, 2, 6, 7, 6, 2, 7, 7, 7, 2, 8, 7, 8, 2, 9, 7, 9, 1, - 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, - 2, 1, 2, 1, 2, 1, 2, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, - 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, - 4, 1, 4, 1, 4, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 6, 1, - 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 7, 1, 7, 1, 8, 4, 8, 80, 8, 8, - 11, 8, 12, 8, 81, 1, 9, 4, 9, 85, 8, 9, 11, 9, 12, 9, 86, 0, 0, 10, 1, - 1, 3, 2, 5, 3, 7, 4, 9, 5, 11, 6, 13, 7, 15, 8, 17, 9, 19, 10, 1, 0, 18, - 2, 0, 85, 85, 117, 117, 2, 0, 83, 83, 115, 115, 2, 0, 69, 69, 101, 101, - 2, 0, 82, 82, 114, 114, 2, 0, 71, 71, 103, 103, 2, 0, 79, 79, 111, 111, - 2, 0, 80, 80, 112, 112, 2, 0, 72, 72, 104, 104, 2, 0, 84, 84, 116, 116, - 2, 0, 76, 76, 108, 108, 2, 0, 67, 67, 99, 99, 2, 0, 65, 65, 97, 97, 2, - 0, 68, 68, 100, 100, 2, 0, 77, 77, 109, 109, 2, 0, 73, 73, 105, 105, 2, - 0, 78, 78, 110, 110, 5, 0, 9, 10, 13, 13, 32, 32, 35, 35, 44, 44, 2, 0, - 9, 9, 32, 32, 89, 0, 1, 1, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, 5, 1, 0, 0, 0, - 0, 7, 1, 0, 0, 0, 0, 9, 1, 0, 0, 0, 0, 11, 1, 0, 0, 0, 0, 13, 1, 0, 0, - 0, 0, 15, 1, 0, 0, 0, 0, 17, 1, 0, 0, 0, 0, 19, 1, 0, 0, 0, 1, 21, 1, 0, - 0, 0, 3, 26, 1, 0, 0, 0, 5, 32, 1, 0, 0, 0, 7, 37, 1, 0, 0, 0, 9, 50, 1, - 0, 0, 0, 11, 60, 1, 0, 0, 0, 13, 68, 1, 0, 0, 0, 15, 76, 1, 0, 0, 0, 17, - 79, 1, 0, 0, 0, 19, 84, 1, 0, 0, 0, 21, 22, 7, 0, 0, 0, 22, 23, 7, 1, 0, - 0, 23, 24, 7, 2, 0, 0, 24, 25, 7, 3, 0, 0, 25, 2, 1, 0, 0, 0, 26, 27, 7, - 4, 0, 0, 27, 28, 7, 3, 0, 0, 28, 29, 7, 5, 0, 0, 29, 30, 7, 0, 0, 0, 30, - 31, 7, 6, 0, 0, 31, 4, 1, 0, 0, 0, 32, 33, 7, 7, 0, 0, 33, 34, 7, 5, 0, - 0, 34, 35, 7, 1, 0, 0, 35, 36, 7, 8, 0, 0, 36, 6, 1, 0, 0, 0, 37, 38, 7, - 9, 0, 0, 38, 39, 7, 5, 0, 0, 39, 40, 7, 10, 0, 0, 40, 41, 7, 11, 0, 0, - 41, 42, 7, 9, 0, 0, 42, 43, 7, 11, 0, 0, 43, 44, 7, 12, 0, 0, 44, 45, 7, - 12, 0, 0, 45, 46, 7, 3, 0, 0, 46, 47, 7, 2, 0, 0, 47, 48, 7, 1, 0, 0, 48, - 49, 7, 1, 0, 0, 49, 8, 1, 0, 0, 0, 50, 51, 7, 9, 0, 0, 51, 52, 7, 5, 0, - 0, 52, 53, 7, 10, 0, 0, 53, 54, 7, 11, 0, 0, 54, 55, 7, 9, 0, 0, 55, 56, - 7, 6, 0, 0, 56, 57, 7, 5, 0, 0, 57, 58, 7, 3, 0, 0, 58, 59, 7, 8, 0, 0, - 59, 10, 1, 0, 0, 0, 60, 61, 7, 3, 0, 0, 61, 62, 7, 12, 0, 0, 62, 63, 7, - 5, 0, 0, 63, 64, 7, 13, 0, 0, 64, 65, 7, 11, 0, 0, 65, 66, 7, 14, 0, 0, - 66, 67, 7, 15, 0, 0, 67, 12, 1, 0, 0, 0, 68, 69, 7, 11, 0, 0, 69, 70, 7, - 12, 0, 0, 70, 71, 7, 12, 0, 0, 71, 72, 7, 3, 0, 0, 72, 73, 7, 2, 0, 0, - 73, 74, 7, 1, 0, 0, 74, 75, 7, 1, 0, 0, 75, 14, 1, 0, 0, 0, 76, 77, 5, - 44, 0, 0, 77, 16, 1, 0, 0, 0, 78, 80, 8, 16, 0, 0, 79, 78, 1, 0, 0, 0, - 80, 81, 1, 0, 0, 0, 81, 79, 1, 0, 0, 0, 81, 82, 1, 0, 0, 0, 82, 18, 1, - 0, 0, 0, 83, 85, 7, 17, 0, 0, 84, 83, 1, 0, 0, 0, 85, 86, 1, 0, 0, 0, 86, - 84, 1, 0, 0, 0, 86, 87, 1, 0, 0, 0, 87, 20, 1, 0, 0, 0, 3, 0, 81, 86, 0, + 4, 0, 3, 19, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 1, 0, 1, 0, 1, + 1, 4, 1, 11, 8, 1, 11, 1, 12, 1, 12, 1, 2, 4, 2, 16, 8, 2, 11, 2, 12, 2, + 17, 0, 0, 3, 1, 1, 3, 2, 5, 3, 1, 0, 2, 5, 0, 9, 10, 13, 13, 32, 32, 35, + 35, 44, 44, 2, 0, 9, 9, 32, 32, 20, 0, 1, 1, 0, 0, 0, 0, 3, 1, 0, 0, 0, + 0, 5, 1, 0, 0, 0, 1, 7, 1, 0, 0, 0, 3, 10, 1, 0, 0, 0, 5, 15, 1, 0, 0, + 0, 7, 8, 5, 44, 0, 0, 8, 2, 1, 0, 0, 0, 9, 11, 8, 0, 0, 0, 10, 9, 1, 0, + 0, 0, 11, 12, 1, 0, 0, 0, 12, 10, 1, 0, 0, 0, 12, 13, 1, 0, 0, 0, 13, 4, + 1, 0, 0, 0, 14, 16, 7, 1, 0, 0, 15, 14, 1, 0, 0, 0, 16, 17, 1, 0, 0, 0, + 17, 15, 1, 0, 0, 0, 17, 18, 1, 0, 0, 0, 18, 6, 1, 0, 0, 0, 3, 0, 12, 17, + 0, } deserializer := antlr.NewATNDeserializer(nil) staticData.atn = deserializer.Deserialize(staticData.serializedATN) @@ -135,14 +103,7 @@ func NewMatchLexer(input antlr.CharStream) *MatchLexer { // MatchLexer tokens. const ( - MatchLexerUSER = 1 - MatchLexerGROUP = 2 - MatchLexerHOST = 3 - MatchLexerLOCALADDRESS = 4 - MatchLexerLOCALPORT = 5 - MatchLexerRDOMAIN = 6 - MatchLexerADDRESS = 7 - MatchLexerCOMMA = 8 - MatchLexerSTRING = 9 - MatchLexerWHITESPACE = 10 + MatchLexerCOMMA = 1 + MatchLexerSTRING = 2 + MatchLexerWHITESPACE = 3 ) diff --git a/handlers/sshd_config/fields/match-parser/parser/match_parser.go b/handlers/sshd_config/fields/match-parser/parser/match_parser.go index ae15253..58bd86d 100644 --- a/handlers/sshd_config/fields/match-parser/parser/match_parser.go +++ b/handlers/sshd_config/fields/match-parser/parser/match_parser.go @@ -33,38 +33,37 @@ var MatchParserStaticData struct { func matchParserInit() { staticData := &MatchParserStaticData staticData.LiteralNames = []string{ - "", "", "", "", "", "", "", "", "','", + "", "','", } staticData.SymbolicNames = []string{ - "", "USER", "GROUP", "HOST", "LOCALADDRESS", "LOCALPORT", "RDOMAIN", - "ADDRESS", "COMMA", "STRING", "WHITESPACE", + "", "COMMA", "STRING", "WHITESPACE", } staticData.RuleNames = []string{ "root", "matchEntry", "separator", "criteria", "values", "value", } staticData.PredictionContextCache = antlr.NewPredictionContextCache() staticData.serializedATN = []int32{ - 4, 1, 10, 52, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, - 4, 2, 5, 7, 5, 1, 0, 3, 0, 14, 8, 0, 1, 0, 1, 0, 3, 0, 18, 8, 0, 5, 0, - 20, 8, 0, 10, 0, 12, 0, 23, 9, 0, 1, 0, 1, 0, 1, 1, 1, 1, 3, 1, 29, 8, - 1, 1, 1, 3, 1, 32, 8, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, 3, 4, 39, 8, 4, - 1, 4, 1, 4, 3, 4, 43, 8, 4, 5, 4, 45, 8, 4, 10, 4, 12, 4, 48, 9, 4, 1, - 5, 1, 5, 1, 5, 0, 0, 6, 0, 2, 4, 6, 8, 10, 0, 1, 1, 0, 1, 7, 53, 0, 13, - 1, 0, 0, 0, 2, 26, 1, 0, 0, 0, 4, 33, 1, 0, 0, 0, 6, 35, 1, 0, 0, 0, 8, - 38, 1, 0, 0, 0, 10, 49, 1, 0, 0, 0, 12, 14, 3, 2, 1, 0, 13, 12, 1, 0, 0, - 0, 13, 14, 1, 0, 0, 0, 14, 21, 1, 0, 0, 0, 15, 17, 5, 10, 0, 0, 16, 18, - 3, 2, 1, 0, 17, 16, 1, 0, 0, 0, 17, 18, 1, 0, 0, 0, 18, 20, 1, 0, 0, 0, - 19, 15, 1, 0, 0, 0, 20, 23, 1, 0, 0, 0, 21, 19, 1, 0, 0, 0, 21, 22, 1, - 0, 0, 0, 22, 24, 1, 0, 0, 0, 23, 21, 1, 0, 0, 0, 24, 25, 5, 0, 0, 1, 25, - 1, 1, 0, 0, 0, 26, 28, 3, 6, 3, 0, 27, 29, 3, 4, 2, 0, 28, 27, 1, 0, 0, - 0, 28, 29, 1, 0, 0, 0, 29, 31, 1, 0, 0, 0, 30, 32, 3, 8, 4, 0, 31, 30, - 1, 0, 0, 0, 31, 32, 1, 0, 0, 0, 32, 3, 1, 0, 0, 0, 33, 34, 5, 10, 0, 0, - 34, 5, 1, 0, 0, 0, 35, 36, 7, 0, 0, 0, 36, 7, 1, 0, 0, 0, 37, 39, 3, 10, - 5, 0, 38, 37, 1, 0, 0, 0, 38, 39, 1, 0, 0, 0, 39, 46, 1, 0, 0, 0, 40, 42, - 5, 8, 0, 0, 41, 43, 3, 10, 5, 0, 42, 41, 1, 0, 0, 0, 42, 43, 1, 0, 0, 0, - 43, 45, 1, 0, 0, 0, 44, 40, 1, 0, 0, 0, 45, 48, 1, 0, 0, 0, 46, 44, 1, - 0, 0, 0, 46, 47, 1, 0, 0, 0, 47, 9, 1, 0, 0, 0, 48, 46, 1, 0, 0, 0, 49, - 50, 5, 9, 0, 0, 50, 11, 1, 0, 0, 0, 8, 13, 17, 21, 28, 31, 38, 42, 46, + 4, 1, 3, 52, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, + 2, 5, 7, 5, 1, 0, 3, 0, 14, 8, 0, 1, 0, 1, 0, 3, 0, 18, 8, 0, 5, 0, 20, + 8, 0, 10, 0, 12, 0, 23, 9, 0, 1, 0, 1, 0, 1, 1, 1, 1, 3, 1, 29, 8, 1, 1, + 1, 3, 1, 32, 8, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, 3, 4, 39, 8, 4, 1, 4, + 1, 4, 3, 4, 43, 8, 4, 5, 4, 45, 8, 4, 10, 4, 12, 4, 48, 9, 4, 1, 5, 1, + 5, 1, 5, 0, 0, 6, 0, 2, 4, 6, 8, 10, 0, 0, 53, 0, 13, 1, 0, 0, 0, 2, 26, + 1, 0, 0, 0, 4, 33, 1, 0, 0, 0, 6, 35, 1, 0, 0, 0, 8, 38, 1, 0, 0, 0, 10, + 49, 1, 0, 0, 0, 12, 14, 3, 2, 1, 0, 13, 12, 1, 0, 0, 0, 13, 14, 1, 0, 0, + 0, 14, 21, 1, 0, 0, 0, 15, 17, 5, 3, 0, 0, 16, 18, 3, 2, 1, 0, 17, 16, + 1, 0, 0, 0, 17, 18, 1, 0, 0, 0, 18, 20, 1, 0, 0, 0, 19, 15, 1, 0, 0, 0, + 20, 23, 1, 0, 0, 0, 21, 19, 1, 0, 0, 0, 21, 22, 1, 0, 0, 0, 22, 24, 1, + 0, 0, 0, 23, 21, 1, 0, 0, 0, 24, 25, 5, 0, 0, 1, 25, 1, 1, 0, 0, 0, 26, + 28, 3, 6, 3, 0, 27, 29, 3, 4, 2, 0, 28, 27, 1, 0, 0, 0, 28, 29, 1, 0, 0, + 0, 29, 31, 1, 0, 0, 0, 30, 32, 3, 8, 4, 0, 31, 30, 1, 0, 0, 0, 31, 32, + 1, 0, 0, 0, 32, 3, 1, 0, 0, 0, 33, 34, 5, 3, 0, 0, 34, 5, 1, 0, 0, 0, 35, + 36, 5, 2, 0, 0, 36, 7, 1, 0, 0, 0, 37, 39, 3, 10, 5, 0, 38, 37, 1, 0, 0, + 0, 38, 39, 1, 0, 0, 0, 39, 46, 1, 0, 0, 0, 40, 42, 5, 1, 0, 0, 41, 43, + 3, 10, 5, 0, 42, 41, 1, 0, 0, 0, 42, 43, 1, 0, 0, 0, 43, 45, 1, 0, 0, 0, + 44, 40, 1, 0, 0, 0, 45, 48, 1, 0, 0, 0, 46, 44, 1, 0, 0, 0, 46, 47, 1, + 0, 0, 0, 47, 9, 1, 0, 0, 0, 48, 46, 1, 0, 0, 0, 49, 50, 5, 2, 0, 0, 50, + 11, 1, 0, 0, 0, 8, 13, 17, 21, 28, 31, 38, 42, 46, } deserializer := antlr.NewATNDeserializer(nil) staticData.atn = deserializer.Deserialize(staticData.serializedATN) @@ -102,17 +101,10 @@ func NewMatchParser(input antlr.TokenStream) *MatchParser { // MatchParser tokens. const ( - MatchParserEOF = antlr.TokenEOF - MatchParserUSER = 1 - MatchParserGROUP = 2 - MatchParserHOST = 3 - MatchParserLOCALADDRESS = 4 - MatchParserLOCALPORT = 5 - MatchParserRDOMAIN = 6 - MatchParserADDRESS = 7 - MatchParserCOMMA = 8 - MatchParserSTRING = 9 - MatchParserWHITESPACE = 10 + MatchParserEOF = antlr.TokenEOF + MatchParserCOMMA = 1 + MatchParserSTRING = 2 + MatchParserWHITESPACE = 3 ) // MatchParser rules. @@ -261,7 +253,7 @@ func (p *MatchParser) Root() (localctx IRootContext) { } _la = p.GetTokenStream().LA(1) - if (int64(_la) & ^0x3f) == 0 && ((int64(1)<<_la)&254) != 0 { + if _la == MatchParserSTRING { { p.SetState(12) p.MatchEntry() @@ -291,7 +283,7 @@ func (p *MatchParser) Root() (localctx IRootContext) { } _la = p.GetTokenStream().LA(1) - if (int64(_la) & ^0x3f) == 0 && ((int64(1)<<_la)&254) != 0 { + if _la == MatchParserSTRING { { p.SetState(16) p.MatchEntry() @@ -594,13 +586,7 @@ type ICriteriaContext interface { GetParser() antlr.Parser // Getter signatures - USER() antlr.TerminalNode - GROUP() antlr.TerminalNode - HOST() antlr.TerminalNode - LOCALADDRESS() antlr.TerminalNode - LOCALPORT() antlr.TerminalNode - RDOMAIN() antlr.TerminalNode - ADDRESS() antlr.TerminalNode + STRING() antlr.TerminalNode // IsCriteriaContext differentiates from other interfaces. IsCriteriaContext() @@ -638,32 +624,8 @@ func NewCriteriaContext(parser antlr.Parser, parent antlr.ParserRuleContext, inv func (s *CriteriaContext) GetParser() antlr.Parser { return s.parser } -func (s *CriteriaContext) USER() antlr.TerminalNode { - return s.GetToken(MatchParserUSER, 0) -} - -func (s *CriteriaContext) GROUP() antlr.TerminalNode { - return s.GetToken(MatchParserGROUP, 0) -} - -func (s *CriteriaContext) HOST() antlr.TerminalNode { - return s.GetToken(MatchParserHOST, 0) -} - -func (s *CriteriaContext) LOCALADDRESS() antlr.TerminalNode { - return s.GetToken(MatchParserLOCALADDRESS, 0) -} - -func (s *CriteriaContext) LOCALPORT() antlr.TerminalNode { - return s.GetToken(MatchParserLOCALPORT, 0) -} - -func (s *CriteriaContext) RDOMAIN() antlr.TerminalNode { - return s.GetToken(MatchParserRDOMAIN, 0) -} - -func (s *CriteriaContext) ADDRESS() antlr.TerminalNode { - return s.GetToken(MatchParserADDRESS, 0) +func (s *CriteriaContext) STRING() antlr.TerminalNode { + return s.GetToken(MatchParserSTRING, 0) } func (s *CriteriaContext) GetRuleContext() antlr.RuleContext { @@ -689,18 +651,13 @@ func (s *CriteriaContext) ExitRule(listener antlr.ParseTreeListener) { func (p *MatchParser) Criteria() (localctx ICriteriaContext) { localctx = NewCriteriaContext(p, p.GetParserRuleContext(), p.GetState()) p.EnterRule(localctx, 6, MatchParserRULE_criteria) - var _la int - p.EnterOuterAlt(localctx, 1) { p.SetState(35) - _la = p.GetTokenStream().LA(1) - - if !((int64(_la) & ^0x3f) == 0 && ((int64(1)<<_la)&254) != 0) { - p.GetErrorHandler().RecoverInline(p) - } else { - p.GetErrorHandler().ReportMatch(p) - p.Consume() + p.Match(MatchParserSTRING) + if p.HasError() { + // Recognition error - abort rule + goto errorExit } } diff --git a/handlers/sshd_config/handlers/formatting.go b/handlers/sshd_config/handlers/formatting.go index 4fcc2de..38aa0e4 100644 --- a/handlers/sshd_config/handlers/formatting.go +++ b/handlers/sshd_config/handlers/formatting.go @@ -26,7 +26,11 @@ func FormatDocument( switch entry.(type) { case *ast.SSHDOption: option := entry.(*ast.SSHDOption) - edits = append(edits, formatSSHDOption(option, options)...) + edits = append(edits, formatSSHDOption( + option, + options, + optionTemplate, + )...) case *ast.SSHDMatchBlock: matchBlock := entry.(*ast.SSHDMatchBlock) diff --git a/handlers/sshd_config/handlers/formatting_nodes.go b/handlers/sshd_config/handlers/formatting_nodes.go index 02c148e..bb0b7cd 100644 --- a/handlers/sshd_config/handlers/formatting_nodes.go +++ b/handlers/sshd_config/handlers/formatting_nodes.go @@ -14,10 +14,17 @@ import ( var optionTemplate = formatting.FormatTemplate( "%s /!'%s/!'", ) +var matchTemplate = formatting.FormatTemplate( + "%s %s", +) +var matchOptionTemplate = formatting.FormatTemplate( + " %s /!'%s/!'", +) func formatSSHDOption( option *ast.SSHDOption, options protocol.FormattingOptions, + template formatting.FormatTemplate, ) []protocol.TextEdit { var key string @@ -38,7 +45,7 @@ func formatSSHDOption( return []protocol.TextEdit{ { Range: option.ToLSPRange(), - NewText: optionTemplate.Format(options, key, value), + NewText: template.Format(options, key, value), }, } } @@ -50,15 +57,23 @@ func formatSSHDMatchBlock( edits := make([]protocol.TextEdit, 0) edits = append(edits, protocol.TextEdit{ - Range: matchBlock.ToLSPRange(), - NewText: optionTemplate.Format(options, matchBlock.MatchEntry.Key.Key, formatMatchToString(matchBlock.MatchValue)), + Range: matchBlock.MatchEntry.ToLSPRange(), + NewText: matchTemplate.Format( + options, + matchBlock.MatchEntry.Key.Key, + formatMatchToString(matchBlock.MatchValue), + ), }) it := matchBlock.Options.Iterator() for it.Next() { option := it.Value().(*ast.SSHDOption) - edits = append(edits, formatSSHDOption(option, options)...) + edits = append(edits, formatSSHDOption( + option, + options, + matchOptionTemplate, + )...) } return edits From a3e7a8c9b9d9aeb6badb07820ffb434f95a1d7e6 Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Sat, 21 Sep 2024 18:38:18 +0200 Subject: [PATCH 069/133] fix(sshd_config): Overall improvements --- handlers/ssh_config/Config.g4 | 41 + handlers/ssh_config/ast/parser/Config.interp | 25 + handlers/ssh_config/ast/parser/Config.tokens | 5 + .../ssh_config/ast/parser/ConfigLexer.interp | 29 + .../ssh_config/ast/parser/ConfigLexer.tokens | 5 + .../ast/parser/config_base_listener.go | 58 + .../ssh_config/ast/parser/config_lexer.go | 112 ++ .../ssh_config/ast/parser/config_listener.go | 46 + .../ssh_config/ast/parser/config_parser.go | 1082 +++++++++++++++++ handlers/ssh_config/ast/ssh_config.go | 62 + handlers/ssh_config/ast/ssh_config_fields.go | 1 + handlers/sshd_config/Config.g4 | 18 +- handlers/sshd_config/analyzer/analyzer.go | 2 +- handlers/sshd_config/analyzer/options.go | 90 +- handlers/sshd_config/analyzer/quotes.go | 59 + handlers/sshd_config/analyzer/quotes_test.go | 62 + handlers/sshd_config/ast/listener.go | 4 + handlers/sshd_config/ast/parser/Config.interp | 5 +- handlers/sshd_config/ast/parser/Config.tokens | 1 + .../sshd_config/ast/parser/ConfigLexer.interp | 5 +- .../sshd_config/ast/parser/ConfigLexer.tokens | 1 + .../ast/parser/config_base_listener.go | 6 + .../sshd_config/ast/parser/config_lexer.go | 46 +- .../sshd_config/ast/parser/config_listener.go | 6 + .../sshd_config/ast/parser/config_parser.go | 384 ++++-- handlers/sshd_config/ast/parser_test.go | 100 +- handlers/sshd_config/ast/sshd_config.go | 1 + .../fields/match-parser/parser_test.go | 2 +- handlers/sshd_config/handlers/completions.go | 12 +- .../lsp/text-document-completion.go | 2 +- handlers/sshd_config/test_utils/input.go | 33 + 31 files changed, 2131 insertions(+), 174 deletions(-) create mode 100644 handlers/ssh_config/Config.g4 create mode 100644 handlers/ssh_config/ast/parser/Config.interp create mode 100644 handlers/ssh_config/ast/parser/Config.tokens create mode 100644 handlers/ssh_config/ast/parser/ConfigLexer.interp create mode 100644 handlers/ssh_config/ast/parser/ConfigLexer.tokens create mode 100644 handlers/ssh_config/ast/parser/config_base_listener.go create mode 100644 handlers/ssh_config/ast/parser/config_lexer.go create mode 100644 handlers/ssh_config/ast/parser/config_listener.go create mode 100644 handlers/ssh_config/ast/parser/config_parser.go create mode 100644 handlers/ssh_config/ast/ssh_config.go create mode 100644 handlers/ssh_config/ast/ssh_config_fields.go create mode 100644 handlers/sshd_config/analyzer/quotes.go create mode 100644 handlers/sshd_config/analyzer/quotes_test.go create mode 100644 handlers/sshd_config/test_utils/input.go diff --git a/handlers/ssh_config/Config.g4 b/handlers/ssh_config/Config.g4 new file mode 100644 index 0000000..ad4cbe8 --- /dev/null +++ b/handlers/ssh_config/Config.g4 @@ -0,0 +1,41 @@ +grammar Config; + +lineStatement + : (entry | leadingComment | WHITESPACE?) EOF + ; + +entry + : WHITESPACE? key? separator? value? leadingComment? + ; + +separator + : WHITESPACE + ; + +key + : STRING + ; + +value + : (STRING WHITESPACE)* STRING? WHITESPACE? + ; + +leadingComment + : HASH WHITESPACE? (STRING WHITESPACE?)+ + ; + +HASH + : '#' + ; + +WHITESPACE + : [ \t]+ + ; + +STRING + : ~(' ' | '\t' | '\r' | '\n' | '#')+ + ; + +NEWLINE + : '\r'? '\n' + ; diff --git a/handlers/ssh_config/ast/parser/Config.interp b/handlers/ssh_config/ast/parser/Config.interp new file mode 100644 index 0000000..2832f42 --- /dev/null +++ b/handlers/ssh_config/ast/parser/Config.interp @@ -0,0 +1,25 @@ +token literal names: +null +'#' +null +null +null + +token symbolic names: +null +HASH +WHITESPACE +STRING +NEWLINE + +rule names: +lineStatement +entry +separator +key +value +leadingComment + + +atn: +[4, 1, 4, 66, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 2, 5, 7, 5, 1, 0, 1, 0, 1, 0, 3, 0, 16, 8, 0, 3, 0, 18, 8, 0, 1, 0, 1, 0, 1, 1, 3, 1, 23, 8, 1, 1, 1, 3, 1, 26, 8, 1, 1, 1, 3, 1, 29, 8, 1, 1, 1, 3, 1, 32, 8, 1, 1, 1, 3, 1, 35, 8, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, 1, 4, 5, 4, 43, 8, 4, 10, 4, 12, 4, 46, 9, 4, 1, 4, 3, 4, 49, 8, 4, 1, 4, 3, 4, 52, 8, 4, 1, 5, 1, 5, 3, 5, 56, 8, 5, 1, 5, 1, 5, 3, 5, 60, 8, 5, 4, 5, 62, 8, 5, 11, 5, 12, 5, 63, 1, 5, 0, 0, 6, 0, 2, 4, 6, 8, 10, 0, 0, 73, 0, 17, 1, 0, 0, 0, 2, 22, 1, 0, 0, 0, 4, 36, 1, 0, 0, 0, 6, 38, 1, 0, 0, 0, 8, 44, 1, 0, 0, 0, 10, 53, 1, 0, 0, 0, 12, 18, 3, 2, 1, 0, 13, 18, 3, 10, 5, 0, 14, 16, 5, 2, 0, 0, 15, 14, 1, 0, 0, 0, 15, 16, 1, 0, 0, 0, 16, 18, 1, 0, 0, 0, 17, 12, 1, 0, 0, 0, 17, 13, 1, 0, 0, 0, 17, 15, 1, 0, 0, 0, 18, 19, 1, 0, 0, 0, 19, 20, 5, 0, 0, 1, 20, 1, 1, 0, 0, 0, 21, 23, 5, 2, 0, 0, 22, 21, 1, 0, 0, 0, 22, 23, 1, 0, 0, 0, 23, 25, 1, 0, 0, 0, 24, 26, 3, 6, 3, 0, 25, 24, 1, 0, 0, 0, 25, 26, 1, 0, 0, 0, 26, 28, 1, 0, 0, 0, 27, 29, 3, 4, 2, 0, 28, 27, 1, 0, 0, 0, 28, 29, 1, 0, 0, 0, 29, 31, 1, 0, 0, 0, 30, 32, 3, 8, 4, 0, 31, 30, 1, 0, 0, 0, 31, 32, 1, 0, 0, 0, 32, 34, 1, 0, 0, 0, 33, 35, 3, 10, 5, 0, 34, 33, 1, 0, 0, 0, 34, 35, 1, 0, 0, 0, 35, 3, 1, 0, 0, 0, 36, 37, 5, 2, 0, 0, 37, 5, 1, 0, 0, 0, 38, 39, 5, 3, 0, 0, 39, 7, 1, 0, 0, 0, 40, 41, 5, 3, 0, 0, 41, 43, 5, 2, 0, 0, 42, 40, 1, 0, 0, 0, 43, 46, 1, 0, 0, 0, 44, 42, 1, 0, 0, 0, 44, 45, 1, 0, 0, 0, 45, 48, 1, 0, 0, 0, 46, 44, 1, 0, 0, 0, 47, 49, 5, 3, 0, 0, 48, 47, 1, 0, 0, 0, 48, 49, 1, 0, 0, 0, 49, 51, 1, 0, 0, 0, 50, 52, 5, 2, 0, 0, 51, 50, 1, 0, 0, 0, 51, 52, 1, 0, 0, 0, 52, 9, 1, 0, 0, 0, 53, 55, 5, 1, 0, 0, 54, 56, 5, 2, 0, 0, 55, 54, 1, 0, 0, 0, 55, 56, 1, 0, 0, 0, 56, 61, 1, 0, 0, 0, 57, 59, 5, 3, 0, 0, 58, 60, 5, 2, 0, 0, 59, 58, 1, 0, 0, 0, 59, 60, 1, 0, 0, 0, 60, 62, 1, 0, 0, 0, 61, 57, 1, 0, 0, 0, 62, 63, 1, 0, 0, 0, 63, 61, 1, 0, 0, 0, 63, 64, 1, 0, 0, 0, 64, 11, 1, 0, 0, 0, 13, 15, 17, 22, 25, 28, 31, 34, 44, 48, 51, 55, 59, 63] \ No newline at end of file diff --git a/handlers/ssh_config/ast/parser/Config.tokens b/handlers/ssh_config/ast/parser/Config.tokens new file mode 100644 index 0000000..aacc14c --- /dev/null +++ b/handlers/ssh_config/ast/parser/Config.tokens @@ -0,0 +1,5 @@ +HASH=1 +WHITESPACE=2 +STRING=3 +NEWLINE=4 +'#'=1 diff --git a/handlers/ssh_config/ast/parser/ConfigLexer.interp b/handlers/ssh_config/ast/parser/ConfigLexer.interp new file mode 100644 index 0000000..d61e14d --- /dev/null +++ b/handlers/ssh_config/ast/parser/ConfigLexer.interp @@ -0,0 +1,29 @@ +token literal names: +null +'#' +null +null +null + +token symbolic names: +null +HASH +WHITESPACE +STRING +NEWLINE + +rule names: +HASH +WHITESPACE +STRING +NEWLINE + +channel names: +DEFAULT_TOKEN_CHANNEL +HIDDEN + +mode names: +DEFAULT_MODE + +atn: +[4, 0, 4, 26, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 1, 0, 1, 0, 1, 1, 4, 1, 13, 8, 1, 11, 1, 12, 1, 14, 1, 2, 4, 2, 18, 8, 2, 11, 2, 12, 2, 19, 1, 3, 3, 3, 23, 8, 3, 1, 3, 1, 3, 0, 0, 4, 1, 1, 3, 2, 5, 3, 7, 4, 1, 0, 2, 2, 0, 9, 9, 32, 32, 4, 0, 9, 10, 13, 13, 32, 32, 35, 35, 28, 0, 1, 1, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, 5, 1, 0, 0, 0, 0, 7, 1, 0, 0, 0, 1, 9, 1, 0, 0, 0, 3, 12, 1, 0, 0, 0, 5, 17, 1, 0, 0, 0, 7, 22, 1, 0, 0, 0, 9, 10, 5, 35, 0, 0, 10, 2, 1, 0, 0, 0, 11, 13, 7, 0, 0, 0, 12, 11, 1, 0, 0, 0, 13, 14, 1, 0, 0, 0, 14, 12, 1, 0, 0, 0, 14, 15, 1, 0, 0, 0, 15, 4, 1, 0, 0, 0, 16, 18, 8, 1, 0, 0, 17, 16, 1, 0, 0, 0, 18, 19, 1, 0, 0, 0, 19, 17, 1, 0, 0, 0, 19, 20, 1, 0, 0, 0, 20, 6, 1, 0, 0, 0, 21, 23, 5, 13, 0, 0, 22, 21, 1, 0, 0, 0, 22, 23, 1, 0, 0, 0, 23, 24, 1, 0, 0, 0, 24, 25, 5, 10, 0, 0, 25, 8, 1, 0, 0, 0, 4, 0, 14, 19, 22, 0] \ No newline at end of file diff --git a/handlers/ssh_config/ast/parser/ConfigLexer.tokens b/handlers/ssh_config/ast/parser/ConfigLexer.tokens new file mode 100644 index 0000000..aacc14c --- /dev/null +++ b/handlers/ssh_config/ast/parser/ConfigLexer.tokens @@ -0,0 +1,5 @@ +HASH=1 +WHITESPACE=2 +STRING=3 +NEWLINE=4 +'#'=1 diff --git a/handlers/ssh_config/ast/parser/config_base_listener.go b/handlers/ssh_config/ast/parser/config_base_listener.go new file mode 100644 index 0000000..ac8bdac --- /dev/null +++ b/handlers/ssh_config/ast/parser/config_base_listener.go @@ -0,0 +1,58 @@ +// Code generated from Config.g4 by ANTLR 4.13.0. DO NOT EDIT. + +package parser // Config + +import "github.com/antlr4-go/antlr/v4" + +// BaseConfigListener is a complete listener for a parse tree produced by ConfigParser. +type BaseConfigListener struct{} + +var _ ConfigListener = &BaseConfigListener{} + +// VisitTerminal is called when a terminal node is visited. +func (s *BaseConfigListener) VisitTerminal(node antlr.TerminalNode) {} + +// VisitErrorNode is called when an error node is visited. +func (s *BaseConfigListener) VisitErrorNode(node antlr.ErrorNode) {} + +// EnterEveryRule is called when any rule is entered. +func (s *BaseConfigListener) EnterEveryRule(ctx antlr.ParserRuleContext) {} + +// ExitEveryRule is called when any rule is exited. +func (s *BaseConfigListener) ExitEveryRule(ctx antlr.ParserRuleContext) {} + +// EnterLineStatement is called when production lineStatement is entered. +func (s *BaseConfigListener) EnterLineStatement(ctx *LineStatementContext) {} + +// ExitLineStatement is called when production lineStatement is exited. +func (s *BaseConfigListener) ExitLineStatement(ctx *LineStatementContext) {} + +// EnterEntry is called when production entry is entered. +func (s *BaseConfigListener) EnterEntry(ctx *EntryContext) {} + +// ExitEntry is called when production entry is exited. +func (s *BaseConfigListener) ExitEntry(ctx *EntryContext) {} + +// EnterSeparator is called when production separator is entered. +func (s *BaseConfigListener) EnterSeparator(ctx *SeparatorContext) {} + +// ExitSeparator is called when production separator is exited. +func (s *BaseConfigListener) ExitSeparator(ctx *SeparatorContext) {} + +// EnterKey is called when production key is entered. +func (s *BaseConfigListener) EnterKey(ctx *KeyContext) {} + +// ExitKey is called when production key is exited. +func (s *BaseConfigListener) ExitKey(ctx *KeyContext) {} + +// EnterValue is called when production value is entered. +func (s *BaseConfigListener) EnterValue(ctx *ValueContext) {} + +// ExitValue is called when production value is exited. +func (s *BaseConfigListener) ExitValue(ctx *ValueContext) {} + +// EnterLeadingComment is called when production leadingComment is entered. +func (s *BaseConfigListener) EnterLeadingComment(ctx *LeadingCommentContext) {} + +// ExitLeadingComment is called when production leadingComment is exited. +func (s *BaseConfigListener) ExitLeadingComment(ctx *LeadingCommentContext) {} diff --git a/handlers/ssh_config/ast/parser/config_lexer.go b/handlers/ssh_config/ast/parser/config_lexer.go new file mode 100644 index 0000000..ace491d --- /dev/null +++ b/handlers/ssh_config/ast/parser/config_lexer.go @@ -0,0 +1,112 @@ +// Code generated from Config.g4 by ANTLR 4.13.0. DO NOT EDIT. + +package parser + +import ( + "fmt" + "github.com/antlr4-go/antlr/v4" + "sync" + "unicode" +) + +// Suppress unused import error +var _ = fmt.Printf +var _ = sync.Once{} +var _ = unicode.IsLetter + +type ConfigLexer struct { + *antlr.BaseLexer + channelNames []string + modeNames []string + // TODO: EOF string +} + +var ConfigLexerLexerStaticData struct { + once sync.Once + serializedATN []int32 + ChannelNames []string + ModeNames []string + LiteralNames []string + SymbolicNames []string + RuleNames []string + PredictionContextCache *antlr.PredictionContextCache + atn *antlr.ATN + decisionToDFA []*antlr.DFA +} + +func configlexerLexerInit() { + staticData := &ConfigLexerLexerStaticData + staticData.ChannelNames = []string{ + "DEFAULT_TOKEN_CHANNEL", "HIDDEN", + } + staticData.ModeNames = []string{ + "DEFAULT_MODE", + } + staticData.LiteralNames = []string{ + "", "'#'", + } + staticData.SymbolicNames = []string{ + "", "HASH", "WHITESPACE", "STRING", "NEWLINE", + } + staticData.RuleNames = []string{ + "HASH", "WHITESPACE", "STRING", "NEWLINE", + } + staticData.PredictionContextCache = antlr.NewPredictionContextCache() + staticData.serializedATN = []int32{ + 4, 0, 4, 26, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 1, + 0, 1, 0, 1, 1, 4, 1, 13, 8, 1, 11, 1, 12, 1, 14, 1, 2, 4, 2, 18, 8, 2, + 11, 2, 12, 2, 19, 1, 3, 3, 3, 23, 8, 3, 1, 3, 1, 3, 0, 0, 4, 1, 1, 3, 2, + 5, 3, 7, 4, 1, 0, 2, 2, 0, 9, 9, 32, 32, 4, 0, 9, 10, 13, 13, 32, 32, 35, + 35, 28, 0, 1, 1, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, 5, 1, 0, 0, 0, 0, 7, 1, + 0, 0, 0, 1, 9, 1, 0, 0, 0, 3, 12, 1, 0, 0, 0, 5, 17, 1, 0, 0, 0, 7, 22, + 1, 0, 0, 0, 9, 10, 5, 35, 0, 0, 10, 2, 1, 0, 0, 0, 11, 13, 7, 0, 0, 0, + 12, 11, 1, 0, 0, 0, 13, 14, 1, 0, 0, 0, 14, 12, 1, 0, 0, 0, 14, 15, 1, + 0, 0, 0, 15, 4, 1, 0, 0, 0, 16, 18, 8, 1, 0, 0, 17, 16, 1, 0, 0, 0, 18, + 19, 1, 0, 0, 0, 19, 17, 1, 0, 0, 0, 19, 20, 1, 0, 0, 0, 20, 6, 1, 0, 0, + 0, 21, 23, 5, 13, 0, 0, 22, 21, 1, 0, 0, 0, 22, 23, 1, 0, 0, 0, 23, 24, + 1, 0, 0, 0, 24, 25, 5, 10, 0, 0, 25, 8, 1, 0, 0, 0, 4, 0, 14, 19, 22, 0, + } + deserializer := antlr.NewATNDeserializer(nil) + staticData.atn = deserializer.Deserialize(staticData.serializedATN) + atn := staticData.atn + staticData.decisionToDFA = make([]*antlr.DFA, len(atn.DecisionToState)) + decisionToDFA := staticData.decisionToDFA + for index, state := range atn.DecisionToState { + decisionToDFA[index] = antlr.NewDFA(state, index) + } +} + +// ConfigLexerInit initializes any static state used to implement ConfigLexer. By default the +// static state used to implement the lexer is lazily initialized during the first call to +// NewConfigLexer(). You can call this function if you wish to initialize the static state ahead +// of time. +func ConfigLexerInit() { + staticData := &ConfigLexerLexerStaticData + staticData.once.Do(configlexerLexerInit) +} + +// NewConfigLexer produces a new lexer instance for the optional input antlr.CharStream. +func NewConfigLexer(input antlr.CharStream) *ConfigLexer { + ConfigLexerInit() + l := new(ConfigLexer) + l.BaseLexer = antlr.NewBaseLexer(input) + staticData := &ConfigLexerLexerStaticData + l.Interpreter = antlr.NewLexerATNSimulator(l, staticData.atn, staticData.decisionToDFA, staticData.PredictionContextCache) + l.channelNames = staticData.ChannelNames + l.modeNames = staticData.ModeNames + l.RuleNames = staticData.RuleNames + l.LiteralNames = staticData.LiteralNames + l.SymbolicNames = staticData.SymbolicNames + l.GrammarFileName = "Config.g4" + // TODO: l.EOF = antlr.TokenEOF + + return l +} + +// ConfigLexer tokens. +const ( + ConfigLexerHASH = 1 + ConfigLexerWHITESPACE = 2 + ConfigLexerSTRING = 3 + ConfigLexerNEWLINE = 4 +) diff --git a/handlers/ssh_config/ast/parser/config_listener.go b/handlers/ssh_config/ast/parser/config_listener.go new file mode 100644 index 0000000..0384e3c --- /dev/null +++ b/handlers/ssh_config/ast/parser/config_listener.go @@ -0,0 +1,46 @@ +// Code generated from Config.g4 by ANTLR 4.13.0. DO NOT EDIT. + +package parser // Config + +import "github.com/antlr4-go/antlr/v4" + +// ConfigListener is a complete listener for a parse tree produced by ConfigParser. +type ConfigListener interface { + antlr.ParseTreeListener + + // EnterLineStatement is called when entering the lineStatement production. + EnterLineStatement(c *LineStatementContext) + + // EnterEntry is called when entering the entry production. + EnterEntry(c *EntryContext) + + // EnterSeparator is called when entering the separator production. + EnterSeparator(c *SeparatorContext) + + // EnterKey is called when entering the key production. + EnterKey(c *KeyContext) + + // EnterValue is called when entering the value production. + EnterValue(c *ValueContext) + + // EnterLeadingComment is called when entering the leadingComment production. + EnterLeadingComment(c *LeadingCommentContext) + + // ExitLineStatement is called when exiting the lineStatement production. + ExitLineStatement(c *LineStatementContext) + + // ExitEntry is called when exiting the entry production. + ExitEntry(c *EntryContext) + + // ExitSeparator is called when exiting the separator production. + ExitSeparator(c *SeparatorContext) + + // ExitKey is called when exiting the key production. + ExitKey(c *KeyContext) + + // ExitValue is called when exiting the value production. + ExitValue(c *ValueContext) + + // ExitLeadingComment is called when exiting the leadingComment production. + ExitLeadingComment(c *LeadingCommentContext) +} diff --git a/handlers/ssh_config/ast/parser/config_parser.go b/handlers/ssh_config/ast/parser/config_parser.go new file mode 100644 index 0000000..018bbb8 --- /dev/null +++ b/handlers/ssh_config/ast/parser/config_parser.go @@ -0,0 +1,1082 @@ +// Code generated from Config.g4 by ANTLR 4.13.0. DO NOT EDIT. + +package parser // Config + +import ( + "fmt" + "strconv" + "sync" + + "github.com/antlr4-go/antlr/v4" +) + +// Suppress unused import errors +var _ = fmt.Printf +var _ = strconv.Itoa +var _ = sync.Once{} + +type ConfigParser struct { + *antlr.BaseParser +} + +var ConfigParserStaticData struct { + once sync.Once + serializedATN []int32 + LiteralNames []string + SymbolicNames []string + RuleNames []string + PredictionContextCache *antlr.PredictionContextCache + atn *antlr.ATN + decisionToDFA []*antlr.DFA +} + +func configParserInit() { + staticData := &ConfigParserStaticData + staticData.LiteralNames = []string{ + "", "'#'", + } + staticData.SymbolicNames = []string{ + "", "HASH", "WHITESPACE", "STRING", "NEWLINE", + } + staticData.RuleNames = []string{ + "lineStatement", "entry", "separator", "key", "value", "leadingComment", + } + staticData.PredictionContextCache = antlr.NewPredictionContextCache() + staticData.serializedATN = []int32{ + 4, 1, 4, 66, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, + 2, 5, 7, 5, 1, 0, 1, 0, 1, 0, 3, 0, 16, 8, 0, 3, 0, 18, 8, 0, 1, 0, 1, + 0, 1, 1, 3, 1, 23, 8, 1, 1, 1, 3, 1, 26, 8, 1, 1, 1, 3, 1, 29, 8, 1, 1, + 1, 3, 1, 32, 8, 1, 1, 1, 3, 1, 35, 8, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, + 1, 4, 5, 4, 43, 8, 4, 10, 4, 12, 4, 46, 9, 4, 1, 4, 3, 4, 49, 8, 4, 1, + 4, 3, 4, 52, 8, 4, 1, 5, 1, 5, 3, 5, 56, 8, 5, 1, 5, 1, 5, 3, 5, 60, 8, + 5, 4, 5, 62, 8, 5, 11, 5, 12, 5, 63, 1, 5, 0, 0, 6, 0, 2, 4, 6, 8, 10, + 0, 0, 73, 0, 17, 1, 0, 0, 0, 2, 22, 1, 0, 0, 0, 4, 36, 1, 0, 0, 0, 6, 38, + 1, 0, 0, 0, 8, 44, 1, 0, 0, 0, 10, 53, 1, 0, 0, 0, 12, 18, 3, 2, 1, 0, + 13, 18, 3, 10, 5, 0, 14, 16, 5, 2, 0, 0, 15, 14, 1, 0, 0, 0, 15, 16, 1, + 0, 0, 0, 16, 18, 1, 0, 0, 0, 17, 12, 1, 0, 0, 0, 17, 13, 1, 0, 0, 0, 17, + 15, 1, 0, 0, 0, 18, 19, 1, 0, 0, 0, 19, 20, 5, 0, 0, 1, 20, 1, 1, 0, 0, + 0, 21, 23, 5, 2, 0, 0, 22, 21, 1, 0, 0, 0, 22, 23, 1, 0, 0, 0, 23, 25, + 1, 0, 0, 0, 24, 26, 3, 6, 3, 0, 25, 24, 1, 0, 0, 0, 25, 26, 1, 0, 0, 0, + 26, 28, 1, 0, 0, 0, 27, 29, 3, 4, 2, 0, 28, 27, 1, 0, 0, 0, 28, 29, 1, + 0, 0, 0, 29, 31, 1, 0, 0, 0, 30, 32, 3, 8, 4, 0, 31, 30, 1, 0, 0, 0, 31, + 32, 1, 0, 0, 0, 32, 34, 1, 0, 0, 0, 33, 35, 3, 10, 5, 0, 34, 33, 1, 0, + 0, 0, 34, 35, 1, 0, 0, 0, 35, 3, 1, 0, 0, 0, 36, 37, 5, 2, 0, 0, 37, 5, + 1, 0, 0, 0, 38, 39, 5, 3, 0, 0, 39, 7, 1, 0, 0, 0, 40, 41, 5, 3, 0, 0, + 41, 43, 5, 2, 0, 0, 42, 40, 1, 0, 0, 0, 43, 46, 1, 0, 0, 0, 44, 42, 1, + 0, 0, 0, 44, 45, 1, 0, 0, 0, 45, 48, 1, 0, 0, 0, 46, 44, 1, 0, 0, 0, 47, + 49, 5, 3, 0, 0, 48, 47, 1, 0, 0, 0, 48, 49, 1, 0, 0, 0, 49, 51, 1, 0, 0, + 0, 50, 52, 5, 2, 0, 0, 51, 50, 1, 0, 0, 0, 51, 52, 1, 0, 0, 0, 52, 9, 1, + 0, 0, 0, 53, 55, 5, 1, 0, 0, 54, 56, 5, 2, 0, 0, 55, 54, 1, 0, 0, 0, 55, + 56, 1, 0, 0, 0, 56, 61, 1, 0, 0, 0, 57, 59, 5, 3, 0, 0, 58, 60, 5, 2, 0, + 0, 59, 58, 1, 0, 0, 0, 59, 60, 1, 0, 0, 0, 60, 62, 1, 0, 0, 0, 61, 57, + 1, 0, 0, 0, 62, 63, 1, 0, 0, 0, 63, 61, 1, 0, 0, 0, 63, 64, 1, 0, 0, 0, + 64, 11, 1, 0, 0, 0, 13, 15, 17, 22, 25, 28, 31, 34, 44, 48, 51, 55, 59, + 63, + } + deserializer := antlr.NewATNDeserializer(nil) + staticData.atn = deserializer.Deserialize(staticData.serializedATN) + atn := staticData.atn + staticData.decisionToDFA = make([]*antlr.DFA, len(atn.DecisionToState)) + decisionToDFA := staticData.decisionToDFA + for index, state := range atn.DecisionToState { + decisionToDFA[index] = antlr.NewDFA(state, index) + } +} + +// ConfigParserInit initializes any static state used to implement ConfigParser. By default the +// static state used to implement the parser is lazily initialized during the first call to +// NewConfigParser(). You can call this function if you wish to initialize the static state ahead +// of time. +func ConfigParserInit() { + staticData := &ConfigParserStaticData + staticData.once.Do(configParserInit) +} + +// NewConfigParser produces a new parser instance for the optional input antlr.TokenStream. +func NewConfigParser(input antlr.TokenStream) *ConfigParser { + ConfigParserInit() + this := new(ConfigParser) + this.BaseParser = antlr.NewBaseParser(input) + staticData := &ConfigParserStaticData + this.Interpreter = antlr.NewParserATNSimulator(this, staticData.atn, staticData.decisionToDFA, staticData.PredictionContextCache) + this.RuleNames = staticData.RuleNames + this.LiteralNames = staticData.LiteralNames + this.SymbolicNames = staticData.SymbolicNames + this.GrammarFileName = "Config.g4" + + return this +} + +// ConfigParser tokens. +const ( + ConfigParserEOF = antlr.TokenEOF + ConfigParserHASH = 1 + ConfigParserWHITESPACE = 2 + ConfigParserSTRING = 3 + ConfigParserNEWLINE = 4 +) + +// ConfigParser rules. +const ( + ConfigParserRULE_lineStatement = 0 + ConfigParserRULE_entry = 1 + ConfigParserRULE_separator = 2 + ConfigParserRULE_key = 3 + ConfigParserRULE_value = 4 + ConfigParserRULE_leadingComment = 5 +) + +// ILineStatementContext is an interface to support dynamic dispatch. +type ILineStatementContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + + // Getter signatures + EOF() antlr.TerminalNode + Entry() IEntryContext + LeadingComment() ILeadingCommentContext + WHITESPACE() antlr.TerminalNode + + // IsLineStatementContext differentiates from other interfaces. + IsLineStatementContext() +} + +type LineStatementContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptyLineStatementContext() *LineStatementContext { + var p = new(LineStatementContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_lineStatement + return p +} + +func InitEmptyLineStatementContext(p *LineStatementContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_lineStatement +} + +func (*LineStatementContext) IsLineStatementContext() {} + +func NewLineStatementContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *LineStatementContext { + var p = new(LineStatementContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = ConfigParserRULE_lineStatement + + return p +} + +func (s *LineStatementContext) GetParser() antlr.Parser { return s.parser } + +func (s *LineStatementContext) EOF() antlr.TerminalNode { + return s.GetToken(ConfigParserEOF, 0) +} + +func (s *LineStatementContext) Entry() IEntryContext { + var t antlr.RuleContext + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(IEntryContext); ok { + t = ctx.(antlr.RuleContext) + break + } + } + + if t == nil { + return nil + } + + return t.(IEntryContext) +} + +func (s *LineStatementContext) LeadingComment() ILeadingCommentContext { + var t antlr.RuleContext + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(ILeadingCommentContext); ok { + t = ctx.(antlr.RuleContext) + break + } + } + + if t == nil { + return nil + } + + return t.(ILeadingCommentContext) +} + +func (s *LineStatementContext) WHITESPACE() antlr.TerminalNode { + return s.GetToken(ConfigParserWHITESPACE, 0) +} + +func (s *LineStatementContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *LineStatementContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +func (s *LineStatementContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.EnterLineStatement(s) + } +} + +func (s *LineStatementContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.ExitLineStatement(s) + } +} + +func (p *ConfigParser) LineStatement() (localctx ILineStatementContext) { + localctx = NewLineStatementContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 0, ConfigParserRULE_lineStatement) + var _la int + + p.EnterOuterAlt(localctx, 1) + p.SetState(17) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + + switch p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 1, p.GetParserRuleContext()) { + case 1: + { + p.SetState(12) + p.Entry() + } + + case 2: + { + p.SetState(13) + p.LeadingComment() + } + + case 3: + p.SetState(15) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + if _la == ConfigParserWHITESPACE { + { + p.SetState(14) + p.Match(ConfigParserWHITESPACE) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + + } + + case antlr.ATNInvalidAltNumber: + goto errorExit + } + { + p.SetState(19) + p.Match(ConfigParserEOF) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} + +// IEntryContext is an interface to support dynamic dispatch. +type IEntryContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + + // Getter signatures + WHITESPACE() antlr.TerminalNode + Key() IKeyContext + Separator() ISeparatorContext + Value() IValueContext + LeadingComment() ILeadingCommentContext + + // IsEntryContext differentiates from other interfaces. + IsEntryContext() +} + +type EntryContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptyEntryContext() *EntryContext { + var p = new(EntryContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_entry + return p +} + +func InitEmptyEntryContext(p *EntryContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_entry +} + +func (*EntryContext) IsEntryContext() {} + +func NewEntryContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *EntryContext { + var p = new(EntryContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = ConfigParserRULE_entry + + return p +} + +func (s *EntryContext) GetParser() antlr.Parser { return s.parser } + +func (s *EntryContext) WHITESPACE() antlr.TerminalNode { + return s.GetToken(ConfigParserWHITESPACE, 0) +} + +func (s *EntryContext) Key() IKeyContext { + var t antlr.RuleContext + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(IKeyContext); ok { + t = ctx.(antlr.RuleContext) + break + } + } + + if t == nil { + return nil + } + + return t.(IKeyContext) +} + +func (s *EntryContext) Separator() ISeparatorContext { + var t antlr.RuleContext + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(ISeparatorContext); ok { + t = ctx.(antlr.RuleContext) + break + } + } + + if t == nil { + return nil + } + + return t.(ISeparatorContext) +} + +func (s *EntryContext) Value() IValueContext { + var t antlr.RuleContext + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(IValueContext); ok { + t = ctx.(antlr.RuleContext) + break + } + } + + if t == nil { + return nil + } + + return t.(IValueContext) +} + +func (s *EntryContext) LeadingComment() ILeadingCommentContext { + var t antlr.RuleContext + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(ILeadingCommentContext); ok { + t = ctx.(antlr.RuleContext) + break + } + } + + if t == nil { + return nil + } + + return t.(ILeadingCommentContext) +} + +func (s *EntryContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *EntryContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +func (s *EntryContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.EnterEntry(s) + } +} + +func (s *EntryContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.ExitEntry(s) + } +} + +func (p *ConfigParser) Entry() (localctx IEntryContext) { + localctx = NewEntryContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 2, ConfigParserRULE_entry) + var _la int + + p.EnterOuterAlt(localctx, 1) + p.SetState(22) + p.GetErrorHandler().Sync(p) + + if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 2, p.GetParserRuleContext()) == 1 { + { + p.SetState(21) + p.Match(ConfigParserWHITESPACE) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + + } else if p.HasError() { // JIM + goto errorExit + } + p.SetState(25) + p.GetErrorHandler().Sync(p) + + if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 3, p.GetParserRuleContext()) == 1 { + { + p.SetState(24) + p.Key() + } + + } else if p.HasError() { // JIM + goto errorExit + } + p.SetState(28) + p.GetErrorHandler().Sync(p) + + if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 4, p.GetParserRuleContext()) == 1 { + { + p.SetState(27) + p.Separator() + } + + } else if p.HasError() { // JIM + goto errorExit + } + p.SetState(31) + p.GetErrorHandler().Sync(p) + + if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 5, p.GetParserRuleContext()) == 1 { + { + p.SetState(30) + p.Value() + } + + } else if p.HasError() { // JIM + goto errorExit + } + p.SetState(34) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + if _la == ConfigParserHASH { + { + p.SetState(33) + p.LeadingComment() + } + + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} + +// ISeparatorContext is an interface to support dynamic dispatch. +type ISeparatorContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + + // Getter signatures + WHITESPACE() antlr.TerminalNode + + // IsSeparatorContext differentiates from other interfaces. + IsSeparatorContext() +} + +type SeparatorContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptySeparatorContext() *SeparatorContext { + var p = new(SeparatorContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_separator + return p +} + +func InitEmptySeparatorContext(p *SeparatorContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_separator +} + +func (*SeparatorContext) IsSeparatorContext() {} + +func NewSeparatorContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *SeparatorContext { + var p = new(SeparatorContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = ConfigParserRULE_separator + + return p +} + +func (s *SeparatorContext) GetParser() antlr.Parser { return s.parser } + +func (s *SeparatorContext) WHITESPACE() antlr.TerminalNode { + return s.GetToken(ConfigParserWHITESPACE, 0) +} + +func (s *SeparatorContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *SeparatorContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +func (s *SeparatorContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.EnterSeparator(s) + } +} + +func (s *SeparatorContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.ExitSeparator(s) + } +} + +func (p *ConfigParser) Separator() (localctx ISeparatorContext) { + localctx = NewSeparatorContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 4, ConfigParserRULE_separator) + p.EnterOuterAlt(localctx, 1) + { + p.SetState(36) + p.Match(ConfigParserWHITESPACE) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} + +// IKeyContext is an interface to support dynamic dispatch. +type IKeyContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + + // Getter signatures + STRING() antlr.TerminalNode + + // IsKeyContext differentiates from other interfaces. + IsKeyContext() +} + +type KeyContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptyKeyContext() *KeyContext { + var p = new(KeyContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_key + return p +} + +func InitEmptyKeyContext(p *KeyContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_key +} + +func (*KeyContext) IsKeyContext() {} + +func NewKeyContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *KeyContext { + var p = new(KeyContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = ConfigParserRULE_key + + return p +} + +func (s *KeyContext) GetParser() antlr.Parser { return s.parser } + +func (s *KeyContext) STRING() antlr.TerminalNode { + return s.GetToken(ConfigParserSTRING, 0) +} + +func (s *KeyContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *KeyContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +func (s *KeyContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.EnterKey(s) + } +} + +func (s *KeyContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.ExitKey(s) + } +} + +func (p *ConfigParser) Key() (localctx IKeyContext) { + localctx = NewKeyContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 6, ConfigParserRULE_key) + p.EnterOuterAlt(localctx, 1) + { + p.SetState(38) + p.Match(ConfigParserSTRING) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} + +// IValueContext is an interface to support dynamic dispatch. +type IValueContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + + // Getter signatures + AllSTRING() []antlr.TerminalNode + STRING(i int) antlr.TerminalNode + AllWHITESPACE() []antlr.TerminalNode + WHITESPACE(i int) antlr.TerminalNode + + // IsValueContext differentiates from other interfaces. + IsValueContext() +} + +type ValueContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptyValueContext() *ValueContext { + var p = new(ValueContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_value + return p +} + +func InitEmptyValueContext(p *ValueContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_value +} + +func (*ValueContext) IsValueContext() {} + +func NewValueContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *ValueContext { + var p = new(ValueContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = ConfigParserRULE_value + + return p +} + +func (s *ValueContext) GetParser() antlr.Parser { return s.parser } + +func (s *ValueContext) AllSTRING() []antlr.TerminalNode { + return s.GetTokens(ConfigParserSTRING) +} + +func (s *ValueContext) STRING(i int) antlr.TerminalNode { + return s.GetToken(ConfigParserSTRING, i) +} + +func (s *ValueContext) AllWHITESPACE() []antlr.TerminalNode { + return s.GetTokens(ConfigParserWHITESPACE) +} + +func (s *ValueContext) WHITESPACE(i int) antlr.TerminalNode { + return s.GetToken(ConfigParserWHITESPACE, i) +} + +func (s *ValueContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *ValueContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +func (s *ValueContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.EnterValue(s) + } +} + +func (s *ValueContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.ExitValue(s) + } +} + +func (p *ConfigParser) Value() (localctx IValueContext) { + localctx = NewValueContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 8, ConfigParserRULE_value) + var _la int + + var _alt int + + p.EnterOuterAlt(localctx, 1) + p.SetState(44) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _alt = p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 7, p.GetParserRuleContext()) + if p.HasError() { + goto errorExit + } + for _alt != 2 && _alt != antlr.ATNInvalidAltNumber { + if _alt == 1 { + { + p.SetState(40) + p.Match(ConfigParserSTRING) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + { + p.SetState(41) + p.Match(ConfigParserWHITESPACE) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + + } + p.SetState(46) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _alt = p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 7, p.GetParserRuleContext()) + if p.HasError() { + goto errorExit + } + } + p.SetState(48) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + if _la == ConfigParserSTRING { + { + p.SetState(47) + p.Match(ConfigParserSTRING) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + + } + p.SetState(51) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + if _la == ConfigParserWHITESPACE { + { + p.SetState(50) + p.Match(ConfigParserWHITESPACE) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} + +// ILeadingCommentContext is an interface to support dynamic dispatch. +type ILeadingCommentContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + + // Getter signatures + HASH() antlr.TerminalNode + AllWHITESPACE() []antlr.TerminalNode + WHITESPACE(i int) antlr.TerminalNode + AllSTRING() []antlr.TerminalNode + STRING(i int) antlr.TerminalNode + + // IsLeadingCommentContext differentiates from other interfaces. + IsLeadingCommentContext() +} + +type LeadingCommentContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptyLeadingCommentContext() *LeadingCommentContext { + var p = new(LeadingCommentContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_leadingComment + return p +} + +func InitEmptyLeadingCommentContext(p *LeadingCommentContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_leadingComment +} + +func (*LeadingCommentContext) IsLeadingCommentContext() {} + +func NewLeadingCommentContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *LeadingCommentContext { + var p = new(LeadingCommentContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = ConfigParserRULE_leadingComment + + return p +} + +func (s *LeadingCommentContext) GetParser() antlr.Parser { return s.parser } + +func (s *LeadingCommentContext) HASH() antlr.TerminalNode { + return s.GetToken(ConfigParserHASH, 0) +} + +func (s *LeadingCommentContext) AllWHITESPACE() []antlr.TerminalNode { + return s.GetTokens(ConfigParserWHITESPACE) +} + +func (s *LeadingCommentContext) WHITESPACE(i int) antlr.TerminalNode { + return s.GetToken(ConfigParserWHITESPACE, i) +} + +func (s *LeadingCommentContext) AllSTRING() []antlr.TerminalNode { + return s.GetTokens(ConfigParserSTRING) +} + +func (s *LeadingCommentContext) STRING(i int) antlr.TerminalNode { + return s.GetToken(ConfigParserSTRING, i) +} + +func (s *LeadingCommentContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *LeadingCommentContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +func (s *LeadingCommentContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.EnterLeadingComment(s) + } +} + +func (s *LeadingCommentContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.ExitLeadingComment(s) + } +} + +func (p *ConfigParser) LeadingComment() (localctx ILeadingCommentContext) { + localctx = NewLeadingCommentContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 10, ConfigParserRULE_leadingComment) + var _la int + + p.EnterOuterAlt(localctx, 1) + { + p.SetState(53) + p.Match(ConfigParserHASH) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + p.SetState(55) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + if _la == ConfigParserWHITESPACE { + { + p.SetState(54) + p.Match(ConfigParserWHITESPACE) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + + } + p.SetState(61) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + for ok := true; ok; ok = _la == ConfigParserSTRING { + { + p.SetState(57) + p.Match(ConfigParserSTRING) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + p.SetState(59) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + if _la == ConfigParserWHITESPACE { + { + p.SetState(58) + p.Match(ConfigParserWHITESPACE) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + + } + + p.SetState(63) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} diff --git a/handlers/ssh_config/ast/ssh_config.go b/handlers/ssh_config/ast/ssh_config.go new file mode 100644 index 0000000..fb15e51 --- /dev/null +++ b/handlers/ssh_config/ast/ssh_config.go @@ -0,0 +1,62 @@ +package ast + +import ( + "config-lsp/common" + commonparser "config-lsp/common/parser" + matchparser "config-lsp/handlers/sshd_config/fields/match-parser" + "github.com/emirpasic/gods/maps/treemap" +) + +type SSHKey struct { + common.LocationRange + Value commonparser.ParsedString + Key string +} + +type SSHSeparator struct { + common.LocationRange + Value commonparser.ParsedString +} + +type SSHValue struct { + common.LocationRange + Value commonparser.ParsedString +} + +type SSHOption struct { + common.LocationRange + Value commonparser.ParsedString + + Key *SSHKey + Separator *SSHSeparator + OptionValue *SSHValue +} + +type SSHMatchBlock struct { + common.LocationRange + MatchOption *SSHOption + MatchValue *matchparser.Match + + // [uint32]*SSHOption -> line number -> *SSHOption + Options *treemap.Map +} + +type SSHHostBlock struct { + common.LocationRange + HostOption *SSHOption + HostValue string + + // [uint32]*SSHOption -> line number -> *SSHOption + Others *treemap.Map +} + +type SSHConfig struct { + // [uint32]SSHOption -> line number -> *SSHEntry + RootOptions *treemap.Map + + MatchBlosks []*SSHMatchBlock + HostBlocks []*SSHHostBlock + + // [uint32]{} -> line number -> {} + CommentLines map[uint32]struct{} +} diff --git a/handlers/ssh_config/ast/ssh_config_fields.go b/handlers/ssh_config/ast/ssh_config_fields.go new file mode 100644 index 0000000..bd41296 --- /dev/null +++ b/handlers/ssh_config/ast/ssh_config_fields.go @@ -0,0 +1 @@ +package ast diff --git a/handlers/sshd_config/Config.g4 b/handlers/sshd_config/Config.g4 index ad4cbe8..3033862 100644 --- a/handlers/sshd_config/Config.g4 +++ b/handlers/sshd_config/Config.g4 @@ -13,17 +13,23 @@ separator ; key - : STRING + : string ; value - : (STRING WHITESPACE)* STRING? WHITESPACE? + : (string WHITESPACE)* string? WHITESPACE? ; leadingComment - : HASH WHITESPACE? (STRING WHITESPACE?)+ + : HASH WHITESPACE? (string WHITESPACE?)+ ; +string + : (QUOTED_STRING | STRING) + ; + +/////////////////////////////////////////////// + HASH : '#' ; @@ -33,9 +39,13 @@ WHITESPACE ; STRING - : ~(' ' | '\t' | '\r' | '\n' | '#')+ + : ~('#' | '\r' | '\n' | '"' | ' ' | '\t')+ ; NEWLINE : '\r'? '\n' ; + +QUOTED_STRING + : '"' WHITESPACE? (STRING WHITESPACE)* STRING? ('"')? + ; diff --git a/handlers/sshd_config/analyzer/analyzer.go b/handlers/sshd_config/analyzer/analyzer.go index 571d548..ffb15b9 100644 --- a/handlers/sshd_config/analyzer/analyzer.go +++ b/handlers/sshd_config/analyzer/analyzer.go @@ -12,7 +12,7 @@ import ( func Analyze( d *sshdconfig.SSHDocument, ) []protocol.Diagnostic { - errors := analyzeOptionsAreValid(d) + errors := analyzeStructureIsValid(d) if len(errors) > 0 { return errsToDiagnostics(errors) diff --git a/handlers/sshd_config/analyzer/options.go b/handlers/sshd_config/analyzer/options.go index b6b07a1..1b3eba7 100644 --- a/handlers/sshd_config/analyzer/options.go +++ b/handlers/sshd_config/analyzer/options.go @@ -11,7 +11,7 @@ import ( "fmt" ) -func analyzeOptionsAreValid( +func analyzeStructureIsValid( d *sshdconfig.SSHDocument, ) []common.LSPError { errs := make([]common.LSPError, 0) @@ -39,48 +39,66 @@ func checkOption( ) []common.LSPError { errs := make([]common.LSPError, 0) - if option.Key != nil { - docOption, found := fields.Options[option.Key.Key] + if option.Key == nil { + return errs + } - if !found { - errs = append(errs, common.LSPError{ - Range: option.Key.LocationRange, - Err: errors.New(fmt.Sprintf("Unknown option: %s", option.Key.Key)), - }) + errs = append(errs, checkIsUsingDoubleQuotes(option.Key.Value, option.Key.LocationRange)...) + errs = append(errs, checkQuotesAreClosed(option.Key.Value, option.Key.LocationRange)...) - return errs - } + docOption, found := fields.Options[option.Key.Key] - if _, found := fields.MatchAllowedOptions[option.Key.Key]; !found && isInMatchBlock { - errs = append(errs, common.LSPError{ - Range: option.Key.LocationRange, - Err: errors.New(fmt.Sprintf("Option '%s' is not allowed inside Match blocks", option.Key.Key)), - }) + if !found { + errs = append(errs, common.LSPError{ + Range: option.Key.LocationRange, + Err: errors.New(fmt.Sprintf("Unknown option: %s", option.Key.Key)), + }) - return errs - } + return errs + } - if option.OptionValue == nil || option.OptionValue.Value.Value == "" { - errs = append(errs, common.LSPError{ - Range: option.Key.LocationRange, - Err: errors.New(fmt.Sprintf("Option '%s' requires a value", option.Key.Key)), - }) - } else { - invalidValues := docOption.CheckIsValid(option.OptionValue.Value.Value) + if _, found := fields.MatchAllowedOptions[option.Key.Key]; !found && isInMatchBlock { + errs = append(errs, common.LSPError{ + Range: option.Key.LocationRange, + Err: errors.New(fmt.Sprintf("Option '%s' is not allowed inside Match blocks", option.Key.Key)), + }) - errs = append( - errs, - utils.Map( - invalidValues, - func(invalidValue *docvalues.InvalidValue) common.LSPError { - err := docvalues.LSPErrorFromInvalidValue(option.Start.Line, *invalidValue) - err.ShiftCharacter(option.OptionValue.Start.Character) + return errs + } - return err - }, - )..., - ) - } + if option.OptionValue == nil || option.OptionValue.Value.Value == "" { + errs = append(errs, common.LSPError{ + Range: option.Key.LocationRange, + Err: errors.New(fmt.Sprintf("Option '%s' requires a value", option.Key.Key)), + }) + } else { + errs = append(errs, checkIsUsingDoubleQuotes(option.OptionValue.Value, option.OptionValue.LocationRange)...) + errs = append(errs, checkQuotesAreClosed(option.OptionValue.Value, option.OptionValue.LocationRange)...) + + invalidValues := docOption.CheckIsValid(option.OptionValue.Value.Value) + + errs = append( + errs, + utils.Map( + invalidValues, + func(invalidValue *docvalues.InvalidValue) common.LSPError { + err := docvalues.LSPErrorFromInvalidValue(option.Start.Line, *invalidValue) + err.ShiftCharacter(option.OptionValue.Start.Character) + + return err + }, + )..., + ) + } + + if option.Separator == nil || option.Separator.Value.Value == "" { + errs = append(errs, common.LSPError{ + Range: option.Key.LocationRange, + Err: errors.New(fmt.Sprintf("There should be a separator between an option and its value")), + }) + } else { + errs = append(errs, checkIsUsingDoubleQuotes(option.Separator.Value, option.Separator.LocationRange)...) + errs = append(errs, checkQuotesAreClosed(option.Separator.Value, option.Separator.LocationRange)...) } return errs diff --git a/handlers/sshd_config/analyzer/quotes.go b/handlers/sshd_config/analyzer/quotes.go new file mode 100644 index 0000000..33677c1 --- /dev/null +++ b/handlers/sshd_config/analyzer/quotes.go @@ -0,0 +1,59 @@ +package analyzer + +import ( + "config-lsp/common" + commonparser "config-lsp/common/parser" + sshdconfig "config-lsp/handlers/sshd_config" + "errors" + "strings" +) + +func analyzeQuotesAreValid( + d *sshdconfig.SSHDocument, +) []common.LSPError { + errs := make([]common.LSPError, 0) + + for _, option := range d.Config.GetAllOptions() { + errs = append(errs, checkIsUsingDoubleQuotes(option.Key.Value, option.Key.LocationRange)...) + errs = append(errs, checkIsUsingDoubleQuotes(option.OptionValue.Value, option.OptionValue.LocationRange)...) + + errs = append(errs, checkQuotesAreClosed(option.Key.Value, option.Key.LocationRange)...) + errs = append(errs, checkQuotesAreClosed(option.OptionValue.Value, option.OptionValue.LocationRange)...) + } + + return errs +} + +func checkIsUsingDoubleQuotes( + value commonparser.ParsedString, + valueRange common.LocationRange, +) []common.LSPError { + singleQuotePosition := strings.Index(value.Raw, "'") + + if singleQuotePosition != -1 { + return []common.LSPError{ + { + Range: valueRange, + Err: errors.New("sshd_config does not support single quotes. Use double quotes (\") instead."), + }, + } + } + + return nil +} + +func checkQuotesAreClosed( + value commonparser.ParsedString, + valueRange common.LocationRange, +) []common.LSPError { + if strings.Count(value.Raw, "\"")%2 != 0 { + return []common.LSPError{ + { + Range: valueRange, + Err: errors.New("There are unclosed quotes here. Make sure all quotes are closed."), + }, + } + } + + return nil +} diff --git a/handlers/sshd_config/analyzer/quotes_test.go b/handlers/sshd_config/analyzer/quotes_test.go new file mode 100644 index 0000000..ba9ff55 --- /dev/null +++ b/handlers/sshd_config/analyzer/quotes_test.go @@ -0,0 +1,62 @@ +package analyzer + +import ( + testutils_test "config-lsp/handlers/sshd_config/test_utils" + "testing" +) + +func TestSimpleInvalidQuotesExample( + t *testing.T, +) { + d := testutils_test.DocumentFromInput(t, ` +PermitRootLogin 'yes' +`) + + errors := analyzeQuotesAreValid(d) + + if !(len(errors) == 1) { + t.Errorf("Expected 1 error, got %v", len(errors)) + } +} + +func TestSingleQuotesKeyAndOptionExample( + t *testing.T, +) { + d := testutils_test.DocumentFromInput(t, ` +'Port' '22' +`) + + errors := analyzeQuotesAreValid(d) + + if !(len(errors) == 2) { + t.Errorf("Expected 2 errors, got %v", len(errors)) + } +} + +func TestSimpleUnclosedQuoteExample( + t *testing.T, +) { + d := testutils_test.DocumentFromInput(t, ` +PermitRootLogin "yes +`) + + errors := analyzeQuotesAreValid(d) + + if !(len(errors) == 1) { + t.Errorf("Expected 1 error, got %v", len(errors)) + } +} + +func TestIncompleteQuotesExample( + t *testing.T, +) { + d := testutils_test.DocumentFromInput(t, ` +"Port +`) + + errors := analyzeQuotesAreValid(d) + + if !(len(errors) == 1) { + t.Errorf("Expected 1 error, got %v", len(errors)) + } +} diff --git a/handlers/sshd_config/ast/listener.go b/handlers/sshd_config/ast/listener.go index aa744d8..d41e6a6 100644 --- a/handlers/sshd_config/ast/listener.go +++ b/handlers/sshd_config/ast/listener.go @@ -84,8 +84,12 @@ func (s *sshParserListener) EnterSeparator(ctx *parser.SeparatorContext) { location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext) location.ChangeBothLines(s.sshContext.line) + text := ctx.GetText() + value := commonparser.ParseRawString(text, commonparser.FullFeatures) + s.sshContext.currentOption.Separator = &SSHDSeparator{ LocationRange: location, + Value: value, } } diff --git a/handlers/sshd_config/ast/parser/Config.interp b/handlers/sshd_config/ast/parser/Config.interp index 2832f42..e02ab96 100644 --- a/handlers/sshd_config/ast/parser/Config.interp +++ b/handlers/sshd_config/ast/parser/Config.interp @@ -4,6 +4,7 @@ null null null null +null token symbolic names: null @@ -11,6 +12,7 @@ HASH WHITESPACE STRING NEWLINE +QUOTED_STRING rule names: lineStatement @@ -19,7 +21,8 @@ separator key value leadingComment +string atn: -[4, 1, 4, 66, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 2, 5, 7, 5, 1, 0, 1, 0, 1, 0, 3, 0, 16, 8, 0, 3, 0, 18, 8, 0, 1, 0, 1, 0, 1, 1, 3, 1, 23, 8, 1, 1, 1, 3, 1, 26, 8, 1, 1, 1, 3, 1, 29, 8, 1, 1, 1, 3, 1, 32, 8, 1, 1, 1, 3, 1, 35, 8, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, 1, 4, 5, 4, 43, 8, 4, 10, 4, 12, 4, 46, 9, 4, 1, 4, 3, 4, 49, 8, 4, 1, 4, 3, 4, 52, 8, 4, 1, 5, 1, 5, 3, 5, 56, 8, 5, 1, 5, 1, 5, 3, 5, 60, 8, 5, 4, 5, 62, 8, 5, 11, 5, 12, 5, 63, 1, 5, 0, 0, 6, 0, 2, 4, 6, 8, 10, 0, 0, 73, 0, 17, 1, 0, 0, 0, 2, 22, 1, 0, 0, 0, 4, 36, 1, 0, 0, 0, 6, 38, 1, 0, 0, 0, 8, 44, 1, 0, 0, 0, 10, 53, 1, 0, 0, 0, 12, 18, 3, 2, 1, 0, 13, 18, 3, 10, 5, 0, 14, 16, 5, 2, 0, 0, 15, 14, 1, 0, 0, 0, 15, 16, 1, 0, 0, 0, 16, 18, 1, 0, 0, 0, 17, 12, 1, 0, 0, 0, 17, 13, 1, 0, 0, 0, 17, 15, 1, 0, 0, 0, 18, 19, 1, 0, 0, 0, 19, 20, 5, 0, 0, 1, 20, 1, 1, 0, 0, 0, 21, 23, 5, 2, 0, 0, 22, 21, 1, 0, 0, 0, 22, 23, 1, 0, 0, 0, 23, 25, 1, 0, 0, 0, 24, 26, 3, 6, 3, 0, 25, 24, 1, 0, 0, 0, 25, 26, 1, 0, 0, 0, 26, 28, 1, 0, 0, 0, 27, 29, 3, 4, 2, 0, 28, 27, 1, 0, 0, 0, 28, 29, 1, 0, 0, 0, 29, 31, 1, 0, 0, 0, 30, 32, 3, 8, 4, 0, 31, 30, 1, 0, 0, 0, 31, 32, 1, 0, 0, 0, 32, 34, 1, 0, 0, 0, 33, 35, 3, 10, 5, 0, 34, 33, 1, 0, 0, 0, 34, 35, 1, 0, 0, 0, 35, 3, 1, 0, 0, 0, 36, 37, 5, 2, 0, 0, 37, 5, 1, 0, 0, 0, 38, 39, 5, 3, 0, 0, 39, 7, 1, 0, 0, 0, 40, 41, 5, 3, 0, 0, 41, 43, 5, 2, 0, 0, 42, 40, 1, 0, 0, 0, 43, 46, 1, 0, 0, 0, 44, 42, 1, 0, 0, 0, 44, 45, 1, 0, 0, 0, 45, 48, 1, 0, 0, 0, 46, 44, 1, 0, 0, 0, 47, 49, 5, 3, 0, 0, 48, 47, 1, 0, 0, 0, 48, 49, 1, 0, 0, 0, 49, 51, 1, 0, 0, 0, 50, 52, 5, 2, 0, 0, 51, 50, 1, 0, 0, 0, 51, 52, 1, 0, 0, 0, 52, 9, 1, 0, 0, 0, 53, 55, 5, 1, 0, 0, 54, 56, 5, 2, 0, 0, 55, 54, 1, 0, 0, 0, 55, 56, 1, 0, 0, 0, 56, 61, 1, 0, 0, 0, 57, 59, 5, 3, 0, 0, 58, 60, 5, 2, 0, 0, 59, 58, 1, 0, 0, 0, 59, 60, 1, 0, 0, 0, 60, 62, 1, 0, 0, 0, 61, 57, 1, 0, 0, 0, 62, 63, 1, 0, 0, 0, 63, 61, 1, 0, 0, 0, 63, 64, 1, 0, 0, 0, 64, 11, 1, 0, 0, 0, 13, 15, 17, 22, 25, 28, 31, 34, 44, 48, 51, 55, 59, 63] \ No newline at end of file +[4, 1, 5, 71, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 2, 5, 7, 5, 2, 6, 7, 6, 1, 0, 1, 0, 1, 0, 3, 0, 18, 8, 0, 3, 0, 20, 8, 0, 1, 0, 1, 0, 1, 1, 3, 1, 25, 8, 1, 1, 1, 3, 1, 28, 8, 1, 1, 1, 3, 1, 31, 8, 1, 1, 1, 3, 1, 34, 8, 1, 1, 1, 3, 1, 37, 8, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, 1, 4, 1, 4, 5, 4, 46, 8, 4, 10, 4, 12, 4, 49, 9, 4, 1, 4, 3, 4, 52, 8, 4, 1, 4, 3, 4, 55, 8, 4, 1, 5, 1, 5, 3, 5, 59, 8, 5, 1, 5, 1, 5, 3, 5, 63, 8, 5, 4, 5, 65, 8, 5, 11, 5, 12, 5, 66, 1, 6, 1, 6, 1, 6, 0, 0, 7, 0, 2, 4, 6, 8, 10, 12, 0, 1, 2, 0, 3, 3, 5, 5, 77, 0, 19, 1, 0, 0, 0, 2, 24, 1, 0, 0, 0, 4, 38, 1, 0, 0, 0, 6, 40, 1, 0, 0, 0, 8, 47, 1, 0, 0, 0, 10, 56, 1, 0, 0, 0, 12, 68, 1, 0, 0, 0, 14, 20, 3, 2, 1, 0, 15, 20, 3, 10, 5, 0, 16, 18, 5, 2, 0, 0, 17, 16, 1, 0, 0, 0, 17, 18, 1, 0, 0, 0, 18, 20, 1, 0, 0, 0, 19, 14, 1, 0, 0, 0, 19, 15, 1, 0, 0, 0, 19, 17, 1, 0, 0, 0, 20, 21, 1, 0, 0, 0, 21, 22, 5, 0, 0, 1, 22, 1, 1, 0, 0, 0, 23, 25, 5, 2, 0, 0, 24, 23, 1, 0, 0, 0, 24, 25, 1, 0, 0, 0, 25, 27, 1, 0, 0, 0, 26, 28, 3, 6, 3, 0, 27, 26, 1, 0, 0, 0, 27, 28, 1, 0, 0, 0, 28, 30, 1, 0, 0, 0, 29, 31, 3, 4, 2, 0, 30, 29, 1, 0, 0, 0, 30, 31, 1, 0, 0, 0, 31, 33, 1, 0, 0, 0, 32, 34, 3, 8, 4, 0, 33, 32, 1, 0, 0, 0, 33, 34, 1, 0, 0, 0, 34, 36, 1, 0, 0, 0, 35, 37, 3, 10, 5, 0, 36, 35, 1, 0, 0, 0, 36, 37, 1, 0, 0, 0, 37, 3, 1, 0, 0, 0, 38, 39, 5, 2, 0, 0, 39, 5, 1, 0, 0, 0, 40, 41, 3, 12, 6, 0, 41, 7, 1, 0, 0, 0, 42, 43, 3, 12, 6, 0, 43, 44, 5, 2, 0, 0, 44, 46, 1, 0, 0, 0, 45, 42, 1, 0, 0, 0, 46, 49, 1, 0, 0, 0, 47, 45, 1, 0, 0, 0, 47, 48, 1, 0, 0, 0, 48, 51, 1, 0, 0, 0, 49, 47, 1, 0, 0, 0, 50, 52, 3, 12, 6, 0, 51, 50, 1, 0, 0, 0, 51, 52, 1, 0, 0, 0, 52, 54, 1, 0, 0, 0, 53, 55, 5, 2, 0, 0, 54, 53, 1, 0, 0, 0, 54, 55, 1, 0, 0, 0, 55, 9, 1, 0, 0, 0, 56, 58, 5, 1, 0, 0, 57, 59, 5, 2, 0, 0, 58, 57, 1, 0, 0, 0, 58, 59, 1, 0, 0, 0, 59, 64, 1, 0, 0, 0, 60, 62, 3, 12, 6, 0, 61, 63, 5, 2, 0, 0, 62, 61, 1, 0, 0, 0, 62, 63, 1, 0, 0, 0, 63, 65, 1, 0, 0, 0, 64, 60, 1, 0, 0, 0, 65, 66, 1, 0, 0, 0, 66, 64, 1, 0, 0, 0, 66, 67, 1, 0, 0, 0, 67, 11, 1, 0, 0, 0, 68, 69, 7, 0, 0, 0, 69, 13, 1, 0, 0, 0, 13, 17, 19, 24, 27, 30, 33, 36, 47, 51, 54, 58, 62, 66] \ No newline at end of file diff --git a/handlers/sshd_config/ast/parser/Config.tokens b/handlers/sshd_config/ast/parser/Config.tokens index aacc14c..fa8c415 100644 --- a/handlers/sshd_config/ast/parser/Config.tokens +++ b/handlers/sshd_config/ast/parser/Config.tokens @@ -2,4 +2,5 @@ HASH=1 WHITESPACE=2 STRING=3 NEWLINE=4 +QUOTED_STRING=5 '#'=1 diff --git a/handlers/sshd_config/ast/parser/ConfigLexer.interp b/handlers/sshd_config/ast/parser/ConfigLexer.interp index d61e14d..c093cfb 100644 --- a/handlers/sshd_config/ast/parser/ConfigLexer.interp +++ b/handlers/sshd_config/ast/parser/ConfigLexer.interp @@ -4,6 +4,7 @@ null null null null +null token symbolic names: null @@ -11,12 +12,14 @@ HASH WHITESPACE STRING NEWLINE +QUOTED_STRING rule names: HASH WHITESPACE STRING NEWLINE +QUOTED_STRING channel names: DEFAULT_TOKEN_CHANNEL @@ -26,4 +29,4 @@ mode names: DEFAULT_MODE atn: -[4, 0, 4, 26, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 1, 0, 1, 0, 1, 1, 4, 1, 13, 8, 1, 11, 1, 12, 1, 14, 1, 2, 4, 2, 18, 8, 2, 11, 2, 12, 2, 19, 1, 3, 3, 3, 23, 8, 3, 1, 3, 1, 3, 0, 0, 4, 1, 1, 3, 2, 5, 3, 7, 4, 1, 0, 2, 2, 0, 9, 9, 32, 32, 4, 0, 9, 10, 13, 13, 32, 32, 35, 35, 28, 0, 1, 1, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, 5, 1, 0, 0, 0, 0, 7, 1, 0, 0, 0, 1, 9, 1, 0, 0, 0, 3, 12, 1, 0, 0, 0, 5, 17, 1, 0, 0, 0, 7, 22, 1, 0, 0, 0, 9, 10, 5, 35, 0, 0, 10, 2, 1, 0, 0, 0, 11, 13, 7, 0, 0, 0, 12, 11, 1, 0, 0, 0, 13, 14, 1, 0, 0, 0, 14, 12, 1, 0, 0, 0, 14, 15, 1, 0, 0, 0, 15, 4, 1, 0, 0, 0, 16, 18, 8, 1, 0, 0, 17, 16, 1, 0, 0, 0, 18, 19, 1, 0, 0, 0, 19, 17, 1, 0, 0, 0, 19, 20, 1, 0, 0, 0, 20, 6, 1, 0, 0, 0, 21, 23, 5, 13, 0, 0, 22, 21, 1, 0, 0, 0, 22, 23, 1, 0, 0, 0, 23, 24, 1, 0, 0, 0, 24, 25, 5, 10, 0, 0, 25, 8, 1, 0, 0, 0, 4, 0, 14, 19, 22, 0] \ No newline at end of file +[4, 0, 5, 46, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 1, 0, 1, 0, 1, 1, 4, 1, 15, 8, 1, 11, 1, 12, 1, 16, 1, 2, 4, 2, 20, 8, 2, 11, 2, 12, 2, 21, 1, 3, 3, 3, 25, 8, 3, 1, 3, 1, 3, 1, 4, 1, 4, 3, 4, 31, 8, 4, 1, 4, 1, 4, 1, 4, 5, 4, 36, 8, 4, 10, 4, 12, 4, 39, 9, 4, 1, 4, 3, 4, 42, 8, 4, 1, 4, 3, 4, 45, 8, 4, 0, 0, 5, 1, 1, 3, 2, 5, 3, 7, 4, 9, 5, 1, 0, 2, 2, 0, 9, 9, 32, 32, 4, 0, 9, 10, 13, 13, 32, 32, 34, 35, 52, 0, 1, 1, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, 5, 1, 0, 0, 0, 0, 7, 1, 0, 0, 0, 0, 9, 1, 0, 0, 0, 1, 11, 1, 0, 0, 0, 3, 14, 1, 0, 0, 0, 5, 19, 1, 0, 0, 0, 7, 24, 1, 0, 0, 0, 9, 28, 1, 0, 0, 0, 11, 12, 5, 35, 0, 0, 12, 2, 1, 0, 0, 0, 13, 15, 7, 0, 0, 0, 14, 13, 1, 0, 0, 0, 15, 16, 1, 0, 0, 0, 16, 14, 1, 0, 0, 0, 16, 17, 1, 0, 0, 0, 17, 4, 1, 0, 0, 0, 18, 20, 8, 1, 0, 0, 19, 18, 1, 0, 0, 0, 20, 21, 1, 0, 0, 0, 21, 19, 1, 0, 0, 0, 21, 22, 1, 0, 0, 0, 22, 6, 1, 0, 0, 0, 23, 25, 5, 13, 0, 0, 24, 23, 1, 0, 0, 0, 24, 25, 1, 0, 0, 0, 25, 26, 1, 0, 0, 0, 26, 27, 5, 10, 0, 0, 27, 8, 1, 0, 0, 0, 28, 30, 5, 34, 0, 0, 29, 31, 3, 3, 1, 0, 30, 29, 1, 0, 0, 0, 30, 31, 1, 0, 0, 0, 31, 37, 1, 0, 0, 0, 32, 33, 3, 5, 2, 0, 33, 34, 3, 3, 1, 0, 34, 36, 1, 0, 0, 0, 35, 32, 1, 0, 0, 0, 36, 39, 1, 0, 0, 0, 37, 35, 1, 0, 0, 0, 37, 38, 1, 0, 0, 0, 38, 41, 1, 0, 0, 0, 39, 37, 1, 0, 0, 0, 40, 42, 3, 5, 2, 0, 41, 40, 1, 0, 0, 0, 41, 42, 1, 0, 0, 0, 42, 44, 1, 0, 0, 0, 43, 45, 5, 34, 0, 0, 44, 43, 1, 0, 0, 0, 44, 45, 1, 0, 0, 0, 45, 10, 1, 0, 0, 0, 8, 0, 16, 21, 24, 30, 37, 41, 44, 0] \ No newline at end of file diff --git a/handlers/sshd_config/ast/parser/ConfigLexer.tokens b/handlers/sshd_config/ast/parser/ConfigLexer.tokens index aacc14c..fa8c415 100644 --- a/handlers/sshd_config/ast/parser/ConfigLexer.tokens +++ b/handlers/sshd_config/ast/parser/ConfigLexer.tokens @@ -2,4 +2,5 @@ HASH=1 WHITESPACE=2 STRING=3 NEWLINE=4 +QUOTED_STRING=5 '#'=1 diff --git a/handlers/sshd_config/ast/parser/config_base_listener.go b/handlers/sshd_config/ast/parser/config_base_listener.go index ac8bdac..00e7840 100644 --- a/handlers/sshd_config/ast/parser/config_base_listener.go +++ b/handlers/sshd_config/ast/parser/config_base_listener.go @@ -56,3 +56,9 @@ func (s *BaseConfigListener) EnterLeadingComment(ctx *LeadingCommentContext) {} // ExitLeadingComment is called when production leadingComment is exited. func (s *BaseConfigListener) ExitLeadingComment(ctx *LeadingCommentContext) {} + +// EnterString is called when production string is entered. +func (s *BaseConfigListener) EnterString(ctx *StringContext) {} + +// ExitString is called when production string is exited. +func (s *BaseConfigListener) ExitString(ctx *StringContext) {} diff --git a/handlers/sshd_config/ast/parser/config_lexer.go b/handlers/sshd_config/ast/parser/config_lexer.go index ace491d..021f1fc 100644 --- a/handlers/sshd_config/ast/parser/config_lexer.go +++ b/handlers/sshd_config/ast/parser/config_lexer.go @@ -46,25 +46,34 @@ func configlexerLexerInit() { "", "'#'", } staticData.SymbolicNames = []string{ - "", "HASH", "WHITESPACE", "STRING", "NEWLINE", + "", "HASH", "WHITESPACE", "STRING", "NEWLINE", "QUOTED_STRING", } staticData.RuleNames = []string{ - "HASH", "WHITESPACE", "STRING", "NEWLINE", + "HASH", "WHITESPACE", "STRING", "NEWLINE", "QUOTED_STRING", } staticData.PredictionContextCache = antlr.NewPredictionContextCache() staticData.serializedATN = []int32{ - 4, 0, 4, 26, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 1, - 0, 1, 0, 1, 1, 4, 1, 13, 8, 1, 11, 1, 12, 1, 14, 1, 2, 4, 2, 18, 8, 2, - 11, 2, 12, 2, 19, 1, 3, 3, 3, 23, 8, 3, 1, 3, 1, 3, 0, 0, 4, 1, 1, 3, 2, - 5, 3, 7, 4, 1, 0, 2, 2, 0, 9, 9, 32, 32, 4, 0, 9, 10, 13, 13, 32, 32, 35, - 35, 28, 0, 1, 1, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, 5, 1, 0, 0, 0, 0, 7, 1, - 0, 0, 0, 1, 9, 1, 0, 0, 0, 3, 12, 1, 0, 0, 0, 5, 17, 1, 0, 0, 0, 7, 22, - 1, 0, 0, 0, 9, 10, 5, 35, 0, 0, 10, 2, 1, 0, 0, 0, 11, 13, 7, 0, 0, 0, - 12, 11, 1, 0, 0, 0, 13, 14, 1, 0, 0, 0, 14, 12, 1, 0, 0, 0, 14, 15, 1, - 0, 0, 0, 15, 4, 1, 0, 0, 0, 16, 18, 8, 1, 0, 0, 17, 16, 1, 0, 0, 0, 18, - 19, 1, 0, 0, 0, 19, 17, 1, 0, 0, 0, 19, 20, 1, 0, 0, 0, 20, 6, 1, 0, 0, - 0, 21, 23, 5, 13, 0, 0, 22, 21, 1, 0, 0, 0, 22, 23, 1, 0, 0, 0, 23, 24, - 1, 0, 0, 0, 24, 25, 5, 10, 0, 0, 25, 8, 1, 0, 0, 0, 4, 0, 14, 19, 22, 0, + 4, 0, 5, 46, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, + 4, 7, 4, 1, 0, 1, 0, 1, 1, 4, 1, 15, 8, 1, 11, 1, 12, 1, 16, 1, 2, 4, 2, + 20, 8, 2, 11, 2, 12, 2, 21, 1, 3, 3, 3, 25, 8, 3, 1, 3, 1, 3, 1, 4, 1, + 4, 3, 4, 31, 8, 4, 1, 4, 1, 4, 1, 4, 5, 4, 36, 8, 4, 10, 4, 12, 4, 39, + 9, 4, 1, 4, 3, 4, 42, 8, 4, 1, 4, 3, 4, 45, 8, 4, 0, 0, 5, 1, 1, 3, 2, + 5, 3, 7, 4, 9, 5, 1, 0, 2, 2, 0, 9, 9, 32, 32, 4, 0, 9, 10, 13, 13, 32, + 32, 34, 35, 52, 0, 1, 1, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, 5, 1, 0, 0, 0, 0, + 7, 1, 0, 0, 0, 0, 9, 1, 0, 0, 0, 1, 11, 1, 0, 0, 0, 3, 14, 1, 0, 0, 0, + 5, 19, 1, 0, 0, 0, 7, 24, 1, 0, 0, 0, 9, 28, 1, 0, 0, 0, 11, 12, 5, 35, + 0, 0, 12, 2, 1, 0, 0, 0, 13, 15, 7, 0, 0, 0, 14, 13, 1, 0, 0, 0, 15, 16, + 1, 0, 0, 0, 16, 14, 1, 0, 0, 0, 16, 17, 1, 0, 0, 0, 17, 4, 1, 0, 0, 0, + 18, 20, 8, 1, 0, 0, 19, 18, 1, 0, 0, 0, 20, 21, 1, 0, 0, 0, 21, 19, 1, + 0, 0, 0, 21, 22, 1, 0, 0, 0, 22, 6, 1, 0, 0, 0, 23, 25, 5, 13, 0, 0, 24, + 23, 1, 0, 0, 0, 24, 25, 1, 0, 0, 0, 25, 26, 1, 0, 0, 0, 26, 27, 5, 10, + 0, 0, 27, 8, 1, 0, 0, 0, 28, 30, 5, 34, 0, 0, 29, 31, 3, 3, 1, 0, 30, 29, + 1, 0, 0, 0, 30, 31, 1, 0, 0, 0, 31, 37, 1, 0, 0, 0, 32, 33, 3, 5, 2, 0, + 33, 34, 3, 3, 1, 0, 34, 36, 1, 0, 0, 0, 35, 32, 1, 0, 0, 0, 36, 39, 1, + 0, 0, 0, 37, 35, 1, 0, 0, 0, 37, 38, 1, 0, 0, 0, 38, 41, 1, 0, 0, 0, 39, + 37, 1, 0, 0, 0, 40, 42, 3, 5, 2, 0, 41, 40, 1, 0, 0, 0, 41, 42, 1, 0, 0, + 0, 42, 44, 1, 0, 0, 0, 43, 45, 5, 34, 0, 0, 44, 43, 1, 0, 0, 0, 44, 45, + 1, 0, 0, 0, 45, 10, 1, 0, 0, 0, 8, 0, 16, 21, 24, 30, 37, 41, 44, 0, } deserializer := antlr.NewATNDeserializer(nil) staticData.atn = deserializer.Deserialize(staticData.serializedATN) @@ -105,8 +114,9 @@ func NewConfigLexer(input antlr.CharStream) *ConfigLexer { // ConfigLexer tokens. const ( - ConfigLexerHASH = 1 - ConfigLexerWHITESPACE = 2 - ConfigLexerSTRING = 3 - ConfigLexerNEWLINE = 4 + ConfigLexerHASH = 1 + ConfigLexerWHITESPACE = 2 + ConfigLexerSTRING = 3 + ConfigLexerNEWLINE = 4 + ConfigLexerQUOTED_STRING = 5 ) diff --git a/handlers/sshd_config/ast/parser/config_listener.go b/handlers/sshd_config/ast/parser/config_listener.go index 0384e3c..1acf598 100644 --- a/handlers/sshd_config/ast/parser/config_listener.go +++ b/handlers/sshd_config/ast/parser/config_listener.go @@ -26,6 +26,9 @@ type ConfigListener interface { // EnterLeadingComment is called when entering the leadingComment production. EnterLeadingComment(c *LeadingCommentContext) + // EnterString is called when entering the string production. + EnterString(c *StringContext) + // ExitLineStatement is called when exiting the lineStatement production. ExitLineStatement(c *LineStatementContext) @@ -43,4 +46,7 @@ type ConfigListener interface { // ExitLeadingComment is called when exiting the leadingComment production. ExitLeadingComment(c *LeadingCommentContext) + + // ExitString is called when exiting the string production. + ExitString(c *StringContext) } diff --git a/handlers/sshd_config/ast/parser/config_parser.go b/handlers/sshd_config/ast/parser/config_parser.go index 018bbb8..aefb1e3 100644 --- a/handlers/sshd_config/ast/parser/config_parser.go +++ b/handlers/sshd_config/ast/parser/config_parser.go @@ -36,42 +36,44 @@ func configParserInit() { "", "'#'", } staticData.SymbolicNames = []string{ - "", "HASH", "WHITESPACE", "STRING", "NEWLINE", + "", "HASH", "WHITESPACE", "STRING", "NEWLINE", "QUOTED_STRING", } staticData.RuleNames = []string{ "lineStatement", "entry", "separator", "key", "value", "leadingComment", + "string", } staticData.PredictionContextCache = antlr.NewPredictionContextCache() staticData.serializedATN = []int32{ - 4, 1, 4, 66, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, - 2, 5, 7, 5, 1, 0, 1, 0, 1, 0, 3, 0, 16, 8, 0, 3, 0, 18, 8, 0, 1, 0, 1, - 0, 1, 1, 3, 1, 23, 8, 1, 1, 1, 3, 1, 26, 8, 1, 1, 1, 3, 1, 29, 8, 1, 1, - 1, 3, 1, 32, 8, 1, 1, 1, 3, 1, 35, 8, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, - 1, 4, 5, 4, 43, 8, 4, 10, 4, 12, 4, 46, 9, 4, 1, 4, 3, 4, 49, 8, 4, 1, - 4, 3, 4, 52, 8, 4, 1, 5, 1, 5, 3, 5, 56, 8, 5, 1, 5, 1, 5, 3, 5, 60, 8, - 5, 4, 5, 62, 8, 5, 11, 5, 12, 5, 63, 1, 5, 0, 0, 6, 0, 2, 4, 6, 8, 10, - 0, 0, 73, 0, 17, 1, 0, 0, 0, 2, 22, 1, 0, 0, 0, 4, 36, 1, 0, 0, 0, 6, 38, - 1, 0, 0, 0, 8, 44, 1, 0, 0, 0, 10, 53, 1, 0, 0, 0, 12, 18, 3, 2, 1, 0, - 13, 18, 3, 10, 5, 0, 14, 16, 5, 2, 0, 0, 15, 14, 1, 0, 0, 0, 15, 16, 1, - 0, 0, 0, 16, 18, 1, 0, 0, 0, 17, 12, 1, 0, 0, 0, 17, 13, 1, 0, 0, 0, 17, - 15, 1, 0, 0, 0, 18, 19, 1, 0, 0, 0, 19, 20, 5, 0, 0, 1, 20, 1, 1, 0, 0, - 0, 21, 23, 5, 2, 0, 0, 22, 21, 1, 0, 0, 0, 22, 23, 1, 0, 0, 0, 23, 25, - 1, 0, 0, 0, 24, 26, 3, 6, 3, 0, 25, 24, 1, 0, 0, 0, 25, 26, 1, 0, 0, 0, - 26, 28, 1, 0, 0, 0, 27, 29, 3, 4, 2, 0, 28, 27, 1, 0, 0, 0, 28, 29, 1, - 0, 0, 0, 29, 31, 1, 0, 0, 0, 30, 32, 3, 8, 4, 0, 31, 30, 1, 0, 0, 0, 31, - 32, 1, 0, 0, 0, 32, 34, 1, 0, 0, 0, 33, 35, 3, 10, 5, 0, 34, 33, 1, 0, - 0, 0, 34, 35, 1, 0, 0, 0, 35, 3, 1, 0, 0, 0, 36, 37, 5, 2, 0, 0, 37, 5, - 1, 0, 0, 0, 38, 39, 5, 3, 0, 0, 39, 7, 1, 0, 0, 0, 40, 41, 5, 3, 0, 0, - 41, 43, 5, 2, 0, 0, 42, 40, 1, 0, 0, 0, 43, 46, 1, 0, 0, 0, 44, 42, 1, - 0, 0, 0, 44, 45, 1, 0, 0, 0, 45, 48, 1, 0, 0, 0, 46, 44, 1, 0, 0, 0, 47, - 49, 5, 3, 0, 0, 48, 47, 1, 0, 0, 0, 48, 49, 1, 0, 0, 0, 49, 51, 1, 0, 0, - 0, 50, 52, 5, 2, 0, 0, 51, 50, 1, 0, 0, 0, 51, 52, 1, 0, 0, 0, 52, 9, 1, - 0, 0, 0, 53, 55, 5, 1, 0, 0, 54, 56, 5, 2, 0, 0, 55, 54, 1, 0, 0, 0, 55, - 56, 1, 0, 0, 0, 56, 61, 1, 0, 0, 0, 57, 59, 5, 3, 0, 0, 58, 60, 5, 2, 0, - 0, 59, 58, 1, 0, 0, 0, 59, 60, 1, 0, 0, 0, 60, 62, 1, 0, 0, 0, 61, 57, - 1, 0, 0, 0, 62, 63, 1, 0, 0, 0, 63, 61, 1, 0, 0, 0, 63, 64, 1, 0, 0, 0, - 64, 11, 1, 0, 0, 0, 13, 15, 17, 22, 25, 28, 31, 34, 44, 48, 51, 55, 59, - 63, + 4, 1, 5, 71, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, + 2, 5, 7, 5, 2, 6, 7, 6, 1, 0, 1, 0, 1, 0, 3, 0, 18, 8, 0, 3, 0, 20, 8, + 0, 1, 0, 1, 0, 1, 1, 3, 1, 25, 8, 1, 1, 1, 3, 1, 28, 8, 1, 1, 1, 3, 1, + 31, 8, 1, 1, 1, 3, 1, 34, 8, 1, 1, 1, 3, 1, 37, 8, 1, 1, 2, 1, 2, 1, 3, + 1, 3, 1, 4, 1, 4, 1, 4, 5, 4, 46, 8, 4, 10, 4, 12, 4, 49, 9, 4, 1, 4, 3, + 4, 52, 8, 4, 1, 4, 3, 4, 55, 8, 4, 1, 5, 1, 5, 3, 5, 59, 8, 5, 1, 5, 1, + 5, 3, 5, 63, 8, 5, 4, 5, 65, 8, 5, 11, 5, 12, 5, 66, 1, 6, 1, 6, 1, 6, + 0, 0, 7, 0, 2, 4, 6, 8, 10, 12, 0, 1, 2, 0, 3, 3, 5, 5, 77, 0, 19, 1, 0, + 0, 0, 2, 24, 1, 0, 0, 0, 4, 38, 1, 0, 0, 0, 6, 40, 1, 0, 0, 0, 8, 47, 1, + 0, 0, 0, 10, 56, 1, 0, 0, 0, 12, 68, 1, 0, 0, 0, 14, 20, 3, 2, 1, 0, 15, + 20, 3, 10, 5, 0, 16, 18, 5, 2, 0, 0, 17, 16, 1, 0, 0, 0, 17, 18, 1, 0, + 0, 0, 18, 20, 1, 0, 0, 0, 19, 14, 1, 0, 0, 0, 19, 15, 1, 0, 0, 0, 19, 17, + 1, 0, 0, 0, 20, 21, 1, 0, 0, 0, 21, 22, 5, 0, 0, 1, 22, 1, 1, 0, 0, 0, + 23, 25, 5, 2, 0, 0, 24, 23, 1, 0, 0, 0, 24, 25, 1, 0, 0, 0, 25, 27, 1, + 0, 0, 0, 26, 28, 3, 6, 3, 0, 27, 26, 1, 0, 0, 0, 27, 28, 1, 0, 0, 0, 28, + 30, 1, 0, 0, 0, 29, 31, 3, 4, 2, 0, 30, 29, 1, 0, 0, 0, 30, 31, 1, 0, 0, + 0, 31, 33, 1, 0, 0, 0, 32, 34, 3, 8, 4, 0, 33, 32, 1, 0, 0, 0, 33, 34, + 1, 0, 0, 0, 34, 36, 1, 0, 0, 0, 35, 37, 3, 10, 5, 0, 36, 35, 1, 0, 0, 0, + 36, 37, 1, 0, 0, 0, 37, 3, 1, 0, 0, 0, 38, 39, 5, 2, 0, 0, 39, 5, 1, 0, + 0, 0, 40, 41, 3, 12, 6, 0, 41, 7, 1, 0, 0, 0, 42, 43, 3, 12, 6, 0, 43, + 44, 5, 2, 0, 0, 44, 46, 1, 0, 0, 0, 45, 42, 1, 0, 0, 0, 46, 49, 1, 0, 0, + 0, 47, 45, 1, 0, 0, 0, 47, 48, 1, 0, 0, 0, 48, 51, 1, 0, 0, 0, 49, 47, + 1, 0, 0, 0, 50, 52, 3, 12, 6, 0, 51, 50, 1, 0, 0, 0, 51, 52, 1, 0, 0, 0, + 52, 54, 1, 0, 0, 0, 53, 55, 5, 2, 0, 0, 54, 53, 1, 0, 0, 0, 54, 55, 1, + 0, 0, 0, 55, 9, 1, 0, 0, 0, 56, 58, 5, 1, 0, 0, 57, 59, 5, 2, 0, 0, 58, + 57, 1, 0, 0, 0, 58, 59, 1, 0, 0, 0, 59, 64, 1, 0, 0, 0, 60, 62, 3, 12, + 6, 0, 61, 63, 5, 2, 0, 0, 62, 61, 1, 0, 0, 0, 62, 63, 1, 0, 0, 0, 63, 65, + 1, 0, 0, 0, 64, 60, 1, 0, 0, 0, 65, 66, 1, 0, 0, 0, 66, 64, 1, 0, 0, 0, + 66, 67, 1, 0, 0, 0, 67, 11, 1, 0, 0, 0, 68, 69, 7, 0, 0, 0, 69, 13, 1, + 0, 0, 0, 13, 17, 19, 24, 27, 30, 33, 36, 47, 51, 54, 58, 62, 66, } deserializer := antlr.NewATNDeserializer(nil) staticData.atn = deserializer.Deserialize(staticData.serializedATN) @@ -109,11 +111,12 @@ func NewConfigParser(input antlr.TokenStream) *ConfigParser { // ConfigParser tokens. const ( - ConfigParserEOF = antlr.TokenEOF - ConfigParserHASH = 1 - ConfigParserWHITESPACE = 2 - ConfigParserSTRING = 3 - ConfigParserNEWLINE = 4 + ConfigParserEOF = antlr.TokenEOF + ConfigParserHASH = 1 + ConfigParserWHITESPACE = 2 + ConfigParserSTRING = 3 + ConfigParserNEWLINE = 4 + ConfigParserQUOTED_STRING = 5 ) // ConfigParser rules. @@ -124,6 +127,7 @@ const ( ConfigParserRULE_key = 3 ConfigParserRULE_value = 4 ConfigParserRULE_leadingComment = 5 + ConfigParserRULE_string = 6 ) // ILineStatementContext is an interface to support dynamic dispatch. @@ -241,7 +245,7 @@ func (p *ConfigParser) LineStatement() (localctx ILineStatementContext) { var _la int p.EnterOuterAlt(localctx, 1) - p.SetState(17) + p.SetState(19) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -250,18 +254,18 @@ func (p *ConfigParser) LineStatement() (localctx ILineStatementContext) { switch p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 1, p.GetParserRuleContext()) { case 1: { - p.SetState(12) + p.SetState(14) p.Entry() } case 2: { - p.SetState(13) + p.SetState(15) p.LeadingComment() } case 3: - p.SetState(15) + p.SetState(17) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -270,7 +274,7 @@ func (p *ConfigParser) LineStatement() (localctx ILineStatementContext) { if _la == ConfigParserWHITESPACE { { - p.SetState(14) + p.SetState(16) p.Match(ConfigParserWHITESPACE) if p.HasError() { // Recognition error - abort rule @@ -284,7 +288,7 @@ func (p *ConfigParser) LineStatement() (localctx ILineStatementContext) { goto errorExit } { - p.SetState(19) + p.SetState(21) p.Match(ConfigParserEOF) if p.HasError() { // Recognition error - abort rule @@ -449,12 +453,12 @@ func (p *ConfigParser) Entry() (localctx IEntryContext) { var _la int p.EnterOuterAlt(localctx, 1) - p.SetState(22) + p.SetState(24) p.GetErrorHandler().Sync(p) if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 2, p.GetParserRuleContext()) == 1 { { - p.SetState(21) + p.SetState(23) p.Match(ConfigParserWHITESPACE) if p.HasError() { // Recognition error - abort rule @@ -465,43 +469,43 @@ func (p *ConfigParser) Entry() (localctx IEntryContext) { } else if p.HasError() { // JIM goto errorExit } - p.SetState(25) + p.SetState(27) p.GetErrorHandler().Sync(p) if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 3, p.GetParserRuleContext()) == 1 { { - p.SetState(24) + p.SetState(26) p.Key() } } else if p.HasError() { // JIM goto errorExit } - p.SetState(28) + p.SetState(30) p.GetErrorHandler().Sync(p) if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 4, p.GetParserRuleContext()) == 1 { { - p.SetState(27) + p.SetState(29) p.Separator() } } else if p.HasError() { // JIM goto errorExit } - p.SetState(31) + p.SetState(33) p.GetErrorHandler().Sync(p) if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 5, p.GetParserRuleContext()) == 1 { { - p.SetState(30) + p.SetState(32) p.Value() } } else if p.HasError() { // JIM goto errorExit } - p.SetState(34) + p.SetState(36) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -510,7 +514,7 @@ func (p *ConfigParser) Entry() (localctx IEntryContext) { if _la == ConfigParserHASH { { - p.SetState(33) + p.SetState(35) p.LeadingComment() } @@ -604,7 +608,7 @@ func (p *ConfigParser) Separator() (localctx ISeparatorContext) { p.EnterRule(localctx, 4, ConfigParserRULE_separator) p.EnterOuterAlt(localctx, 1) { - p.SetState(36) + p.SetState(38) p.Match(ConfigParserWHITESPACE) if p.HasError() { // Recognition error - abort rule @@ -633,7 +637,7 @@ type IKeyContext interface { GetParser() antlr.Parser // Getter signatures - STRING() antlr.TerminalNode + String_() IStringContext // IsKeyContext differentiates from other interfaces. IsKeyContext() @@ -671,8 +675,20 @@ func NewKeyContext(parser antlr.Parser, parent antlr.ParserRuleContext, invoking func (s *KeyContext) GetParser() antlr.Parser { return s.parser } -func (s *KeyContext) STRING() antlr.TerminalNode { - return s.GetToken(ConfigParserSTRING, 0) +func (s *KeyContext) String_() IStringContext { + var t antlr.RuleContext + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(IStringContext); ok { + t = ctx.(antlr.RuleContext) + break + } + } + + if t == nil { + return nil + } + + return t.(IStringContext) } func (s *KeyContext) GetRuleContext() antlr.RuleContext { @@ -700,12 +716,8 @@ func (p *ConfigParser) Key() (localctx IKeyContext) { p.EnterRule(localctx, 6, ConfigParserRULE_key) p.EnterOuterAlt(localctx, 1) { - p.SetState(38) - p.Match(ConfigParserSTRING) - if p.HasError() { - // Recognition error - abort rule - goto errorExit - } + p.SetState(40) + p.String_() } errorExit: @@ -729,8 +741,8 @@ type IValueContext interface { GetParser() antlr.Parser // Getter signatures - AllSTRING() []antlr.TerminalNode - STRING(i int) antlr.TerminalNode + AllString_() []IStringContext + String_(i int) IStringContext AllWHITESPACE() []antlr.TerminalNode WHITESPACE(i int) antlr.TerminalNode @@ -770,12 +782,45 @@ func NewValueContext(parser antlr.Parser, parent antlr.ParserRuleContext, invoki func (s *ValueContext) GetParser() antlr.Parser { return s.parser } -func (s *ValueContext) AllSTRING() []antlr.TerminalNode { - return s.GetTokens(ConfigParserSTRING) +func (s *ValueContext) AllString_() []IStringContext { + children := s.GetChildren() + len := 0 + for _, ctx := range children { + if _, ok := ctx.(IStringContext); ok { + len++ + } + } + + tst := make([]IStringContext, len) + i := 0 + for _, ctx := range children { + if t, ok := ctx.(IStringContext); ok { + tst[i] = t.(IStringContext) + i++ + } + } + + return tst } -func (s *ValueContext) STRING(i int) antlr.TerminalNode { - return s.GetToken(ConfigParserSTRING, i) +func (s *ValueContext) String_(i int) IStringContext { + var t antlr.RuleContext + j := 0 + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(IStringContext); ok { + if j == i { + t = ctx.(antlr.RuleContext) + break + } + j++ + } + } + + if t == nil { + return nil + } + + return t.(IStringContext) } func (s *ValueContext) AllWHITESPACE() []antlr.TerminalNode { @@ -814,7 +859,7 @@ func (p *ConfigParser) Value() (localctx IValueContext) { var _alt int p.EnterOuterAlt(localctx, 1) - p.SetState(44) + p.SetState(47) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -826,15 +871,11 @@ func (p *ConfigParser) Value() (localctx IValueContext) { for _alt != 2 && _alt != antlr.ATNInvalidAltNumber { if _alt == 1 { { - p.SetState(40) - p.Match(ConfigParserSTRING) - if p.HasError() { - // Recognition error - abort rule - goto errorExit - } + p.SetState(42) + p.String_() } { - p.SetState(41) + p.SetState(43) p.Match(ConfigParserWHITESPACE) if p.HasError() { // Recognition error - abort rule @@ -843,7 +884,7 @@ func (p *ConfigParser) Value() (localctx IValueContext) { } } - p.SetState(46) + p.SetState(49) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -853,25 +894,21 @@ func (p *ConfigParser) Value() (localctx IValueContext) { goto errorExit } } - p.SetState(48) + p.SetState(51) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit } _la = p.GetTokenStream().LA(1) - if _la == ConfigParserSTRING { + if _la == ConfigParserSTRING || _la == ConfigParserQUOTED_STRING { { - p.SetState(47) - p.Match(ConfigParserSTRING) - if p.HasError() { - // Recognition error - abort rule - goto errorExit - } + p.SetState(50) + p.String_() } } - p.SetState(51) + p.SetState(54) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -880,7 +917,7 @@ func (p *ConfigParser) Value() (localctx IValueContext) { if _la == ConfigParserWHITESPACE { { - p.SetState(50) + p.SetState(53) p.Match(ConfigParserWHITESPACE) if p.HasError() { // Recognition error - abort rule @@ -914,8 +951,8 @@ type ILeadingCommentContext interface { HASH() antlr.TerminalNode AllWHITESPACE() []antlr.TerminalNode WHITESPACE(i int) antlr.TerminalNode - AllSTRING() []antlr.TerminalNode - STRING(i int) antlr.TerminalNode + AllString_() []IStringContext + String_(i int) IStringContext // IsLeadingCommentContext differentiates from other interfaces. IsLeadingCommentContext() @@ -965,12 +1002,45 @@ func (s *LeadingCommentContext) WHITESPACE(i int) antlr.TerminalNode { return s.GetToken(ConfigParserWHITESPACE, i) } -func (s *LeadingCommentContext) AllSTRING() []antlr.TerminalNode { - return s.GetTokens(ConfigParserSTRING) +func (s *LeadingCommentContext) AllString_() []IStringContext { + children := s.GetChildren() + len := 0 + for _, ctx := range children { + if _, ok := ctx.(IStringContext); ok { + len++ + } + } + + tst := make([]IStringContext, len) + i := 0 + for _, ctx := range children { + if t, ok := ctx.(IStringContext); ok { + tst[i] = t.(IStringContext) + i++ + } + } + + return tst } -func (s *LeadingCommentContext) STRING(i int) antlr.TerminalNode { - return s.GetToken(ConfigParserSTRING, i) +func (s *LeadingCommentContext) String_(i int) IStringContext { + var t antlr.RuleContext + j := 0 + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(IStringContext); ok { + if j == i { + t = ctx.(antlr.RuleContext) + break + } + j++ + } + } + + if t == nil { + return nil + } + + return t.(IStringContext) } func (s *LeadingCommentContext) GetRuleContext() antlr.RuleContext { @@ -1000,14 +1070,14 @@ func (p *ConfigParser) LeadingComment() (localctx ILeadingCommentContext) { p.EnterOuterAlt(localctx, 1) { - p.SetState(53) + p.SetState(56) p.Match(ConfigParserHASH) if p.HasError() { // Recognition error - abort rule goto errorExit } } - p.SetState(55) + p.SetState(58) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -1016,7 +1086,7 @@ func (p *ConfigParser) LeadingComment() (localctx ILeadingCommentContext) { if _la == ConfigParserWHITESPACE { { - p.SetState(54) + p.SetState(57) p.Match(ConfigParserWHITESPACE) if p.HasError() { // Recognition error - abort rule @@ -1025,23 +1095,19 @@ func (p *ConfigParser) LeadingComment() (localctx ILeadingCommentContext) { } } - p.SetState(61) + p.SetState(64) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit } _la = p.GetTokenStream().LA(1) - for ok := true; ok; ok = _la == ConfigParserSTRING { + for ok := true; ok; ok = _la == ConfigParserSTRING || _la == ConfigParserQUOTED_STRING { { - p.SetState(57) - p.Match(ConfigParserSTRING) - if p.HasError() { - // Recognition error - abort rule - goto errorExit - } + p.SetState(60) + p.String_() } - p.SetState(59) + p.SetState(62) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -1050,7 +1116,7 @@ func (p *ConfigParser) LeadingComment() (localctx ILeadingCommentContext) { if _la == ConfigParserWHITESPACE { { - p.SetState(58) + p.SetState(61) p.Match(ConfigParserWHITESPACE) if p.HasError() { // Recognition error - abort rule @@ -1060,7 +1126,7 @@ func (p *ConfigParser) LeadingComment() (localctx ILeadingCommentContext) { } - p.SetState(63) + p.SetState(66) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -1080,3 +1146,109 @@ errorExit: return localctx goto errorExit // Trick to prevent compiler error if the label is not used } + +// IStringContext is an interface to support dynamic dispatch. +type IStringContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + + // Getter signatures + QUOTED_STRING() antlr.TerminalNode + STRING() antlr.TerminalNode + + // IsStringContext differentiates from other interfaces. + IsStringContext() +} + +type StringContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptyStringContext() *StringContext { + var p = new(StringContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_string + return p +} + +func InitEmptyStringContext(p *StringContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_string +} + +func (*StringContext) IsStringContext() {} + +func NewStringContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *StringContext { + var p = new(StringContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = ConfigParserRULE_string + + return p +} + +func (s *StringContext) GetParser() antlr.Parser { return s.parser } + +func (s *StringContext) QUOTED_STRING() antlr.TerminalNode { + return s.GetToken(ConfigParserQUOTED_STRING, 0) +} + +func (s *StringContext) STRING() antlr.TerminalNode { + return s.GetToken(ConfigParserSTRING, 0) +} + +func (s *StringContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *StringContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +func (s *StringContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.EnterString(s) + } +} + +func (s *StringContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.ExitString(s) + } +} + +func (p *ConfigParser) String_() (localctx IStringContext) { + localctx = NewStringContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 12, ConfigParserRULE_string) + var _la int + + p.EnterOuterAlt(localctx, 1) + { + p.SetState(68) + _la = p.GetTokenStream().LA(1) + + if !(_la == ConfigParserSTRING || _la == ConfigParserQUOTED_STRING) { + p.GetErrorHandler().RecoverInline(p) + } else { + p.GetErrorHandler().ReportMatch(p) + p.Consume() + } + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} diff --git a/handlers/sshd_config/ast/parser_test.go b/handlers/sshd_config/ast/parser_test.go index b309380..5aebf15 100644 --- a/handlers/sshd_config/ast/parser_test.go +++ b/handlers/sshd_config/ast/parser_test.go @@ -165,7 +165,7 @@ func TestIncompleteMatchBlock( t.Errorf("Expected first entry to be 'User lena', but got: %v", matchBlock.MatchValue.Entries[0]) } - if !(matchBlock.MatchValue.Entries[1].Value.Value == "User " && matchBlock.MatchValue.Entries[1].Criteria.Type == "User" && matchBlock.MatchValue.Entries[1].Values == nil) { + if !(matchBlock.MatchValue.Entries[1].Value.Value == "User " && matchBlock.MatchValue.Entries[1].Criteria.Type == "User" && len(matchBlock.MatchValue.Entries[1].Values.Values) == 0) { t.Errorf("Expected second entry to be 'User ', but got: %v", matchBlock.MatchValue.Entries[1]) } } @@ -544,3 +544,101 @@ Match Address 172.22.100.0/24,172.22.5.0/24,127.0.0.1 t.Errorf("Expected seventh entry to be 'PermitRootLogin without-password', but got: %v", seventhEntry.Value) } } + +func TestQuotedOptionExample( + t *testing.T, +) { + input := utils.Dedent(` +PermitRootLogin "no" +`) + p := NewSSHConfig() + errors := p.Parse(input) + + if len(errors) != 0 { + t.Fatalf("Expected no errors, got %v", errors) + } + + if !(p.Options.Size() == 1 && + len(utils.KeysOfMap(p.CommentLines)) == 0) { + t.Errorf("Expected 1 option and no comment lines, but got: %v, %v", p.Options, p.CommentLines) + } + + rawFirstEntry, _ := p.Options.Get(uint32(0)) + entry := rawFirstEntry.(*SSHDOption) + + if !(entry.Key.Value.Value == "PermitRootLogin" && entry.OptionValue.Value.Value == "no") { + t.Errorf("Expected first entry to be 'PermitRootLogin no', but got: %v", entry.Value) + } + + if !(entry.LocationRange.Start.Line == 0 && entry.LocationRange.Start.Character == 0 && entry.LocationRange.End.Line == 0 && entry.LocationRange.End.Character == 20) { + t.Errorf("Expected location range to be 0:0-0:20, but got: %v", entry.LocationRange) + } + + if !(entry.OptionValue.LocationRange.Start.Character == 16 && entry.OptionValue.LocationRange.End.Character == 20) { + t.Errorf("Expected option value location range to be 17-20, but got: %v", entry.OptionValue.LocationRange) + } +} + +func TestQuotedKeyExample( + t *testing.T, +) { + input := utils.Dedent(` +"PermitRootLogin" no +`) + p := NewSSHConfig() + errors := p.Parse(input) + + if len(errors) != 0 { + t.Fatalf("Expected no errors, got %v", errors) + } + + if !(p.Options.Size() == 1 && + len(utils.KeysOfMap(p.CommentLines)) == 0) { + t.Errorf("Expected 1 option and no comment lines, but got: %v, %v", p.Options, p.CommentLines) + } + + rawFirstEntry, _ := p.Options.Get(uint32(0)) + entry := rawFirstEntry.(*SSHDOption) + + if !(entry.Key.Value.Value == "PermitRootLogin" && entry.OptionValue.Value.Value == "no") { + t.Errorf("Expected first entry to be 'PermitRootLogin no', but got: %v", entry.Value) + } + + if !(entry.LocationRange.Start.Line == 0 && entry.LocationRange.Start.Character == 0 && entry.LocationRange.End.Line == 0 && entry.LocationRange.End.Character == 20) { + t.Errorf("Expected location range to be 0:0-0:20, but got: %v", entry.LocationRange) + } + + if !(entry.Key.LocationRange.Start.Character == 0 && entry.Key.LocationRange.End.Character == 17) { + t.Errorf("Expected key location range to be 0-17, but got: %v", entry.Key.LocationRange) + } + + if !(entry.Key.LocationRange.Start.Character == 0 && entry.Key.LocationRange.End.Character == 17) { + t.Errorf("Expected key location range to be 0-17, but got: %v", entry.Key.LocationRange) + } +} + +func TestQuotedValueWithSpacesExample( + t *testing.T, +) { + input := utils.Dedent(` +PermitRootLogin "no yes maybe" +`) + p := NewSSHConfig() + errors := p.Parse(input) + + if len(errors) != 0 { + t.Fatalf("Expected no errors, got %v", errors) + } + + if !(p.Options.Size() == 1 && + len(utils.KeysOfMap(p.CommentLines)) == 0) { + t.Errorf("Expected 1 option and no comment lines, but got: %v, %v", p.Options, p.CommentLines) + } + + rawFirstEntry, _ := p.Options.Get(uint32(0)) + entry := rawFirstEntry.(*SSHDOption) + + if !(entry.Key.Value.Value == "PermitRootLogin" && entry.OptionValue.Value.Value == "no yes maybe") { + t.Errorf("Expected first entry to be 'PermitRootLogin no yes maybe', but got: %v", entry.Value) + } +} diff --git a/handlers/sshd_config/ast/sshd_config.go b/handlers/sshd_config/ast/sshd_config.go index fda6f34..27b5aef 100644 --- a/handlers/sshd_config/ast/sshd_config.go +++ b/handlers/sshd_config/ast/sshd_config.go @@ -33,6 +33,7 @@ type SSHDEntry interface { type SSHDSeparator struct { common.LocationRange + Value commonparser.ParsedString } type SSHDOption struct { diff --git a/handlers/sshd_config/fields/match-parser/parser_test.go b/handlers/sshd_config/fields/match-parser/parser_test.go index e35647f..a7554e7 100644 --- a/handlers/sshd_config/fields/match-parser/parser_test.go +++ b/handlers/sshd_config/fields/match-parser/parser_test.go @@ -128,7 +128,7 @@ func TestIncompleteBetweenValuesExample( t.Errorf("Expected User, but got %v", match.Entries[0]) } - if !(match.Entries[0].Values == nil) { + if !(len(match.Entries[0].Values.Values) == 0) { t.Errorf("Expected 0 values, but got %v", match.Entries[0].Values) } } diff --git a/handlers/sshd_config/handlers/completions.go b/handlers/sshd_config/handlers/completions.go index 8314f3c..d6f2ca2 100644 --- a/handlers/sshd_config/handlers/completions.go +++ b/handlers/sshd_config/handlers/completions.go @@ -22,16 +22,20 @@ func GetRootCompletions( if parentMatchBlock == nil { for key, option := range fields.Options { - if _, found := d.Indexes.AllOptionsPerName[key]; !found { - availableOptions[key] = option + if d.Indexes != nil && utils.KeyExists(d.Indexes.AllOptionsPerName, key) && !utils.KeyExists(fields.AllowedDuplicateOptions, key) { + continue } + + availableOptions[key] = option } } else { for key := range fields.MatchAllowedOptions { if option, found := fields.Options[key]; found { - if _, found := d.Indexes.AllOptionsPerName[key]; !found { - availableOptions[key] = option + if d.Indexes != nil && utils.KeyExists(d.Indexes.AllOptionsPerName, key) && !utils.KeyExists(fields.AllowedDuplicateOptions, key) { + continue } + + availableOptions[key] = option } } } diff --git a/handlers/sshd_config/lsp/text-document-completion.go b/handlers/sshd_config/lsp/text-document-completion.go index d779ba2..96c1ce9 100644 --- a/handlers/sshd_config/lsp/text-document-completion.go +++ b/handlers/sshd_config/lsp/text-document-completion.go @@ -33,7 +33,7 @@ func TextDocumentCompletion(context *glsp.Context, params *protocol.CompletionPa d, matchBlock, // Empty line, or currently typing a new key - entry == nil || isEmptyPattern.Match([]byte(entry.Value.Value[cursor:])), + entry == nil || isEmptyPattern.Match([]byte(entry.Value.Raw[cursor:])), ) } diff --git a/handlers/sshd_config/test_utils/input.go b/handlers/sshd_config/test_utils/input.go new file mode 100644 index 0000000..4f6f5fd --- /dev/null +++ b/handlers/sshd_config/test_utils/input.go @@ -0,0 +1,33 @@ +package testutils_test + +import ( + sshdconfig "config-lsp/handlers/sshd_config" + "config-lsp/handlers/sshd_config/ast" + "config-lsp/handlers/sshd_config/indexes" + "config-lsp/utils" + "testing" +) + +func DocumentFromInput( + t *testing.T, + content string, +) *sshdconfig.SSHDocument { + input := utils.Dedent(content) + c := ast.NewSSHConfig() + errors := c.Parse(input) + + if len(errors) > 0 { + t.Fatalf("Parse error: %v", errors) + } + + i, errors := indexes.CreateIndexes(*c) + + if len(errors) > 0 { + t.Fatalf("Index error: %v", errors) + } + + return &sshdconfig.SSHDocument{ + Config: c, + Indexes: i, + } +} From 250ec83a598f39a05deb5dd5a9ed99705cca571d Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Sat, 21 Sep 2024 18:41:20 +0200 Subject: [PATCH 070/133] refactor: Move match parser to common package --- .../parsers/openssh-match-parser}/Match.g4 | 0 .../openssh-match-parser}/error-listener.go | 0 .../openssh-match-parser}/full_test.go | 0 .../parsers/openssh-match-parser}/listener.go | 16 +++++----- .../openssh-match-parser}/match_ast.go | 0 .../openssh-match-parser}/match_fields.go | 0 .../parsers/openssh-match-parser}/parser.go | 6 ++-- .../openssh-match-parser}/parser/Match.interp | 0 .../openssh-match-parser}/parser/Match.tokens | 0 .../parser/MatchLexer.interp | 0 .../parser/MatchLexer.tokens | 0 .../parser/match_base_listener.go | 0 .../parser/match_lexer.go | 0 .../parser/match_listener.go | 0 .../parser/match_parser.go | 0 .../openssh-match-parser}/parser_test.go | 0 handlers/ssh_config/ast/ssh_config.go | 2 +- handlers/sshd_config/analyzer/match.go | 2 +- handlers/sshd_config/analyzer/options.go | 2 +- handlers/sshd_config/ast/listener.go | 8 ++--- handlers/sshd_config/ast/parser_test.go | 30 +++++++++---------- handlers/sshd_config/ast/sshd_config.go | 7 ++--- .../sshd_config/ast/sshd_config_fields.go | 10 +++---- .../sshd_config/handlers/completions_match.go | 3 +- .../sshd_config/handlers/formatting_nodes.go | 6 ++-- handlers/sshd_config/indexes/handlers.go | 2 +- 26 files changed, 46 insertions(+), 48 deletions(-) rename {handlers/sshd_config/fields/match-parser => common/parsers/openssh-match-parser}/Match.g4 (100%) rename {handlers/sshd_config/fields/match-parser => common/parsers/openssh-match-parser}/error-listener.go (100%) rename {handlers/sshd_config/fields/match-parser => common/parsers/openssh-match-parser}/full_test.go (100%) rename {handlers/sshd_config/fields/match-parser => common/parsers/openssh-match-parser}/listener.go (86%) rename {handlers/sshd_config/fields/match-parser => common/parsers/openssh-match-parser}/match_ast.go (100%) rename {handlers/sshd_config/fields/match-parser => common/parsers/openssh-match-parser}/match_fields.go (100%) rename {handlers/sshd_config/fields/match-parser => common/parsers/openssh-match-parser}/parser.go (87%) rename {handlers/sshd_config/fields/match-parser => common/parsers/openssh-match-parser}/parser/Match.interp (100%) rename {handlers/sshd_config/fields/match-parser => common/parsers/openssh-match-parser}/parser/Match.tokens (100%) rename {handlers/sshd_config/fields/match-parser => common/parsers/openssh-match-parser}/parser/MatchLexer.interp (100%) rename {handlers/sshd_config/fields/match-parser => common/parsers/openssh-match-parser}/parser/MatchLexer.tokens (100%) rename {handlers/sshd_config/fields/match-parser => common/parsers/openssh-match-parser}/parser/match_base_listener.go (100%) rename {handlers/sshd_config/fields/match-parser => common/parsers/openssh-match-parser}/parser/match_lexer.go (100%) rename {handlers/sshd_config/fields/match-parser => common/parsers/openssh-match-parser}/parser/match_listener.go (100%) rename {handlers/sshd_config/fields/match-parser => common/parsers/openssh-match-parser}/parser/match_parser.go (100%) rename {handlers/sshd_config/fields/match-parser => common/parsers/openssh-match-parser}/parser_test.go (100%) diff --git a/handlers/sshd_config/fields/match-parser/Match.g4 b/common/parsers/openssh-match-parser/Match.g4 similarity index 100% rename from handlers/sshd_config/fields/match-parser/Match.g4 rename to common/parsers/openssh-match-parser/Match.g4 diff --git a/handlers/sshd_config/fields/match-parser/error-listener.go b/common/parsers/openssh-match-parser/error-listener.go similarity index 100% rename from handlers/sshd_config/fields/match-parser/error-listener.go rename to common/parsers/openssh-match-parser/error-listener.go diff --git a/handlers/sshd_config/fields/match-parser/full_test.go b/common/parsers/openssh-match-parser/full_test.go similarity index 100% rename from handlers/sshd_config/fields/match-parser/full_test.go rename to common/parsers/openssh-match-parser/full_test.go diff --git a/handlers/sshd_config/fields/match-parser/listener.go b/common/parsers/openssh-match-parser/listener.go similarity index 86% rename from handlers/sshd_config/fields/match-parser/listener.go rename to common/parsers/openssh-match-parser/listener.go index ce5e130..fc1f3b5 100644 --- a/handlers/sshd_config/fields/match-parser/listener.go +++ b/common/parsers/openssh-match-parser/listener.go @@ -3,7 +3,7 @@ package matchparser import ( "config-lsp/common" commonparser "config-lsp/common/parser" - "config-lsp/handlers/sshd_config/fields/match-parser/parser" + parser2 "config-lsp/common/parsers/openssh-match-parser/parser" "config-lsp/utils" "errors" "fmt" @@ -39,13 +39,13 @@ func createListener( } type matchParserListener struct { - *parser.BaseMatchListener + *parser2.BaseMatchListener match *Match Errors []common.LSPError matchContext *matchListenerContext } -func (s *matchParserListener) EnterMatchEntry(ctx *parser.MatchEntryContext) { +func (s *matchParserListener) EnterMatchEntry(ctx *parser2.MatchEntryContext) { location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext).ShiftHorizontal(s.matchContext.startCharacter) location.ChangeBothLines(s.matchContext.line) @@ -58,7 +58,7 @@ func (s *matchParserListener) EnterMatchEntry(ctx *parser.MatchEntryContext) { s.matchContext.currentEntry = entry } -func (s *matchParserListener) ExitMatchEntry(ctx *parser.MatchEntryContext) { +func (s *matchParserListener) ExitMatchEntry(ctx *parser2.MatchEntryContext) { s.matchContext.currentEntry = nil } @@ -72,7 +72,7 @@ var availableCriteria = map[string]MatchCriteriaType{ string(MatchCriteriaTypeAddress): MatchCriteriaTypeAddress, } -func (s *matchParserListener) EnterCriteria(ctx *parser.CriteriaContext) { +func (s *matchParserListener) EnterCriteria(ctx *parser2.CriteriaContext) { location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext).ShiftHorizontal(s.matchContext.startCharacter) location.ChangeBothLines(s.matchContext.line) @@ -95,7 +95,7 @@ func (s *matchParserListener) EnterCriteria(ctx *parser.CriteriaContext) { } } -func (s *matchParserListener) EnterSeparator(ctx *parser.SeparatorContext) { +func (s *matchParserListener) EnterSeparator(ctx *parser2.SeparatorContext) { location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext).ShiftHorizontal(s.matchContext.startCharacter) location.ChangeBothLines(s.matchContext.line) @@ -104,7 +104,7 @@ func (s *matchParserListener) EnterSeparator(ctx *parser.SeparatorContext) { } } -func (s *matchParserListener) EnterValues(ctx *parser.ValuesContext) { +func (s *matchParserListener) EnterValues(ctx *parser2.ValuesContext) { location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext).ShiftHorizontal(s.matchContext.startCharacter) location.ChangeBothLines(s.matchContext.line) @@ -114,7 +114,7 @@ func (s *matchParserListener) EnterValues(ctx *parser.ValuesContext) { } } -func (s *matchParserListener) EnterValue(ctx *parser.ValueContext) { +func (s *matchParserListener) EnterValue(ctx *parser2.ValueContext) { location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext).ShiftHorizontal(s.matchContext.startCharacter) location.ChangeBothLines(s.matchContext.line) diff --git a/handlers/sshd_config/fields/match-parser/match_ast.go b/common/parsers/openssh-match-parser/match_ast.go similarity index 100% rename from handlers/sshd_config/fields/match-parser/match_ast.go rename to common/parsers/openssh-match-parser/match_ast.go diff --git a/handlers/sshd_config/fields/match-parser/match_fields.go b/common/parsers/openssh-match-parser/match_fields.go similarity index 100% rename from handlers/sshd_config/fields/match-parser/match_fields.go rename to common/parsers/openssh-match-parser/match_fields.go diff --git a/handlers/sshd_config/fields/match-parser/parser.go b/common/parsers/openssh-match-parser/parser.go similarity index 87% rename from handlers/sshd_config/fields/match-parser/parser.go rename to common/parsers/openssh-match-parser/parser.go index d81f73c..b4abe9e 100644 --- a/handlers/sshd_config/fields/match-parser/parser.go +++ b/common/parsers/openssh-match-parser/parser.go @@ -2,7 +2,7 @@ package matchparser import ( "config-lsp/common" - "config-lsp/handlers/sshd_config/fields/match-parser/parser" + parser2 "config-lsp/common/parsers/openssh-match-parser/parser" "github.com/antlr4-go/antlr/v4" ) @@ -27,14 +27,14 @@ func (m *Match) Parse( stream := antlr.NewInputStream(input) lexerErrorListener := createErrorListener(context.line) - lexer := parser.NewMatchLexer(stream) + lexer := parser2.NewMatchLexer(stream) lexer.RemoveErrorListeners() lexer.AddErrorListener(&lexerErrorListener) tokenStream := antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel) parserErrorListener := createErrorListener(context.line) - antlrParser := parser.NewMatchParser(tokenStream) + antlrParser := parser2.NewMatchParser(tokenStream) antlrParser.RemoveErrorListeners() antlrParser.AddErrorListener(&parserErrorListener) diff --git a/handlers/sshd_config/fields/match-parser/parser/Match.interp b/common/parsers/openssh-match-parser/parser/Match.interp similarity index 100% rename from handlers/sshd_config/fields/match-parser/parser/Match.interp rename to common/parsers/openssh-match-parser/parser/Match.interp diff --git a/handlers/sshd_config/fields/match-parser/parser/Match.tokens b/common/parsers/openssh-match-parser/parser/Match.tokens similarity index 100% rename from handlers/sshd_config/fields/match-parser/parser/Match.tokens rename to common/parsers/openssh-match-parser/parser/Match.tokens diff --git a/handlers/sshd_config/fields/match-parser/parser/MatchLexer.interp b/common/parsers/openssh-match-parser/parser/MatchLexer.interp similarity index 100% rename from handlers/sshd_config/fields/match-parser/parser/MatchLexer.interp rename to common/parsers/openssh-match-parser/parser/MatchLexer.interp diff --git a/handlers/sshd_config/fields/match-parser/parser/MatchLexer.tokens b/common/parsers/openssh-match-parser/parser/MatchLexer.tokens similarity index 100% rename from handlers/sshd_config/fields/match-parser/parser/MatchLexer.tokens rename to common/parsers/openssh-match-parser/parser/MatchLexer.tokens diff --git a/handlers/sshd_config/fields/match-parser/parser/match_base_listener.go b/common/parsers/openssh-match-parser/parser/match_base_listener.go similarity index 100% rename from handlers/sshd_config/fields/match-parser/parser/match_base_listener.go rename to common/parsers/openssh-match-parser/parser/match_base_listener.go diff --git a/handlers/sshd_config/fields/match-parser/parser/match_lexer.go b/common/parsers/openssh-match-parser/parser/match_lexer.go similarity index 100% rename from handlers/sshd_config/fields/match-parser/parser/match_lexer.go rename to common/parsers/openssh-match-parser/parser/match_lexer.go diff --git a/handlers/sshd_config/fields/match-parser/parser/match_listener.go b/common/parsers/openssh-match-parser/parser/match_listener.go similarity index 100% rename from handlers/sshd_config/fields/match-parser/parser/match_listener.go rename to common/parsers/openssh-match-parser/parser/match_listener.go diff --git a/handlers/sshd_config/fields/match-parser/parser/match_parser.go b/common/parsers/openssh-match-parser/parser/match_parser.go similarity index 100% rename from handlers/sshd_config/fields/match-parser/parser/match_parser.go rename to common/parsers/openssh-match-parser/parser/match_parser.go diff --git a/handlers/sshd_config/fields/match-parser/parser_test.go b/common/parsers/openssh-match-parser/parser_test.go similarity index 100% rename from handlers/sshd_config/fields/match-parser/parser_test.go rename to common/parsers/openssh-match-parser/parser_test.go diff --git a/handlers/ssh_config/ast/ssh_config.go b/handlers/ssh_config/ast/ssh_config.go index fb15e51..b3b5b6a 100644 --- a/handlers/ssh_config/ast/ssh_config.go +++ b/handlers/ssh_config/ast/ssh_config.go @@ -3,7 +3,7 @@ package ast import ( "config-lsp/common" commonparser "config-lsp/common/parser" - matchparser "config-lsp/handlers/sshd_config/fields/match-parser" + "config-lsp/common/parsers/openssh-match-parser" "github.com/emirpasic/gods/maps/treemap" ) diff --git a/handlers/sshd_config/analyzer/match.go b/handlers/sshd_config/analyzer/match.go index 68d4769..a150fef 100644 --- a/handlers/sshd_config/analyzer/match.go +++ b/handlers/sshd_config/analyzer/match.go @@ -2,8 +2,8 @@ package analyzer import ( "config-lsp/common" + "config-lsp/common/parsers/openssh-match-parser" sshdconfig "config-lsp/handlers/sshd_config" - matchparser "config-lsp/handlers/sshd_config/fields/match-parser" "config-lsp/utils" "errors" "fmt" diff --git a/handlers/sshd_config/analyzer/options.go b/handlers/sshd_config/analyzer/options.go index 1b3eba7..3f19923 100644 --- a/handlers/sshd_config/analyzer/options.go +++ b/handlers/sshd_config/analyzer/options.go @@ -109,7 +109,7 @@ func checkMatchBlock( ) []common.LSPError { errs := make([]common.LSPError, 0) - matchOption := matchBlock.MatchEntry.OptionValue + matchOption := matchBlock.MatchOption.OptionValue if matchOption != nil { invalidValues := fields.Options["Match"].CheckIsValid(matchOption.Value.Value) diff --git a/handlers/sshd_config/ast/listener.go b/handlers/sshd_config/ast/listener.go index d41e6a6..72816dc 100644 --- a/handlers/sshd_config/ast/listener.go +++ b/handlers/sshd_config/ast/listener.go @@ -3,8 +3,8 @@ package ast import ( "config-lsp/common" commonparser "config-lsp/common/parser" + matchparser2 "config-lsp/common/parsers/openssh-match-parser" "config-lsp/handlers/sshd_config/ast/parser" - matchparser "config-lsp/handlers/sshd_config/fields/match-parser" "strings" "github.com/emirpasic/gods/maps/treemap" @@ -113,10 +113,10 @@ func (s *sshParserListener) ExitEntry(ctx *parser.EntryContext) { if s.sshContext.isKeyAMatchBlock { // Add new match block - var match *matchparser.Match + var match *matchparser2.Match if s.sshContext.currentOption.OptionValue != nil { - matchParser := matchparser.NewMatch() + matchParser := matchparser2.NewMatch() errors := matchParser.Parse( s.sshContext.currentOption.OptionValue.Value.Raw, location.Start.Line, @@ -137,7 +137,7 @@ func (s *sshParserListener) ExitEntry(ctx *parser.EntryContext) { matchBlock := &SSHDMatchBlock{ LocationRange: location, - MatchEntry: s.sshContext.currentOption, + MatchOption: s.sshContext.currentOption, MatchValue: match, Options: treemap.NewWith(gods.UInt32Comparator), } diff --git a/handlers/sshd_config/ast/parser_test.go b/handlers/sshd_config/ast/parser_test.go index 5aebf15..423c6b2 100644 --- a/handlers/sshd_config/ast/parser_test.go +++ b/handlers/sshd_config/ast/parser_test.go @@ -88,15 +88,15 @@ Match Address 192.168.0.1 rawSecondEntry, _ := p.Options.Get(uint32(2)) secondEntry := rawSecondEntry.(*SSHDMatchBlock) - if !(secondEntry.MatchEntry.Value.Value == "Match Address 192.168.0.1") { - t.Errorf("Expected second entry to be 'Match Address 192.168.0.1', but got: %v", secondEntry.MatchEntry.Value) + if !(secondEntry.MatchOption.Value.Value == "Match Address 192.168.0.1") { + t.Errorf("Expected second entry to be 'Match Address 192.168.0.1', but got: %v", secondEntry.MatchOption.Value) } if !(secondEntry.Start.Line == 2 && secondEntry.Start.Character == 0 && secondEntry.End.Line == 3 && secondEntry.End.Character == 27) { t.Errorf("Expected second entry's location to be 2:0-3:25, but got: %v", secondEntry.LocationRange) } - if !(secondEntry.MatchValue.Entries[0].Criteria.Type == "Address" && secondEntry.MatchValue.Entries[0].Values.Values[0].Value.Value == "192.168.0.1" && secondEntry.MatchEntry.OptionValue.Start.Character == 6) { + if !(secondEntry.MatchValue.Entries[0].Criteria.Type == "Address" && secondEntry.MatchValue.Entries[0].Values.Values[0].Value.Value == "192.168.0.1" && secondEntry.MatchOption.OptionValue.Start.Character == 6) { t.Errorf("Expected second entry to be 'Match Address 192.168.0.1', but got: %v", secondEntry.MatchValue) } @@ -126,8 +126,8 @@ Match User lena User root _, matchBlock := p.FindOption(uint32(0)) - if !(matchBlock.MatchEntry.Value.Value == "Match User lena User root") { - t.Errorf("Expected match block to be 'Match User lena User root', but got: %v", matchBlock.MatchEntry.Value) + if !(matchBlock.MatchOption.Value.Value == "Match User lena User root") { + t.Errorf("Expected match block to be 'Match User lena User root', but got: %v", matchBlock.MatchOption.Value) } if !(len(matchBlock.MatchValue.Entries) == 2) { @@ -157,8 +157,8 @@ func TestIncompleteMatchBlock( _, matchBlock := p.FindOption(uint32(0)) - if !(matchBlock.MatchEntry.Value.Value == "Match User lena User ") { - t.Errorf("Expected match block to be 'Match User lena User ', but got: %v", matchBlock.MatchEntry.Value) + if !(matchBlock.MatchOption.Value.Value == "Match User lena User ") { + t.Errorf("Expected match block to be 'Match User lena User ', but got: %v", matchBlock.MatchOption.Value) } if !(matchBlock.MatchValue.Entries[0].Criteria.Type == "User" && matchBlock.MatchValue.Entries[0].Values.Values[0].Value.Value == "lena") { @@ -231,12 +231,12 @@ Match Address 192.168.0.2 } emptyOption, matchBlock := p.FindOption(uint32(5)) - if !(emptyOption == nil && matchBlock.MatchEntry.Value.Value == "Match User lena" && matchBlock.MatchValue.Entries[0].Values.Values[0].Value.Value == "lena") { + if !(emptyOption == nil && matchBlock.MatchOption.Value.Value == "Match User lena" && matchBlock.MatchValue.Entries[0].Values.Values[0].Value.Value == "lena") { t.Errorf("Expected empty option and match block to be 'Match User lena', but got: %v, %v", emptyOption, matchBlock) } matchOption, matchBlock := p.FindOption(uint32(2)) - if !(matchOption.Value.Value == "Match User lena" && matchBlock.MatchEntry.Value.Value == "Match User lena" && matchBlock.MatchValue.Entries[0].Values.Values[0].Value.Value == "lena" && matchBlock.MatchEntry.OptionValue.Start.Character == 6) { + if !(matchOption.Value.Value == "Match User lena" && matchBlock.MatchOption.Value.Value == "Match User lena" && matchBlock.MatchValue.Entries[0].Values.Values[0].Value.Value == "lena" && matchBlock.MatchOption.OptionValue.Start.Character == 6) { t.Errorf("Expected match option to be 'Match User lena', but got: %v, %v", matchOption, matchBlock) } @@ -502,8 +502,8 @@ Match Address 172.22.100.0/24,172.22.5.0/24,127.0.0.1 rawFourthEntry, _ := p.Options.Get(uint32(135)) fourthEntry := rawFourthEntry.(*SSHDMatchBlock) - if !(fourthEntry.MatchEntry.Value.Value == "Match User anoncvs") { - t.Errorf("Expected fourth entry to be 'Match User anoncvs', but got: %v", fourthEntry.MatchEntry.Value) + if !(fourthEntry.MatchOption.Value.Value == "Match User anoncvs") { + t.Errorf("Expected fourth entry to be 'Match User anoncvs', but got: %v", fourthEntry.MatchOption.Value) } if !(fourthEntry.MatchValue.Entries[0].Criteria.Type == "User" && fourthEntry.MatchValue.Entries[0].Values.Values[0].Value.Value == "anoncvs") { @@ -522,12 +522,12 @@ Match Address 172.22.100.0/24,172.22.5.0/24,127.0.0.1 rawSixthEntry, _ := p.Options.Get(uint32(142)) sixthEntry := rawSixthEntry.(*SSHDMatchBlock) - if !(sixthEntry.MatchEntry.Value.Value == "Match Address 172.22.100.0/24,172.22.5.0/24,127.0.0.1") { - t.Errorf("Expected sixth entry to be 'Match Address 172.22.100.0/24,172.22.5.0/24,127.0.0.1', but got: %v", sixthEntry.MatchEntry.Value) + if !(sixthEntry.MatchOption.Value.Value == "Match Address 172.22.100.0/24,172.22.5.0/24,127.0.0.1") { + t.Errorf("Expected sixth entry to be 'Match Address 172.22.100.0/24,172.22.5.0/24,127.0.0.1', but got: %v", sixthEntry.MatchOption.Value) } - if !(sixthEntry.MatchEntry.Key.Value.Value == "Match" && sixthEntry.MatchEntry.OptionValue.Value.Value == "Address 172.22.100.0/24,172.22.5.0/24,127.0.0.1") { - t.Errorf("Expected sixth entry to be 'Match Address 172.22.100.0/24,172.22.5.0/24,127.0.0.1', but got: %v", sixthEntry.MatchEntry.Value) + if !(sixthEntry.MatchOption.Key.Value.Value == "Match" && sixthEntry.MatchOption.OptionValue.Value.Value == "Address 172.22.100.0/24,172.22.5.0/24,127.0.0.1") { + t.Errorf("Expected sixth entry to be 'Match Address 172.22.100.0/24,172.22.5.0/24,127.0.0.1', but got: %v", sixthEntry.MatchOption.Value) } if !(sixthEntry.MatchValue.Entries[0].Criteria.Type == "Address" && len(sixthEntry.MatchValue.Entries[0].Values.Values) == 3) { diff --git a/handlers/sshd_config/ast/sshd_config.go b/handlers/sshd_config/ast/sshd_config.go index 27b5aef..72933b0 100644 --- a/handlers/sshd_config/ast/sshd_config.go +++ b/handlers/sshd_config/ast/sshd_config.go @@ -3,8 +3,7 @@ package ast import ( "config-lsp/common" commonparser "config-lsp/common/parser" - matchparser "config-lsp/handlers/sshd_config/fields/match-parser" - + "config-lsp/common/parsers/openssh-match-parser" "github.com/emirpasic/gods/maps/treemap" ) @@ -47,8 +46,8 @@ type SSHDOption struct { type SSHDMatchBlock struct { common.LocationRange - MatchEntry *SSHDOption - MatchValue *matchparser.Match + MatchOption *SSHDOption + MatchValue *matchparser.Match // [uint32]*SSHDOption -> line number -> *SSHDOption Options *treemap.Map diff --git a/handlers/sshd_config/ast/sshd_config_fields.go b/handlers/sshd_config/ast/sshd_config_fields.go index 97cb4b7..8c226bd 100644 --- a/handlers/sshd_config/ast/sshd_config_fields.go +++ b/handlers/sshd_config/ast/sshd_config_fields.go @@ -13,7 +13,7 @@ func (m SSHDMatchBlock) GetType() SSHDEntryType { } func (m SSHDMatchBlock) GetOption() SSHDOption { - return *m.MatchEntry + return *m.MatchOption } func (c SSHDConfig) FindMatchBlock(line uint32) *SSHDMatchBlock { @@ -37,8 +37,8 @@ func (c SSHDConfig) FindOption(line uint32) (*SSHDOption, *SSHDMatchBlock) { matchBlock := c.FindMatchBlock(line) if matchBlock != nil { - if line == matchBlock.MatchEntry.Start.Line { - return matchBlock.MatchEntry, matchBlock + if line == matchBlock.MatchOption.Start.Line { + return matchBlock.MatchOption, matchBlock } rawEntry, found := matchBlock.Options.Get(line) @@ -55,7 +55,7 @@ func (c SSHDConfig) FindOption(line uint32) (*SSHDOption, *SSHDMatchBlock) { if found { switch rawEntry.(type) { case *SSHDMatchBlock: - return rawEntry.(*SSHDMatchBlock).MatchEntry, rawEntry.(*SSHDMatchBlock) + return rawEntry.(*SSHDMatchBlock).MatchOption, rawEntry.(*SSHDMatchBlock) case *SSHDOption: return rawEntry.(*SSHDOption), nil } @@ -78,7 +78,7 @@ func (c SSHDConfig) GetAllOptions() []*SSHDOption { case *SSHDOption: options = append(options, entry) case *SSHDMatchBlock: - options = append(options, entry.MatchEntry) + options = append(options, entry.MatchOption) for _, rawOption := range entry.Options.Values() { options = append(options, rawOption.(*SSHDOption)) diff --git a/handlers/sshd_config/handlers/completions_match.go b/handlers/sshd_config/handlers/completions_match.go index 4c4707b..0d13fd5 100644 --- a/handlers/sshd_config/handlers/completions_match.go +++ b/handlers/sshd_config/handlers/completions_match.go @@ -2,10 +2,9 @@ package handlers import ( "config-lsp/common" + "config-lsp/common/parsers/openssh-match-parser" sshdconfig "config-lsp/handlers/sshd_config" "config-lsp/handlers/sshd_config/fields" - matchparser "config-lsp/handlers/sshd_config/fields/match-parser" - protocol "github.com/tliron/glsp/protocol_3_16" ) diff --git a/handlers/sshd_config/handlers/formatting_nodes.go b/handlers/sshd_config/handlers/formatting_nodes.go index bb0b7cd..e0e9bf3 100644 --- a/handlers/sshd_config/handlers/formatting_nodes.go +++ b/handlers/sshd_config/handlers/formatting_nodes.go @@ -2,8 +2,8 @@ package handlers import ( "config-lsp/common/formatting" + "config-lsp/common/parsers/openssh-match-parser" "config-lsp/handlers/sshd_config/ast" - matchparser "config-lsp/handlers/sshd_config/fields/match-parser" "config-lsp/utils" "fmt" "strings" @@ -57,10 +57,10 @@ func formatSSHDMatchBlock( edits := make([]protocol.TextEdit, 0) edits = append(edits, protocol.TextEdit{ - Range: matchBlock.MatchEntry.ToLSPRange(), + Range: matchBlock.MatchOption.ToLSPRange(), NewText: matchTemplate.Format( options, - matchBlock.MatchEntry.Key.Key, + matchBlock.MatchOption.Key.Key, formatMatchToString(matchBlock.MatchValue), ), }) diff --git a/handlers/sshd_config/indexes/handlers.go b/handlers/sshd_config/indexes/handlers.go index 533825c..271887b 100644 --- a/handlers/sshd_config/indexes/handlers.go +++ b/handlers/sshd_config/indexes/handlers.go @@ -30,7 +30,7 @@ func CreateIndexes(config ast.SSHDConfig) (*SSHDIndexes, []common.LSPError) { case *ast.SSHDMatchBlock: matchBlock := entry.(*ast.SSHDMatchBlock) - errs = append(errs, addOption(indexes, matchBlock.MatchEntry, matchBlock)...) + errs = append(errs, addOption(indexes, matchBlock.MatchOption, matchBlock)...) it := matchBlock.Options.Iterator() for it.Next() { From 4eb4a1845c00db55c4292f0103d359de03640f9d Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Sun, 22 Sep 2024 11:22:38 +0200 Subject: [PATCH 071/133] chore: Update parsers; Add update script --- handlers/ssh_config/Config.g4 | 18 +- handlers/sshd_config/analyzer/analyzer.go | 2 +- handlers/sshd_config/analyzer/include.go | 8 +- handlers/sshd_config/analyzer/match.go | 6 +- handlers/sshd_config/analyzer/match_test.go | 6 +- handlers/sshd_config/analyzer/options.go | 2 +- handlers/sshd_config/analyzer/quotes.go | 2 +- handlers/sshd_config/ast/listener.go | 90 +- handlers/sshd_config/ast/parser.go | 6 +- handlers/sshd_config/ast/parser_test.go | 22 +- handlers/sshd_config/ast/sshd_config.go | 4 +- handlers/sshd_config/handlers/completions.go | 4 +- .../sshd_config/handlers/completions_match.go | 6 +- handlers/sshd_config/handlers/formatting.go | 2 +- .../sshd_config/handlers/formatting_nodes.go | 4 +- .../sshd_config/handlers/formatting_test.go | 4 +- handlers/sshd_config/indexes/indexes_test.go | 4 +- .../sshd_config/lsp/text-document-did-open.go | 6 +- .../sshd_config/match-parser}/Match.g4 | 0 .../match-parser}/error-listener.go | 0 .../sshd_config/match-parser}/full_test.go | 0 .../sshd_config/match-parser}/Match.interp | 0 .../sshd_config/match-parser}/Match.tokens | 0 .../match-parser}/MatchLexer.interp | 0 .../match-parser}/MatchLexer.tokens | 0 .../match-parser/match_base_listener.go | 58 + .../sshd_config/match-parser/match_lexer.go | 109 ++ .../match-parser/match_listener.go | 46 + .../sshd_config/match-parser/match_parser.go | 961 +++++++++++++ .../sshd_config/match-parser}/listener.go | 16 +- .../sshd_config/match-parser}/match_ast.go | 0 .../sshd_config/match-parser}/match_fields.go | 0 .../sshd_config/match-parser}/parser.go | 6 +- .../match-parser/parser/Match.interp | 23 + .../match-parser/parser/Match.tokens | 4 + .../match-parser/parser/MatchLexer.interp | 26 + .../match-parser/parser/MatchLexer.tokens | 4 + .../parser/match_base_listener.go | 0 .../match-parser}/parser/match_lexer.go | 0 .../match-parser}/parser/match_listener.go | 0 .../match-parser}/parser/match_parser.go | 0 .../sshd_config/match-parser}/parser_test.go | 0 .../parser/handlers/sshd_config/Config.interp | 28 + .../parser/handlers/sshd_config/Config.tokens | 6 + .../handlers/sshd_config/ConfigLexer.interp | 32 + .../handlers/sshd_config/ConfigLexer.tokens | 6 + .../sshd_config/config_base_listener.go | 64 + .../handlers/sshd_config/config_lexer.go | 122 ++ .../handlers/sshd_config/config_listener.go | 52 + .../handlers/sshd_config/config_parser.go | 1254 +++++++++++++++++ handlers/sshd_config/shared.go | 4 +- handlers/sshd_config/test_utils/input.go | 6 +- 52 files changed, 2914 insertions(+), 109 deletions(-) rename {common/parsers/openssh-match-parser => handlers/sshd_config/match-parser}/Match.g4 (100%) rename {common/parsers/openssh-match-parser => handlers/sshd_config/match-parser}/error-listener.go (100%) rename {common/parsers/openssh-match-parser => handlers/sshd_config/match-parser}/full_test.go (100%) rename {common/parsers/openssh-match-parser/parser => handlers/sshd_config/match-parser/handlers/sshd_config/match-parser}/Match.interp (100%) rename {common/parsers/openssh-match-parser/parser => handlers/sshd_config/match-parser/handlers/sshd_config/match-parser}/Match.tokens (100%) rename {common/parsers/openssh-match-parser/parser => handlers/sshd_config/match-parser/handlers/sshd_config/match-parser}/MatchLexer.interp (100%) rename {common/parsers/openssh-match-parser/parser => handlers/sshd_config/match-parser/handlers/sshd_config/match-parser}/MatchLexer.tokens (100%) create mode 100644 handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/match_base_listener.go create mode 100644 handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/match_lexer.go create mode 100644 handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/match_listener.go create mode 100644 handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/match_parser.go rename {common/parsers/openssh-match-parser => handlers/sshd_config/match-parser}/listener.go (86%) rename {common/parsers/openssh-match-parser => handlers/sshd_config/match-parser}/match_ast.go (100%) rename {common/parsers/openssh-match-parser => handlers/sshd_config/match-parser}/match_fields.go (100%) rename {common/parsers/openssh-match-parser => handlers/sshd_config/match-parser}/parser.go (87%) create mode 100644 handlers/sshd_config/match-parser/parser/Match.interp create mode 100644 handlers/sshd_config/match-parser/parser/Match.tokens create mode 100644 handlers/sshd_config/match-parser/parser/MatchLexer.interp create mode 100644 handlers/sshd_config/match-parser/parser/MatchLexer.tokens rename {common/parsers/openssh-match-parser => handlers/sshd_config/match-parser}/parser/match_base_listener.go (100%) rename {common/parsers/openssh-match-parser => handlers/sshd_config/match-parser}/parser/match_lexer.go (100%) rename {common/parsers/openssh-match-parser => handlers/sshd_config/match-parser}/parser/match_listener.go (100%) rename {common/parsers/openssh-match-parser => handlers/sshd_config/match-parser}/parser/match_parser.go (100%) rename {common/parsers/openssh-match-parser => handlers/sshd_config/match-parser}/parser_test.go (100%) create mode 100644 handlers/sshd_config/parser/handlers/sshd_config/Config.interp create mode 100644 handlers/sshd_config/parser/handlers/sshd_config/Config.tokens create mode 100644 handlers/sshd_config/parser/handlers/sshd_config/ConfigLexer.interp create mode 100644 handlers/sshd_config/parser/handlers/sshd_config/ConfigLexer.tokens create mode 100644 handlers/sshd_config/parser/handlers/sshd_config/config_base_listener.go create mode 100644 handlers/sshd_config/parser/handlers/sshd_config/config_lexer.go create mode 100644 handlers/sshd_config/parser/handlers/sshd_config/config_listener.go create mode 100644 handlers/sshd_config/parser/handlers/sshd_config/config_parser.go diff --git a/handlers/ssh_config/Config.g4 b/handlers/ssh_config/Config.g4 index ad4cbe8..3033862 100644 --- a/handlers/ssh_config/Config.g4 +++ b/handlers/ssh_config/Config.g4 @@ -13,17 +13,23 @@ separator ; key - : STRING + : string ; value - : (STRING WHITESPACE)* STRING? WHITESPACE? + : (string WHITESPACE)* string? WHITESPACE? ; leadingComment - : HASH WHITESPACE? (STRING WHITESPACE?)+ + : HASH WHITESPACE? (string WHITESPACE?)+ ; +string + : (QUOTED_STRING | STRING) + ; + +/////////////////////////////////////////////// + HASH : '#' ; @@ -33,9 +39,13 @@ WHITESPACE ; STRING - : ~(' ' | '\t' | '\r' | '\n' | '#')+ + : ~('#' | '\r' | '\n' | '"' | ' ' | '\t')+ ; NEWLINE : '\r'? '\n' ; + +QUOTED_STRING + : '"' WHITESPACE? (STRING WHITESPACE)* STRING? ('"')? + ; diff --git a/handlers/sshd_config/analyzer/analyzer.go b/handlers/sshd_config/analyzer/analyzer.go index ffb15b9..3a204ea 100644 --- a/handlers/sshd_config/analyzer/analyzer.go +++ b/handlers/sshd_config/analyzer/analyzer.go @@ -10,7 +10,7 @@ import ( ) func Analyze( - d *sshdconfig.SSHDocument, + d *sshdconfig.SSHDDocument, ) []protocol.Diagnostic { errors := analyzeStructureIsValid(d) diff --git a/handlers/sshd_config/analyzer/include.go b/handlers/sshd_config/analyzer/include.go index 04164d8..3cf9833 100644 --- a/handlers/sshd_config/analyzer/include.go +++ b/handlers/sshd_config/analyzer/include.go @@ -17,7 +17,7 @@ import ( var whitespacePattern = regexp.MustCompile(`\S+`) func analyzeIncludeValues( - d *sshdconfig.SSHDocument, + d *sshdconfig.SSHDDocument, ) []common.LSPError { errs := make([]common.LSPError, 0) @@ -70,12 +70,12 @@ func createIncludePaths( func parseFile( filePath string, -) (*sshdconfig.SSHDocument, error) { +) (*sshdconfig.SSHDDocument, error) { if d, ok := sshdconfig.DocumentParserMap[filePath]; ok { return d, nil } - c := ast.NewSSHConfig() + c := ast.NewSSHDConfig() content, err := os.ReadFile(filePath) @@ -89,7 +89,7 @@ func parseFile( return nil, errors.New(fmt.Sprintf("Errors in %s", filePath)) } - d := &sshdconfig.SSHDocument{ + d := &sshdconfig.SSHDDocument{ Config: c, } diff --git a/handlers/sshd_config/analyzer/match.go b/handlers/sshd_config/analyzer/match.go index a150fef..9a2bb63 100644 --- a/handlers/sshd_config/analyzer/match.go +++ b/handlers/sshd_config/analyzer/match.go @@ -2,8 +2,8 @@ package analyzer import ( "config-lsp/common" - "config-lsp/common/parsers/openssh-match-parser" sshdconfig "config-lsp/handlers/sshd_config" + "config-lsp/handlers/sshd_config/match-parser" "config-lsp/utils" "errors" "fmt" @@ -11,7 +11,7 @@ import ( ) func analyzeMatchBlocks( - d *sshdconfig.SSHDocument, + d *sshdconfig.SSHDDocument, ) []common.LSPError { errs := make([]common.LSPError, 0) @@ -54,7 +54,7 @@ func analyzeMatchBlocks( } func analyzeMatchValueNegation( - value *matchparser.MatchValue, + value *matchparser.matchparser, ) []common.LSPError { errs := make([]common.LSPError, 0) diff --git a/handlers/sshd_config/analyzer/match_test.go b/handlers/sshd_config/analyzer/match_test.go index b65b478..c0b3cfe 100644 --- a/handlers/sshd_config/analyzer/match_test.go +++ b/handlers/sshd_config/analyzer/match_test.go @@ -15,7 +15,7 @@ func TestEmptyMatchBlocksMakesErrors( PermitRootLogin yes Match User root `) - c := ast.NewSSHConfig() + c := ast.NewSSHDConfig() errors := c.Parse(input) if len(errors) > 0 { @@ -28,7 +28,7 @@ Match User root t.Fatalf("Index error: %v", errors) } - d := &sshdconfig.SSHDocument{ + d := &sshdconfig.SSHDDocument{ Config: c, Indexes: indexes, } @@ -47,7 +47,7 @@ func TestContainsOnlyNegativeValues( PermitRootLogin yes Match User !root,!admin `) - c := ast.NewSSHConfig() + c := ast.NewSSHDConfig() errors := c.Parse(input) if len(errors) > 0 { diff --git a/handlers/sshd_config/analyzer/options.go b/handlers/sshd_config/analyzer/options.go index 3f19923..10ba045 100644 --- a/handlers/sshd_config/analyzer/options.go +++ b/handlers/sshd_config/analyzer/options.go @@ -12,7 +12,7 @@ import ( ) func analyzeStructureIsValid( - d *sshdconfig.SSHDocument, + d *sshdconfig.SSHDDocument, ) []common.LSPError { errs := make([]common.LSPError, 0) it := d.Config.Options.Iterator() diff --git a/handlers/sshd_config/analyzer/quotes.go b/handlers/sshd_config/analyzer/quotes.go index 33677c1..5d080f0 100644 --- a/handlers/sshd_config/analyzer/quotes.go +++ b/handlers/sshd_config/analyzer/quotes.go @@ -9,7 +9,7 @@ import ( ) func analyzeQuotesAreValid( - d *sshdconfig.SSHDocument, + d *sshdconfig.SSHDDocument, ) []common.LSPError { errs := make([]common.LSPError, 0) diff --git a/handlers/sshd_config/ast/listener.go b/handlers/sshd_config/ast/listener.go index 72816dc..2ffcdec 100644 --- a/handlers/sshd_config/ast/listener.go +++ b/handlers/sshd_config/ast/listener.go @@ -3,23 +3,23 @@ package ast import ( "config-lsp/common" commonparser "config-lsp/common/parser" - matchparser2 "config-lsp/common/parsers/openssh-match-parser" "config-lsp/handlers/sshd_config/ast/parser" + "config-lsp/handlers/sshd_config/match-parser" "strings" "github.com/emirpasic/gods/maps/treemap" gods "github.com/emirpasic/gods/utils" ) -type sshListenerContext struct { +type sshdListenerContext struct { line uint32 currentOption *SSHDOption currentMatchBlock *SSHDMatchBlock isKeyAMatchBlock bool } -func createSSHListenerContext() *sshListenerContext { - context := new(sshListenerContext) +func createListenerContext() *sshdListenerContext { + context := new(sshdListenerContext) context.isKeyAMatchBlock = false return context @@ -27,37 +27,37 @@ func createSSHListenerContext() *sshListenerContext { func createListener( config *SSHDConfig, - context *sshListenerContext, -) sshParserListener { - return sshParserListener{ - Config: config, - Errors: make([]common.LSPError, 0), - sshContext: context, + context *sshdListenerContext, +) sshdParserListener { + return sshdParserListener{ + Config: config, + Errors: make([]common.LSPError, 0), + sshdContext: context, } } -type sshParserListener struct { +type sshdParserListener struct { *parser.BaseConfigListener - Config *SSHDConfig - Errors []common.LSPError - sshContext *sshListenerContext + Config *SSHDConfig + Errors []common.LSPError + sshdContext *sshdListenerContext } -func (s *sshParserListener) EnterEntry(ctx *parser.EntryContext) { +func (s *sshdParserListener) EnterEntry(ctx *parser.EntryContext) { location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext) - location.ChangeBothLines(s.sshContext.line) + location.ChangeBothLines(s.sshdContext.line) option := &SSHDOption{ LocationRange: location, Value: commonparser.ParseRawString(ctx.GetText(), commonparser.FullFeatures), } - s.sshContext.currentOption = option + s.sshdContext.currentOption = option } -func (s *sshParserListener) EnterKey(ctx *parser.KeyContext) { +func (s *sshdParserListener) EnterKey(ctx *parser.KeyContext) { location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext) - location.ChangeBothLines(s.sshContext.line) + location.ChangeBothLines(s.sshdContext.line) text := ctx.GetText() value := commonparser.ParseRawString(text, commonparser.FullFeatures) @@ -70,63 +70,63 @@ func (s *sshParserListener) EnterKey(ctx *parser.KeyContext) { ) if strings.ToLower(text) == "match" { - s.sshContext.isKeyAMatchBlock = true + s.sshdContext.isKeyAMatchBlock = true } - s.sshContext.currentOption.Key = &SSHDKey{ + s.sshdContext.currentOption.Key = &SSHDKey{ LocationRange: location, Value: value, Key: key, } } -func (s *sshParserListener) EnterSeparator(ctx *parser.SeparatorContext) { +func (s *sshdParserListener) EnterSeparator(ctx *parser.SeparatorContext) { location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext) - location.ChangeBothLines(s.sshContext.line) + location.ChangeBothLines(s.sshdContext.line) text := ctx.GetText() value := commonparser.ParseRawString(text, commonparser.FullFeatures) - s.sshContext.currentOption.Separator = &SSHDSeparator{ + s.sshdContext.currentOption.Separator = &SSHDSeparator{ LocationRange: location, Value: value, } } -func (s *sshParserListener) EnterValue(ctx *parser.ValueContext) { +func (s *sshdParserListener) EnterValue(ctx *parser.ValueContext) { location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext) - location.ChangeBothLines(s.sshContext.line) + location.ChangeBothLines(s.sshdContext.line) - s.sshContext.currentOption.OptionValue = &SSHDValue{ + s.sshdContext.currentOption.OptionValue = &SSHDValue{ LocationRange: location, Value: commonparser.ParseRawString(ctx.GetText(), commonparser.FullFeatures), } } -func (s *sshParserListener) ExitEntry(ctx *parser.EntryContext) { +func (s *sshdParserListener) ExitEntry(ctx *parser.EntryContext) { location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext) - location.ChangeBothLines(s.sshContext.line) + location.ChangeBothLines(s.sshdContext.line) defer (func() { - s.sshContext.currentOption = nil + s.sshdContext.currentOption = nil })() - if s.sshContext.isKeyAMatchBlock { + if s.sshdContext.isKeyAMatchBlock { // Add new match block - var match *matchparser2.Match + var match *matchparser.Match - if s.sshContext.currentOption.OptionValue != nil { - matchParser := matchparser2.NewMatch() + if s.sshdContext.currentOption.OptionValue != nil { + matchParser := matchparser.NewMatch() errors := matchParser.Parse( - s.sshContext.currentOption.OptionValue.Value.Raw, + s.sshdContext.currentOption.OptionValue.Value.Raw, location.Start.Line, - s.sshContext.currentOption.OptionValue.Start.Character, + s.sshdContext.currentOption.OptionValue.Start.Character, ) if len(errors) > 0 { for _, err := range errors { s.Errors = append(s.Errors, common.LSPError{ - Range: err.Range.ShiftHorizontal(s.sshContext.currentOption.Start.Character), + Range: err.Range.ShiftHorizontal(s.sshdContext.currentOption.Start.Character), Err: err.Err, }) } @@ -137,7 +137,7 @@ func (s *sshParserListener) ExitEntry(ctx *parser.EntryContext) { matchBlock := &SSHDMatchBlock{ LocationRange: location, - MatchOption: s.sshContext.currentOption, + MatchOption: s.sshdContext.currentOption, MatchValue: match, Options: treemap.NewWith(gods.UInt32Comparator), } @@ -146,23 +146,23 @@ func (s *sshParserListener) ExitEntry(ctx *parser.EntryContext) { matchBlock, ) - s.sshContext.currentMatchBlock = matchBlock + s.sshdContext.currentMatchBlock = matchBlock - s.sshContext.isKeyAMatchBlock = false + s.sshdContext.isKeyAMatchBlock = false return } - if s.sshContext.currentMatchBlock != nil { - s.sshContext.currentMatchBlock.Options.Put( + if s.sshdContext.currentMatchBlock != nil { + s.sshdContext.currentMatchBlock.Options.Put( location.Start.Line, - s.sshContext.currentOption, + s.sshdContext.currentOption, ) - s.sshContext.currentMatchBlock.End = s.sshContext.currentOption.End + s.sshdContext.currentMatchBlock.End = s.sshdContext.currentOption.End } else { s.Config.Options.Put( location.Start.Line, - s.sshContext.currentOption, + s.sshdContext.currentOption, ) } } diff --git a/handlers/sshd_config/ast/parser.go b/handlers/sshd_config/ast/parser.go index 75c9523..d979799 100644 --- a/handlers/sshd_config/ast/parser.go +++ b/handlers/sshd_config/ast/parser.go @@ -12,7 +12,7 @@ import ( gods "github.com/emirpasic/gods/utils" ) -func NewSSHConfig() *SSHDConfig { +func NewSSHDConfig() *SSHDConfig { config := &SSHDConfig{} config.Clear() @@ -30,7 +30,7 @@ var emptyPattern = regexp.MustCompile(`^\s*$`) func (c *SSHDConfig) Parse(input string) []common.LSPError { errors := make([]common.LSPError, 0) lines := utils.SplitIntoLines(input) - context := createSSHListenerContext() + context := createListenerContext() for rawLineNumber, line := range lines { context.line = uint32(rawLineNumber) @@ -54,7 +54,7 @@ func (c *SSHDConfig) Parse(input string) []common.LSPError { } func (c *SSHDConfig) parseStatement( - context *sshListenerContext, + context *sshdListenerContext, input string, ) []common.LSPError { stream := antlr.NewInputStream(input) diff --git a/handlers/sshd_config/ast/parser_test.go b/handlers/sshd_config/ast/parser_test.go index 423c6b2..ca2ceb8 100644 --- a/handlers/sshd_config/ast/parser_test.go +++ b/handlers/sshd_config/ast/parser_test.go @@ -12,7 +12,7 @@ func TestSimpleParserExample( PermitRootLogin no PasswordAuthentication yes `) - p := NewSSHConfig() + p := NewSSHDConfig() errors := p.Parse(input) if len(errors) != 0 { @@ -68,7 +68,7 @@ PermitRootLogin no Match Address 192.168.0.1 PasswordAuthentication yes `) - p := NewSSHConfig() + p := NewSSHDConfig() errors := p.Parse(input) if len(errors) != 0 { @@ -117,7 +117,7 @@ func TestMultipleEntriesInMatchBlock( input := utils.Dedent(` Match User lena User root `) - p := NewSSHConfig() + p := NewSSHDConfig() errors := p.Parse(input) if len(errors) != 0 { @@ -148,7 +148,7 @@ func TestIncompleteMatchBlock( ) { input := "Match User lena User " - p := NewSSHConfig() + p := NewSSHDConfig() errors := p.Parse(input) if !(len(errors) == 0) { @@ -183,7 +183,7 @@ Match User lena Match Address 192.168.0.2 MaxAuthTries 3 `) - p := NewSSHConfig() + p := NewSSHDConfig() errors := p.Parse(input) if len(errors) != 0 { @@ -263,7 +263,7 @@ Port 22 AddressFamily any Sample `) - p := NewSSHConfig() + p := NewSSHDConfig() errors := p.Parse(input) if len(errors) != 0 { @@ -309,7 +309,7 @@ func TestIncompleteExample( input := utils.Dedent(` MACs `) - p := NewSSHConfig() + p := NewSSHDConfig() errors := p.Parse(input) if len(errors) != 0 { @@ -470,7 +470,7 @@ Match Address 172.22.100.0/24,172.22.5.0/24,127.0.0.1 PermitRootLogin without-password PasswordAuthentication yes `) - p := NewSSHConfig() + p := NewSSHDConfig() errors := p.Parse(input) if len(errors) != 0 { @@ -551,7 +551,7 @@ func TestQuotedOptionExample( input := utils.Dedent(` PermitRootLogin "no" `) - p := NewSSHConfig() + p := NewSSHDConfig() errors := p.Parse(input) if len(errors) != 0 { @@ -585,7 +585,7 @@ func TestQuotedKeyExample( input := utils.Dedent(` "PermitRootLogin" no `) - p := NewSSHConfig() + p := NewSSHDConfig() errors := p.Parse(input) if len(errors) != 0 { @@ -623,7 +623,7 @@ func TestQuotedValueWithSpacesExample( input := utils.Dedent(` PermitRootLogin "no yes maybe" `) - p := NewSSHConfig() + p := NewSSHDConfig() errors := p.Parse(input) if len(errors) != 0 { diff --git a/handlers/sshd_config/ast/sshd_config.go b/handlers/sshd_config/ast/sshd_config.go index 72933b0..28fbb75 100644 --- a/handlers/sshd_config/ast/sshd_config.go +++ b/handlers/sshd_config/ast/sshd_config.go @@ -3,7 +3,7 @@ package ast import ( "config-lsp/common" commonparser "config-lsp/common/parser" - "config-lsp/common/parsers/openssh-match-parser" + "config-lsp/handlers/sshd_config/match-parser" "github.com/emirpasic/gods/maps/treemap" ) @@ -47,7 +47,7 @@ type SSHDOption struct { type SSHDMatchBlock struct { common.LocationRange MatchOption *SSHDOption - MatchValue *matchparser.Match + MatchValue *matchparser.matchparser // [uint32]*SSHDOption -> line number -> *SSHDOption Options *treemap.Map diff --git a/handlers/sshd_config/handlers/completions.go b/handlers/sshd_config/handlers/completions.go index d6f2ca2..827b636 100644 --- a/handlers/sshd_config/handlers/completions.go +++ b/handlers/sshd_config/handlers/completions.go @@ -12,7 +12,7 @@ import ( ) func GetRootCompletions( - d *sshdconfig.SSHDocument, + d *sshdconfig.SSHDDocument, parentMatchBlock *ast.SSHDMatchBlock, suggestValue bool, ) ([]protocol.CompletionItem, error) { @@ -72,7 +72,7 @@ func GetRootCompletions( } func GetOptionCompletions( - d *sshdconfig.SSHDocument, + d *sshdconfig.SSHDDocument, entry *ast.SSHDOption, matchBlock *ast.SSHDMatchBlock, cursor common.CursorPosition, diff --git a/handlers/sshd_config/handlers/completions_match.go b/handlers/sshd_config/handlers/completions_match.go index 0d13fd5..9d225a1 100644 --- a/handlers/sshd_config/handlers/completions_match.go +++ b/handlers/sshd_config/handlers/completions_match.go @@ -2,16 +2,16 @@ package handlers import ( "config-lsp/common" - "config-lsp/common/parsers/openssh-match-parser" sshdconfig "config-lsp/handlers/sshd_config" "config-lsp/handlers/sshd_config/fields" + "config-lsp/handlers/sshd_config/match-parser" protocol "github.com/tliron/glsp/protocol_3_16" ) func getMatchCompletions( - d *sshdconfig.SSHDocument, + d *sshdconfig.SSHDDocument, cursor common.CursorPosition, - match *matchparser.Match, + match *matchparser.matchparser, ) ([]protocol.CompletionItem, error) { if match == nil || len(match.Entries) == 0 { completions := getMatchCriteriaCompletions() diff --git a/handlers/sshd_config/handlers/formatting.go b/handlers/sshd_config/handlers/formatting.go index 38aa0e4..4521fd4 100644 --- a/handlers/sshd_config/handlers/formatting.go +++ b/handlers/sshd_config/handlers/formatting.go @@ -8,7 +8,7 @@ import ( ) func FormatDocument( - d *sshdconfig.SSHDocument, + d *sshdconfig.SSHDDocument, textRange protocol.Range, options protocol.FormattingOptions, ) ([]protocol.TextEdit, error) { diff --git a/handlers/sshd_config/handlers/formatting_nodes.go b/handlers/sshd_config/handlers/formatting_nodes.go index e0e9bf3..1f521f7 100644 --- a/handlers/sshd_config/handlers/formatting_nodes.go +++ b/handlers/sshd_config/handlers/formatting_nodes.go @@ -2,8 +2,8 @@ package handlers import ( "config-lsp/common/formatting" - "config-lsp/common/parsers/openssh-match-parser" "config-lsp/handlers/sshd_config/ast" + "config-lsp/handlers/sshd_config/match-parser" "config-lsp/utils" "fmt" "strings" @@ -80,7 +80,7 @@ func formatSSHDMatchBlock( } func formatMatchToString( - match *matchparser.Match, + match *matchparser.matchparser, ) string { entriesAsStrings := utils.Map( match.Entries, diff --git a/handlers/sshd_config/handlers/formatting_test.go b/handlers/sshd_config/handlers/formatting_test.go index 3a15d89..631ae6f 100644 --- a/handlers/sshd_config/handlers/formatting_test.go +++ b/handlers/sshd_config/handlers/formatting_test.go @@ -17,7 +17,7 @@ func TestSimpleFormattingExampleWorks( PermitRootLogin yes a b `) - config := ast.NewSSHConfig() + config := ast.NewSSHDConfig() errors := config.Parse(input) if len(errors) > 0 { @@ -30,7 +30,7 @@ a b t.Fatalf("Failed to create indexes: %v", errors) } - d := sshdconfig.SSHDocument{ + d := sshdconfig.SSHDDocument{ Config: config, Indexes: i, } diff --git a/handlers/sshd_config/indexes/indexes_test.go b/handlers/sshd_config/indexes/indexes_test.go index cc4be38..25a772d 100644 --- a/handlers/sshd_config/indexes/indexes_test.go +++ b/handlers/sshd_config/indexes/indexes_test.go @@ -20,7 +20,7 @@ Match Address 192.168.0.1/24 RoomLogin yes PermitRootLogin yes `) - config := ast.NewSSHConfig() + config := ast.NewSSHDConfig() errors := config.Parse(input) if len(errors) > 0 { @@ -54,7 +54,7 @@ func TestIncludeExample( PermitRootLogin yes Include /etc/ssh/sshd_config.d/*.conf hello_world `) - config := ast.NewSSHConfig() + config := ast.NewSSHDConfig() errors := config.Parse(input) if len(errors) > 0 { diff --git a/handlers/sshd_config/lsp/text-document-did-open.go b/handlers/sshd_config/lsp/text-document-did-open.go index 24bb7c0..2fc07a8 100644 --- a/handlers/sshd_config/lsp/text-document-did-open.go +++ b/handlers/sshd_config/lsp/text-document-did-open.go @@ -17,13 +17,13 @@ func TextDocumentDidOpen( ) error { common.ClearDiagnostics(context, params.TextDocument.URI) - var document *sshdconfig.SSHDocument + var document *sshdconfig.SSHDDocument if foundDocument, ok := sshdconfig.DocumentParserMap[params.TextDocument.URI]; ok { document = foundDocument } else { - config := ast.NewSSHConfig() - document = &sshdconfig.SSHDocument{ + config := ast.NewSSHDConfig() + document = &sshdconfig.SSHDDocument{ Config: config, } sshdconfig.DocumentParserMap[params.TextDocument.URI] = document diff --git a/common/parsers/openssh-match-parser/Match.g4 b/handlers/sshd_config/match-parser/Match.g4 similarity index 100% rename from common/parsers/openssh-match-parser/Match.g4 rename to handlers/sshd_config/match-parser/Match.g4 diff --git a/common/parsers/openssh-match-parser/error-listener.go b/handlers/sshd_config/match-parser/error-listener.go similarity index 100% rename from common/parsers/openssh-match-parser/error-listener.go rename to handlers/sshd_config/match-parser/error-listener.go diff --git a/common/parsers/openssh-match-parser/full_test.go b/handlers/sshd_config/match-parser/full_test.go similarity index 100% rename from common/parsers/openssh-match-parser/full_test.go rename to handlers/sshd_config/match-parser/full_test.go diff --git a/common/parsers/openssh-match-parser/parser/Match.interp b/handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/Match.interp similarity index 100% rename from common/parsers/openssh-match-parser/parser/Match.interp rename to handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/Match.interp diff --git a/common/parsers/openssh-match-parser/parser/Match.tokens b/handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/Match.tokens similarity index 100% rename from common/parsers/openssh-match-parser/parser/Match.tokens rename to handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/Match.tokens diff --git a/common/parsers/openssh-match-parser/parser/MatchLexer.interp b/handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/MatchLexer.interp similarity index 100% rename from common/parsers/openssh-match-parser/parser/MatchLexer.interp rename to handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/MatchLexer.interp diff --git a/common/parsers/openssh-match-parser/parser/MatchLexer.tokens b/handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/MatchLexer.tokens similarity index 100% rename from common/parsers/openssh-match-parser/parser/MatchLexer.tokens rename to handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/MatchLexer.tokens diff --git a/handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/match_base_listener.go b/handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/match_base_listener.go new file mode 100644 index 0000000..f9cb3e5 --- /dev/null +++ b/handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/match_base_listener.go @@ -0,0 +1,58 @@ +// Code generated from handlers/sshd_config/match-parser/Match.g4 by ANTLR 4.13.0. DO NOT EDIT. + +package parser // Match + +import "github.com/antlr4-go/antlr/v4" + +// BaseMatchListener is a complete listener for a parse tree produced by MatchParser. +type BaseMatchListener struct{} + +var _ MatchListener = &BaseMatchListener{} + +// VisitTerminal is called when a terminal node is visited. +func (s *BaseMatchListener) VisitTerminal(node antlr.TerminalNode) {} + +// VisitErrorNode is called when an error node is visited. +func (s *BaseMatchListener) VisitErrorNode(node antlr.ErrorNode) {} + +// EnterEveryRule is called when any rule is entered. +func (s *BaseMatchListener) EnterEveryRule(ctx antlr.ParserRuleContext) {} + +// ExitEveryRule is called when any rule is exited. +func (s *BaseMatchListener) ExitEveryRule(ctx antlr.ParserRuleContext) {} + +// EnterRoot is called when production root is entered. +func (s *BaseMatchListener) EnterRoot(ctx *RootContext) {} + +// ExitRoot is called when production root is exited. +func (s *BaseMatchListener) ExitRoot(ctx *RootContext) {} + +// EnterMatchEntry is called when production matchEntry is entered. +func (s *BaseMatchListener) EnterMatchEntry(ctx *MatchEntryContext) {} + +// ExitMatchEntry is called when production matchEntry is exited. +func (s *BaseMatchListener) ExitMatchEntry(ctx *MatchEntryContext) {} + +// EnterSeparator is called when production separator is entered. +func (s *BaseMatchListener) EnterSeparator(ctx *SeparatorContext) {} + +// ExitSeparator is called when production separator is exited. +func (s *BaseMatchListener) ExitSeparator(ctx *SeparatorContext) {} + +// EnterCriteria is called when production criteria is entered. +func (s *BaseMatchListener) EnterCriteria(ctx *CriteriaContext) {} + +// ExitCriteria is called when production criteria is exited. +func (s *BaseMatchListener) ExitCriteria(ctx *CriteriaContext) {} + +// EnterValues is called when production values is entered. +func (s *BaseMatchListener) EnterValues(ctx *ValuesContext) {} + +// ExitValues is called when production values is exited. +func (s *BaseMatchListener) ExitValues(ctx *ValuesContext) {} + +// EnterValue is called when production value is entered. +func (s *BaseMatchListener) EnterValue(ctx *ValueContext) {} + +// ExitValue is called when production value is exited. +func (s *BaseMatchListener) ExitValue(ctx *ValueContext) {} diff --git a/handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/match_lexer.go b/handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/match_lexer.go new file mode 100644 index 0000000..42d3891 --- /dev/null +++ b/handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/match_lexer.go @@ -0,0 +1,109 @@ +// Code generated from handlers/sshd_config/match-parser/Match.g4 by ANTLR 4.13.0. DO NOT EDIT. + +package parser + +import ( + "fmt" + "github.com/antlr4-go/antlr/v4" + "sync" + "unicode" +) + +// Suppress unused import error +var _ = fmt.Printf +var _ = sync.Once{} +var _ = unicode.IsLetter + +type MatchLexer struct { + *antlr.BaseLexer + channelNames []string + modeNames []string + // TODO: EOF string +} + +var MatchLexerLexerStaticData struct { + once sync.Once + serializedATN []int32 + ChannelNames []string + ModeNames []string + LiteralNames []string + SymbolicNames []string + RuleNames []string + PredictionContextCache *antlr.PredictionContextCache + atn *antlr.ATN + decisionToDFA []*antlr.DFA +} + +func matchlexerLexerInit() { + staticData := &MatchLexerLexerStaticData + staticData.ChannelNames = []string{ + "DEFAULT_TOKEN_CHANNEL", "HIDDEN", + } + staticData.ModeNames = []string{ + "DEFAULT_MODE", + } + staticData.LiteralNames = []string{ + "", "','", + } + staticData.SymbolicNames = []string{ + "", "COMMA", "STRING", "WHITESPACE", + } + staticData.RuleNames = []string{ + "COMMA", "STRING", "WHITESPACE", + } + staticData.PredictionContextCache = antlr.NewPredictionContextCache() + staticData.serializedATN = []int32{ + 4, 0, 3, 19, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 1, 0, 1, 0, 1, + 1, 4, 1, 11, 8, 1, 11, 1, 12, 1, 12, 1, 2, 4, 2, 16, 8, 2, 11, 2, 12, 2, + 17, 0, 0, 3, 1, 1, 3, 2, 5, 3, 1, 0, 2, 5, 0, 9, 10, 13, 13, 32, 32, 35, + 35, 44, 44, 2, 0, 9, 9, 32, 32, 20, 0, 1, 1, 0, 0, 0, 0, 3, 1, 0, 0, 0, + 0, 5, 1, 0, 0, 0, 1, 7, 1, 0, 0, 0, 3, 10, 1, 0, 0, 0, 5, 15, 1, 0, 0, + 0, 7, 8, 5, 44, 0, 0, 8, 2, 1, 0, 0, 0, 9, 11, 8, 0, 0, 0, 10, 9, 1, 0, + 0, 0, 11, 12, 1, 0, 0, 0, 12, 10, 1, 0, 0, 0, 12, 13, 1, 0, 0, 0, 13, 4, + 1, 0, 0, 0, 14, 16, 7, 1, 0, 0, 15, 14, 1, 0, 0, 0, 16, 17, 1, 0, 0, 0, + 17, 15, 1, 0, 0, 0, 17, 18, 1, 0, 0, 0, 18, 6, 1, 0, 0, 0, 3, 0, 12, 17, + 0, + } + deserializer := antlr.NewATNDeserializer(nil) + staticData.atn = deserializer.Deserialize(staticData.serializedATN) + atn := staticData.atn + staticData.decisionToDFA = make([]*antlr.DFA, len(atn.DecisionToState)) + decisionToDFA := staticData.decisionToDFA + for index, state := range atn.DecisionToState { + decisionToDFA[index] = antlr.NewDFA(state, index) + } +} + +// MatchLexerInit initializes any static state used to implement MatchLexer. By default the +// static state used to implement the lexer is lazily initialized during the first call to +// NewMatchLexer(). You can call this function if you wish to initialize the static state ahead +// of time. +func MatchLexerInit() { + staticData := &MatchLexerLexerStaticData + staticData.once.Do(matchlexerLexerInit) +} + +// NewMatchLexer produces a new lexer instance for the optional input antlr.CharStream. +func NewMatchLexer(input antlr.CharStream) *MatchLexer { + MatchLexerInit() + l := new(MatchLexer) + l.BaseLexer = antlr.NewBaseLexer(input) + staticData := &MatchLexerLexerStaticData + l.Interpreter = antlr.NewLexerATNSimulator(l, staticData.atn, staticData.decisionToDFA, staticData.PredictionContextCache) + l.channelNames = staticData.ChannelNames + l.modeNames = staticData.ModeNames + l.RuleNames = staticData.RuleNames + l.LiteralNames = staticData.LiteralNames + l.SymbolicNames = staticData.SymbolicNames + l.GrammarFileName = "Match.g4" + // TODO: l.EOF = antlr.TokenEOF + + return l +} + +// MatchLexer tokens. +const ( + MatchLexerCOMMA = 1 + MatchLexerSTRING = 2 + MatchLexerWHITESPACE = 3 +) diff --git a/handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/match_listener.go b/handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/match_listener.go new file mode 100644 index 0000000..d13801e --- /dev/null +++ b/handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/match_listener.go @@ -0,0 +1,46 @@ +// Code generated from handlers/sshd_config/match-parser/Match.g4 by ANTLR 4.13.0. DO NOT EDIT. + +package parser // Match + +import "github.com/antlr4-go/antlr/v4" + +// MatchListener is a complete listener for a parse tree produced by MatchParser. +type MatchListener interface { + antlr.ParseTreeListener + + // EnterRoot is called when entering the root production. + EnterRoot(c *RootContext) + + // EnterMatchEntry is called when entering the matchEntry production. + EnterMatchEntry(c *MatchEntryContext) + + // EnterSeparator is called when entering the separator production. + EnterSeparator(c *SeparatorContext) + + // EnterCriteria is called when entering the criteria production. + EnterCriteria(c *CriteriaContext) + + // EnterValues is called when entering the values production. + EnterValues(c *ValuesContext) + + // EnterValue is called when entering the value production. + EnterValue(c *ValueContext) + + // ExitRoot is called when exiting the root production. + ExitRoot(c *RootContext) + + // ExitMatchEntry is called when exiting the matchEntry production. + ExitMatchEntry(c *MatchEntryContext) + + // ExitSeparator is called when exiting the separator production. + ExitSeparator(c *SeparatorContext) + + // ExitCriteria is called when exiting the criteria production. + ExitCriteria(c *CriteriaContext) + + // ExitValues is called when exiting the values production. + ExitValues(c *ValuesContext) + + // ExitValue is called when exiting the value production. + ExitValue(c *ValueContext) +} diff --git a/handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/match_parser.go b/handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/match_parser.go new file mode 100644 index 0000000..bde60cb --- /dev/null +++ b/handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/match_parser.go @@ -0,0 +1,961 @@ +// Code generated from handlers/sshd_config/match-parser/Match.g4 by ANTLR 4.13.0. DO NOT EDIT. + +package parser // Match + +import ( + "fmt" + "strconv" + "sync" + + "github.com/antlr4-go/antlr/v4" +) + +// Suppress unused import errors +var _ = fmt.Printf +var _ = strconv.Itoa +var _ = sync.Once{} + +type MatchParser struct { + *antlr.BaseParser +} + +var MatchParserStaticData struct { + once sync.Once + serializedATN []int32 + LiteralNames []string + SymbolicNames []string + RuleNames []string + PredictionContextCache *antlr.PredictionContextCache + atn *antlr.ATN + decisionToDFA []*antlr.DFA +} + +func matchParserInit() { + staticData := &MatchParserStaticData + staticData.LiteralNames = []string{ + "", "','", + } + staticData.SymbolicNames = []string{ + "", "COMMA", "STRING", "WHITESPACE", + } + staticData.RuleNames = []string{ + "root", "matchEntry", "separator", "criteria", "values", "value", + } + staticData.PredictionContextCache = antlr.NewPredictionContextCache() + staticData.serializedATN = []int32{ + 4, 1, 3, 52, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, + 2, 5, 7, 5, 1, 0, 3, 0, 14, 8, 0, 1, 0, 1, 0, 3, 0, 18, 8, 0, 5, 0, 20, + 8, 0, 10, 0, 12, 0, 23, 9, 0, 1, 0, 1, 0, 1, 1, 1, 1, 3, 1, 29, 8, 1, 1, + 1, 3, 1, 32, 8, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, 3, 4, 39, 8, 4, 1, 4, + 1, 4, 3, 4, 43, 8, 4, 5, 4, 45, 8, 4, 10, 4, 12, 4, 48, 9, 4, 1, 5, 1, + 5, 1, 5, 0, 0, 6, 0, 2, 4, 6, 8, 10, 0, 0, 53, 0, 13, 1, 0, 0, 0, 2, 26, + 1, 0, 0, 0, 4, 33, 1, 0, 0, 0, 6, 35, 1, 0, 0, 0, 8, 38, 1, 0, 0, 0, 10, + 49, 1, 0, 0, 0, 12, 14, 3, 2, 1, 0, 13, 12, 1, 0, 0, 0, 13, 14, 1, 0, 0, + 0, 14, 21, 1, 0, 0, 0, 15, 17, 5, 3, 0, 0, 16, 18, 3, 2, 1, 0, 17, 16, + 1, 0, 0, 0, 17, 18, 1, 0, 0, 0, 18, 20, 1, 0, 0, 0, 19, 15, 1, 0, 0, 0, + 20, 23, 1, 0, 0, 0, 21, 19, 1, 0, 0, 0, 21, 22, 1, 0, 0, 0, 22, 24, 1, + 0, 0, 0, 23, 21, 1, 0, 0, 0, 24, 25, 5, 0, 0, 1, 25, 1, 1, 0, 0, 0, 26, + 28, 3, 6, 3, 0, 27, 29, 3, 4, 2, 0, 28, 27, 1, 0, 0, 0, 28, 29, 1, 0, 0, + 0, 29, 31, 1, 0, 0, 0, 30, 32, 3, 8, 4, 0, 31, 30, 1, 0, 0, 0, 31, 32, + 1, 0, 0, 0, 32, 3, 1, 0, 0, 0, 33, 34, 5, 3, 0, 0, 34, 5, 1, 0, 0, 0, 35, + 36, 5, 2, 0, 0, 36, 7, 1, 0, 0, 0, 37, 39, 3, 10, 5, 0, 38, 37, 1, 0, 0, + 0, 38, 39, 1, 0, 0, 0, 39, 46, 1, 0, 0, 0, 40, 42, 5, 1, 0, 0, 41, 43, + 3, 10, 5, 0, 42, 41, 1, 0, 0, 0, 42, 43, 1, 0, 0, 0, 43, 45, 1, 0, 0, 0, + 44, 40, 1, 0, 0, 0, 45, 48, 1, 0, 0, 0, 46, 44, 1, 0, 0, 0, 46, 47, 1, + 0, 0, 0, 47, 9, 1, 0, 0, 0, 48, 46, 1, 0, 0, 0, 49, 50, 5, 2, 0, 0, 50, + 11, 1, 0, 0, 0, 8, 13, 17, 21, 28, 31, 38, 42, 46, + } + deserializer := antlr.NewATNDeserializer(nil) + staticData.atn = deserializer.Deserialize(staticData.serializedATN) + atn := staticData.atn + staticData.decisionToDFA = make([]*antlr.DFA, len(atn.DecisionToState)) + decisionToDFA := staticData.decisionToDFA + for index, state := range atn.DecisionToState { + decisionToDFA[index] = antlr.NewDFA(state, index) + } +} + +// MatchParserInit initializes any static state used to implement MatchParser. By default the +// static state used to implement the parser is lazily initialized during the first call to +// NewMatchParser(). You can call this function if you wish to initialize the static state ahead +// of time. +func MatchParserInit() { + staticData := &MatchParserStaticData + staticData.once.Do(matchParserInit) +} + +// NewMatchParser produces a new parser instance for the optional input antlr.TokenStream. +func NewMatchParser(input antlr.TokenStream) *MatchParser { + MatchParserInit() + this := new(MatchParser) + this.BaseParser = antlr.NewBaseParser(input) + staticData := &MatchParserStaticData + this.Interpreter = antlr.NewParserATNSimulator(this, staticData.atn, staticData.decisionToDFA, staticData.PredictionContextCache) + this.RuleNames = staticData.RuleNames + this.LiteralNames = staticData.LiteralNames + this.SymbolicNames = staticData.SymbolicNames + this.GrammarFileName = "Match.g4" + + return this +} + +// MatchParser tokens. +const ( + MatchParserEOF = antlr.TokenEOF + MatchParserCOMMA = 1 + MatchParserSTRING = 2 + MatchParserWHITESPACE = 3 +) + +// MatchParser rules. +const ( + MatchParserRULE_root = 0 + MatchParserRULE_matchEntry = 1 + MatchParserRULE_separator = 2 + MatchParserRULE_criteria = 3 + MatchParserRULE_values = 4 + MatchParserRULE_value = 5 +) + +// IRootContext is an interface to support dynamic dispatch. +type IRootContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + + // Getter signatures + EOF() antlr.TerminalNode + AllMatchEntry() []IMatchEntryContext + MatchEntry(i int) IMatchEntryContext + AllWHITESPACE() []antlr.TerminalNode + WHITESPACE(i int) antlr.TerminalNode + + // IsRootContext differentiates from other interfaces. + IsRootContext() +} + +type RootContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptyRootContext() *RootContext { + var p = new(RootContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = MatchParserRULE_root + return p +} + +func InitEmptyRootContext(p *RootContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = MatchParserRULE_root +} + +func (*RootContext) IsRootContext() {} + +func NewRootContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *RootContext { + var p = new(RootContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = MatchParserRULE_root + + return p +} + +func (s *RootContext) GetParser() antlr.Parser { return s.parser } + +func (s *RootContext) EOF() antlr.TerminalNode { + return s.GetToken(MatchParserEOF, 0) +} + +func (s *RootContext) AllMatchEntry() []IMatchEntryContext { + children := s.GetChildren() + len := 0 + for _, ctx := range children { + if _, ok := ctx.(IMatchEntryContext); ok { + len++ + } + } + + tst := make([]IMatchEntryContext, len) + i := 0 + for _, ctx := range children { + if t, ok := ctx.(IMatchEntryContext); ok { + tst[i] = t.(IMatchEntryContext) + i++ + } + } + + return tst +} + +func (s *RootContext) MatchEntry(i int) IMatchEntryContext { + var t antlr.RuleContext + j := 0 + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(IMatchEntryContext); ok { + if j == i { + t = ctx.(antlr.RuleContext) + break + } + j++ + } + } + + if t == nil { + return nil + } + + return t.(IMatchEntryContext) +} + +func (s *RootContext) AllWHITESPACE() []antlr.TerminalNode { + return s.GetTokens(MatchParserWHITESPACE) +} + +func (s *RootContext) WHITESPACE(i int) antlr.TerminalNode { + return s.GetToken(MatchParserWHITESPACE, i) +} + +func (s *RootContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *RootContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +func (s *RootContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(MatchListener); ok { + listenerT.EnterRoot(s) + } +} + +func (s *RootContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(MatchListener); ok { + listenerT.ExitRoot(s) + } +} + +func (p *MatchParser) Root() (localctx IRootContext) { + localctx = NewRootContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 0, MatchParserRULE_root) + var _la int + + p.EnterOuterAlt(localctx, 1) + p.SetState(13) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + if _la == MatchParserSTRING { + { + p.SetState(12) + p.MatchEntry() + } + + } + p.SetState(21) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + for _la == MatchParserWHITESPACE { + { + p.SetState(15) + p.Match(MatchParserWHITESPACE) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + p.SetState(17) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + if _la == MatchParserSTRING { + { + p.SetState(16) + p.MatchEntry() + } + + } + + p.SetState(23) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + } + { + p.SetState(24) + p.Match(MatchParserEOF) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} + +// IMatchEntryContext is an interface to support dynamic dispatch. +type IMatchEntryContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + + // Getter signatures + Criteria() ICriteriaContext + Separator() ISeparatorContext + Values() IValuesContext + + // IsMatchEntryContext differentiates from other interfaces. + IsMatchEntryContext() +} + +type MatchEntryContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptyMatchEntryContext() *MatchEntryContext { + var p = new(MatchEntryContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = MatchParserRULE_matchEntry + return p +} + +func InitEmptyMatchEntryContext(p *MatchEntryContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = MatchParserRULE_matchEntry +} + +func (*MatchEntryContext) IsMatchEntryContext() {} + +func NewMatchEntryContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *MatchEntryContext { + var p = new(MatchEntryContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = MatchParserRULE_matchEntry + + return p +} + +func (s *MatchEntryContext) GetParser() antlr.Parser { return s.parser } + +func (s *MatchEntryContext) Criteria() ICriteriaContext { + var t antlr.RuleContext + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(ICriteriaContext); ok { + t = ctx.(antlr.RuleContext) + break + } + } + + if t == nil { + return nil + } + + return t.(ICriteriaContext) +} + +func (s *MatchEntryContext) Separator() ISeparatorContext { + var t antlr.RuleContext + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(ISeparatorContext); ok { + t = ctx.(antlr.RuleContext) + break + } + } + + if t == nil { + return nil + } + + return t.(ISeparatorContext) +} + +func (s *MatchEntryContext) Values() IValuesContext { + var t antlr.RuleContext + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(IValuesContext); ok { + t = ctx.(antlr.RuleContext) + break + } + } + + if t == nil { + return nil + } + + return t.(IValuesContext) +} + +func (s *MatchEntryContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *MatchEntryContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +func (s *MatchEntryContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(MatchListener); ok { + listenerT.EnterMatchEntry(s) + } +} + +func (s *MatchEntryContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(MatchListener); ok { + listenerT.ExitMatchEntry(s) + } +} + +func (p *MatchParser) MatchEntry() (localctx IMatchEntryContext) { + localctx = NewMatchEntryContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 2, MatchParserRULE_matchEntry) + p.EnterOuterAlt(localctx, 1) + { + p.SetState(26) + p.Criteria() + } + p.SetState(28) + p.GetErrorHandler().Sync(p) + + if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 3, p.GetParserRuleContext()) == 1 { + { + p.SetState(27) + p.Separator() + } + + } else if p.HasError() { // JIM + goto errorExit + } + p.SetState(31) + p.GetErrorHandler().Sync(p) + + if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 4, p.GetParserRuleContext()) == 1 { + { + p.SetState(30) + p.Values() + } + + } else if p.HasError() { // JIM + goto errorExit + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} + +// ISeparatorContext is an interface to support dynamic dispatch. +type ISeparatorContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + + // Getter signatures + WHITESPACE() antlr.TerminalNode + + // IsSeparatorContext differentiates from other interfaces. + IsSeparatorContext() +} + +type SeparatorContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptySeparatorContext() *SeparatorContext { + var p = new(SeparatorContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = MatchParserRULE_separator + return p +} + +func InitEmptySeparatorContext(p *SeparatorContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = MatchParserRULE_separator +} + +func (*SeparatorContext) IsSeparatorContext() {} + +func NewSeparatorContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *SeparatorContext { + var p = new(SeparatorContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = MatchParserRULE_separator + + return p +} + +func (s *SeparatorContext) GetParser() antlr.Parser { return s.parser } + +func (s *SeparatorContext) WHITESPACE() antlr.TerminalNode { + return s.GetToken(MatchParserWHITESPACE, 0) +} + +func (s *SeparatorContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *SeparatorContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +func (s *SeparatorContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(MatchListener); ok { + listenerT.EnterSeparator(s) + } +} + +func (s *SeparatorContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(MatchListener); ok { + listenerT.ExitSeparator(s) + } +} + +func (p *MatchParser) Separator() (localctx ISeparatorContext) { + localctx = NewSeparatorContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 4, MatchParserRULE_separator) + p.EnterOuterAlt(localctx, 1) + { + p.SetState(33) + p.Match(MatchParserWHITESPACE) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} + +// ICriteriaContext is an interface to support dynamic dispatch. +type ICriteriaContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + + // Getter signatures + STRING() antlr.TerminalNode + + // IsCriteriaContext differentiates from other interfaces. + IsCriteriaContext() +} + +type CriteriaContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptyCriteriaContext() *CriteriaContext { + var p = new(CriteriaContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = MatchParserRULE_criteria + return p +} + +func InitEmptyCriteriaContext(p *CriteriaContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = MatchParserRULE_criteria +} + +func (*CriteriaContext) IsCriteriaContext() {} + +func NewCriteriaContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *CriteriaContext { + var p = new(CriteriaContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = MatchParserRULE_criteria + + return p +} + +func (s *CriteriaContext) GetParser() antlr.Parser { return s.parser } + +func (s *CriteriaContext) STRING() antlr.TerminalNode { + return s.GetToken(MatchParserSTRING, 0) +} + +func (s *CriteriaContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *CriteriaContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +func (s *CriteriaContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(MatchListener); ok { + listenerT.EnterCriteria(s) + } +} + +func (s *CriteriaContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(MatchListener); ok { + listenerT.ExitCriteria(s) + } +} + +func (p *MatchParser) Criteria() (localctx ICriteriaContext) { + localctx = NewCriteriaContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 6, MatchParserRULE_criteria) + p.EnterOuterAlt(localctx, 1) + { + p.SetState(35) + p.Match(MatchParserSTRING) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} + +// IValuesContext is an interface to support dynamic dispatch. +type IValuesContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + + // Getter signatures + AllValue() []IValueContext + Value(i int) IValueContext + AllCOMMA() []antlr.TerminalNode + COMMA(i int) antlr.TerminalNode + + // IsValuesContext differentiates from other interfaces. + IsValuesContext() +} + +type ValuesContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptyValuesContext() *ValuesContext { + var p = new(ValuesContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = MatchParserRULE_values + return p +} + +func InitEmptyValuesContext(p *ValuesContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = MatchParserRULE_values +} + +func (*ValuesContext) IsValuesContext() {} + +func NewValuesContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *ValuesContext { + var p = new(ValuesContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = MatchParserRULE_values + + return p +} + +func (s *ValuesContext) GetParser() antlr.Parser { return s.parser } + +func (s *ValuesContext) AllValue() []IValueContext { + children := s.GetChildren() + len := 0 + for _, ctx := range children { + if _, ok := ctx.(IValueContext); ok { + len++ + } + } + + tst := make([]IValueContext, len) + i := 0 + for _, ctx := range children { + if t, ok := ctx.(IValueContext); ok { + tst[i] = t.(IValueContext) + i++ + } + } + + return tst +} + +func (s *ValuesContext) Value(i int) IValueContext { + var t antlr.RuleContext + j := 0 + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(IValueContext); ok { + if j == i { + t = ctx.(antlr.RuleContext) + break + } + j++ + } + } + + if t == nil { + return nil + } + + return t.(IValueContext) +} + +func (s *ValuesContext) AllCOMMA() []antlr.TerminalNode { + return s.GetTokens(MatchParserCOMMA) +} + +func (s *ValuesContext) COMMA(i int) antlr.TerminalNode { + return s.GetToken(MatchParserCOMMA, i) +} + +func (s *ValuesContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *ValuesContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +func (s *ValuesContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(MatchListener); ok { + listenerT.EnterValues(s) + } +} + +func (s *ValuesContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(MatchListener); ok { + listenerT.ExitValues(s) + } +} + +func (p *MatchParser) Values() (localctx IValuesContext) { + localctx = NewValuesContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 8, MatchParserRULE_values) + var _la int + + p.EnterOuterAlt(localctx, 1) + p.SetState(38) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + if _la == MatchParserSTRING { + { + p.SetState(37) + p.Value() + } + + } + p.SetState(46) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + for _la == MatchParserCOMMA { + { + p.SetState(40) + p.Match(MatchParserCOMMA) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + p.SetState(42) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + if _la == MatchParserSTRING { + { + p.SetState(41) + p.Value() + } + + } + + p.SetState(48) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} + +// IValueContext is an interface to support dynamic dispatch. +type IValueContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + + // Getter signatures + STRING() antlr.TerminalNode + + // IsValueContext differentiates from other interfaces. + IsValueContext() +} + +type ValueContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptyValueContext() *ValueContext { + var p = new(ValueContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = MatchParserRULE_value + return p +} + +func InitEmptyValueContext(p *ValueContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = MatchParserRULE_value +} + +func (*ValueContext) IsValueContext() {} + +func NewValueContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *ValueContext { + var p = new(ValueContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = MatchParserRULE_value + + return p +} + +func (s *ValueContext) GetParser() antlr.Parser { return s.parser } + +func (s *ValueContext) STRING() antlr.TerminalNode { + return s.GetToken(MatchParserSTRING, 0) +} + +func (s *ValueContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *ValueContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +func (s *ValueContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(MatchListener); ok { + listenerT.EnterValue(s) + } +} + +func (s *ValueContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(MatchListener); ok { + listenerT.ExitValue(s) + } +} + +func (p *MatchParser) Value() (localctx IValueContext) { + localctx = NewValueContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 10, MatchParserRULE_value) + p.EnterOuterAlt(localctx, 1) + { + p.SetState(49) + p.Match(MatchParserSTRING) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} diff --git a/common/parsers/openssh-match-parser/listener.go b/handlers/sshd_config/match-parser/listener.go similarity index 86% rename from common/parsers/openssh-match-parser/listener.go rename to handlers/sshd_config/match-parser/listener.go index fc1f3b5..e8299a8 100644 --- a/common/parsers/openssh-match-parser/listener.go +++ b/handlers/sshd_config/match-parser/listener.go @@ -3,7 +3,7 @@ package matchparser import ( "config-lsp/common" commonparser "config-lsp/common/parser" - parser2 "config-lsp/common/parsers/openssh-match-parser/parser" + "config-lsp/handlers/sshd_config/match-parser/parser" "config-lsp/utils" "errors" "fmt" @@ -39,13 +39,13 @@ func createListener( } type matchParserListener struct { - *parser2.BaseMatchListener + *parser.BaseMatchListener match *Match Errors []common.LSPError matchContext *matchListenerContext } -func (s *matchParserListener) EnterMatchEntry(ctx *parser2.MatchEntryContext) { +func (s *matchParserListener) EnterMatchEntry(ctx *parser.MatchEntryContext) { location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext).ShiftHorizontal(s.matchContext.startCharacter) location.ChangeBothLines(s.matchContext.line) @@ -58,7 +58,7 @@ func (s *matchParserListener) EnterMatchEntry(ctx *parser2.MatchEntryContext) { s.matchContext.currentEntry = entry } -func (s *matchParserListener) ExitMatchEntry(ctx *parser2.MatchEntryContext) { +func (s *matchParserListener) ExitMatchEntry(ctx *parser.MatchEntryContext) { s.matchContext.currentEntry = nil } @@ -72,7 +72,7 @@ var availableCriteria = map[string]MatchCriteriaType{ string(MatchCriteriaTypeAddress): MatchCriteriaTypeAddress, } -func (s *matchParserListener) EnterCriteria(ctx *parser2.CriteriaContext) { +func (s *matchParserListener) EnterCriteria(ctx *parser.CriteriaContext) { location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext).ShiftHorizontal(s.matchContext.startCharacter) location.ChangeBothLines(s.matchContext.line) @@ -95,7 +95,7 @@ func (s *matchParserListener) EnterCriteria(ctx *parser2.CriteriaContext) { } } -func (s *matchParserListener) EnterSeparator(ctx *parser2.SeparatorContext) { +func (s *matchParserListener) EnterSeparator(ctx *parser.SeparatorContext) { location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext).ShiftHorizontal(s.matchContext.startCharacter) location.ChangeBothLines(s.matchContext.line) @@ -104,7 +104,7 @@ func (s *matchParserListener) EnterSeparator(ctx *parser2.SeparatorContext) { } } -func (s *matchParserListener) EnterValues(ctx *parser2.ValuesContext) { +func (s *matchParserListener) EnterValues(ctx *parser.ValuesContext) { location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext).ShiftHorizontal(s.matchContext.startCharacter) location.ChangeBothLines(s.matchContext.line) @@ -114,7 +114,7 @@ func (s *matchParserListener) EnterValues(ctx *parser2.ValuesContext) { } } -func (s *matchParserListener) EnterValue(ctx *parser2.ValueContext) { +func (s *matchParserListener) EnterValue(ctx *parser.ValueContext) { location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext).ShiftHorizontal(s.matchContext.startCharacter) location.ChangeBothLines(s.matchContext.line) diff --git a/common/parsers/openssh-match-parser/match_ast.go b/handlers/sshd_config/match-parser/match_ast.go similarity index 100% rename from common/parsers/openssh-match-parser/match_ast.go rename to handlers/sshd_config/match-parser/match_ast.go diff --git a/common/parsers/openssh-match-parser/match_fields.go b/handlers/sshd_config/match-parser/match_fields.go similarity index 100% rename from common/parsers/openssh-match-parser/match_fields.go rename to handlers/sshd_config/match-parser/match_fields.go diff --git a/common/parsers/openssh-match-parser/parser.go b/handlers/sshd_config/match-parser/parser.go similarity index 87% rename from common/parsers/openssh-match-parser/parser.go rename to handlers/sshd_config/match-parser/parser.go index b4abe9e..b61d4de 100644 --- a/common/parsers/openssh-match-parser/parser.go +++ b/handlers/sshd_config/match-parser/parser.go @@ -2,7 +2,7 @@ package matchparser import ( "config-lsp/common" - parser2 "config-lsp/common/parsers/openssh-match-parser/parser" + "config-lsp/handlers/sshd_config/match-parser/parser" "github.com/antlr4-go/antlr/v4" ) @@ -27,14 +27,14 @@ func (m *Match) Parse( stream := antlr.NewInputStream(input) lexerErrorListener := createErrorListener(context.line) - lexer := parser2.NewMatchLexer(stream) + lexer := parser.NewMatchLexer(stream) lexer.RemoveErrorListeners() lexer.AddErrorListener(&lexerErrorListener) tokenStream := antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel) parserErrorListener := createErrorListener(context.line) - antlrParser := parser2.NewMatchParser(tokenStream) + antlrParser := parser.NewMatchParser(tokenStream) antlrParser.RemoveErrorListeners() antlrParser.AddErrorListener(&parserErrorListener) diff --git a/handlers/sshd_config/match-parser/parser/Match.interp b/handlers/sshd_config/match-parser/parser/Match.interp new file mode 100644 index 0000000..491bdd3 --- /dev/null +++ b/handlers/sshd_config/match-parser/parser/Match.interp @@ -0,0 +1,23 @@ +token literal names: +null +',' +null +null + +token symbolic names: +null +COMMA +STRING +WHITESPACE + +rule names: +root +matchEntry +separator +criteria +values +value + + +atn: +[4, 1, 3, 52, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 2, 5, 7, 5, 1, 0, 3, 0, 14, 8, 0, 1, 0, 1, 0, 3, 0, 18, 8, 0, 5, 0, 20, 8, 0, 10, 0, 12, 0, 23, 9, 0, 1, 0, 1, 0, 1, 1, 1, 1, 3, 1, 29, 8, 1, 1, 1, 3, 1, 32, 8, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, 3, 4, 39, 8, 4, 1, 4, 1, 4, 3, 4, 43, 8, 4, 5, 4, 45, 8, 4, 10, 4, 12, 4, 48, 9, 4, 1, 5, 1, 5, 1, 5, 0, 0, 6, 0, 2, 4, 6, 8, 10, 0, 0, 53, 0, 13, 1, 0, 0, 0, 2, 26, 1, 0, 0, 0, 4, 33, 1, 0, 0, 0, 6, 35, 1, 0, 0, 0, 8, 38, 1, 0, 0, 0, 10, 49, 1, 0, 0, 0, 12, 14, 3, 2, 1, 0, 13, 12, 1, 0, 0, 0, 13, 14, 1, 0, 0, 0, 14, 21, 1, 0, 0, 0, 15, 17, 5, 3, 0, 0, 16, 18, 3, 2, 1, 0, 17, 16, 1, 0, 0, 0, 17, 18, 1, 0, 0, 0, 18, 20, 1, 0, 0, 0, 19, 15, 1, 0, 0, 0, 20, 23, 1, 0, 0, 0, 21, 19, 1, 0, 0, 0, 21, 22, 1, 0, 0, 0, 22, 24, 1, 0, 0, 0, 23, 21, 1, 0, 0, 0, 24, 25, 5, 0, 0, 1, 25, 1, 1, 0, 0, 0, 26, 28, 3, 6, 3, 0, 27, 29, 3, 4, 2, 0, 28, 27, 1, 0, 0, 0, 28, 29, 1, 0, 0, 0, 29, 31, 1, 0, 0, 0, 30, 32, 3, 8, 4, 0, 31, 30, 1, 0, 0, 0, 31, 32, 1, 0, 0, 0, 32, 3, 1, 0, 0, 0, 33, 34, 5, 3, 0, 0, 34, 5, 1, 0, 0, 0, 35, 36, 5, 2, 0, 0, 36, 7, 1, 0, 0, 0, 37, 39, 3, 10, 5, 0, 38, 37, 1, 0, 0, 0, 38, 39, 1, 0, 0, 0, 39, 46, 1, 0, 0, 0, 40, 42, 5, 1, 0, 0, 41, 43, 3, 10, 5, 0, 42, 41, 1, 0, 0, 0, 42, 43, 1, 0, 0, 0, 43, 45, 1, 0, 0, 0, 44, 40, 1, 0, 0, 0, 45, 48, 1, 0, 0, 0, 46, 44, 1, 0, 0, 0, 46, 47, 1, 0, 0, 0, 47, 9, 1, 0, 0, 0, 48, 46, 1, 0, 0, 0, 49, 50, 5, 2, 0, 0, 50, 11, 1, 0, 0, 0, 8, 13, 17, 21, 28, 31, 38, 42, 46] \ No newline at end of file diff --git a/handlers/sshd_config/match-parser/parser/Match.tokens b/handlers/sshd_config/match-parser/parser/Match.tokens new file mode 100644 index 0000000..9172656 --- /dev/null +++ b/handlers/sshd_config/match-parser/parser/Match.tokens @@ -0,0 +1,4 @@ +COMMA=1 +STRING=2 +WHITESPACE=3 +','=1 diff --git a/handlers/sshd_config/match-parser/parser/MatchLexer.interp b/handlers/sshd_config/match-parser/parser/MatchLexer.interp new file mode 100644 index 0000000..90a8247 --- /dev/null +++ b/handlers/sshd_config/match-parser/parser/MatchLexer.interp @@ -0,0 +1,26 @@ +token literal names: +null +',' +null +null + +token symbolic names: +null +COMMA +STRING +WHITESPACE + +rule names: +COMMA +STRING +WHITESPACE + +channel names: +DEFAULT_TOKEN_CHANNEL +HIDDEN + +mode names: +DEFAULT_MODE + +atn: +[4, 0, 3, 19, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 1, 0, 1, 0, 1, 1, 4, 1, 11, 8, 1, 11, 1, 12, 1, 12, 1, 2, 4, 2, 16, 8, 2, 11, 2, 12, 2, 17, 0, 0, 3, 1, 1, 3, 2, 5, 3, 1, 0, 2, 5, 0, 9, 10, 13, 13, 32, 32, 35, 35, 44, 44, 2, 0, 9, 9, 32, 32, 20, 0, 1, 1, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, 5, 1, 0, 0, 0, 1, 7, 1, 0, 0, 0, 3, 10, 1, 0, 0, 0, 5, 15, 1, 0, 0, 0, 7, 8, 5, 44, 0, 0, 8, 2, 1, 0, 0, 0, 9, 11, 8, 0, 0, 0, 10, 9, 1, 0, 0, 0, 11, 12, 1, 0, 0, 0, 12, 10, 1, 0, 0, 0, 12, 13, 1, 0, 0, 0, 13, 4, 1, 0, 0, 0, 14, 16, 7, 1, 0, 0, 15, 14, 1, 0, 0, 0, 16, 17, 1, 0, 0, 0, 17, 15, 1, 0, 0, 0, 17, 18, 1, 0, 0, 0, 18, 6, 1, 0, 0, 0, 3, 0, 12, 17, 0] \ No newline at end of file diff --git a/handlers/sshd_config/match-parser/parser/MatchLexer.tokens b/handlers/sshd_config/match-parser/parser/MatchLexer.tokens new file mode 100644 index 0000000..9172656 --- /dev/null +++ b/handlers/sshd_config/match-parser/parser/MatchLexer.tokens @@ -0,0 +1,4 @@ +COMMA=1 +STRING=2 +WHITESPACE=3 +','=1 diff --git a/common/parsers/openssh-match-parser/parser/match_base_listener.go b/handlers/sshd_config/match-parser/parser/match_base_listener.go similarity index 100% rename from common/parsers/openssh-match-parser/parser/match_base_listener.go rename to handlers/sshd_config/match-parser/parser/match_base_listener.go diff --git a/common/parsers/openssh-match-parser/parser/match_lexer.go b/handlers/sshd_config/match-parser/parser/match_lexer.go similarity index 100% rename from common/parsers/openssh-match-parser/parser/match_lexer.go rename to handlers/sshd_config/match-parser/parser/match_lexer.go diff --git a/common/parsers/openssh-match-parser/parser/match_listener.go b/handlers/sshd_config/match-parser/parser/match_listener.go similarity index 100% rename from common/parsers/openssh-match-parser/parser/match_listener.go rename to handlers/sshd_config/match-parser/parser/match_listener.go diff --git a/common/parsers/openssh-match-parser/parser/match_parser.go b/handlers/sshd_config/match-parser/parser/match_parser.go similarity index 100% rename from common/parsers/openssh-match-parser/parser/match_parser.go rename to handlers/sshd_config/match-parser/parser/match_parser.go diff --git a/common/parsers/openssh-match-parser/parser_test.go b/handlers/sshd_config/match-parser/parser_test.go similarity index 100% rename from common/parsers/openssh-match-parser/parser_test.go rename to handlers/sshd_config/match-parser/parser_test.go diff --git a/handlers/sshd_config/parser/handlers/sshd_config/Config.interp b/handlers/sshd_config/parser/handlers/sshd_config/Config.interp new file mode 100644 index 0000000..e02ab96 --- /dev/null +++ b/handlers/sshd_config/parser/handlers/sshd_config/Config.interp @@ -0,0 +1,28 @@ +token literal names: +null +'#' +null +null +null +null + +token symbolic names: +null +HASH +WHITESPACE +STRING +NEWLINE +QUOTED_STRING + +rule names: +lineStatement +entry +separator +key +value +leadingComment +string + + +atn: +[4, 1, 5, 71, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 2, 5, 7, 5, 2, 6, 7, 6, 1, 0, 1, 0, 1, 0, 3, 0, 18, 8, 0, 3, 0, 20, 8, 0, 1, 0, 1, 0, 1, 1, 3, 1, 25, 8, 1, 1, 1, 3, 1, 28, 8, 1, 1, 1, 3, 1, 31, 8, 1, 1, 1, 3, 1, 34, 8, 1, 1, 1, 3, 1, 37, 8, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, 1, 4, 1, 4, 5, 4, 46, 8, 4, 10, 4, 12, 4, 49, 9, 4, 1, 4, 3, 4, 52, 8, 4, 1, 4, 3, 4, 55, 8, 4, 1, 5, 1, 5, 3, 5, 59, 8, 5, 1, 5, 1, 5, 3, 5, 63, 8, 5, 4, 5, 65, 8, 5, 11, 5, 12, 5, 66, 1, 6, 1, 6, 1, 6, 0, 0, 7, 0, 2, 4, 6, 8, 10, 12, 0, 1, 2, 0, 3, 3, 5, 5, 77, 0, 19, 1, 0, 0, 0, 2, 24, 1, 0, 0, 0, 4, 38, 1, 0, 0, 0, 6, 40, 1, 0, 0, 0, 8, 47, 1, 0, 0, 0, 10, 56, 1, 0, 0, 0, 12, 68, 1, 0, 0, 0, 14, 20, 3, 2, 1, 0, 15, 20, 3, 10, 5, 0, 16, 18, 5, 2, 0, 0, 17, 16, 1, 0, 0, 0, 17, 18, 1, 0, 0, 0, 18, 20, 1, 0, 0, 0, 19, 14, 1, 0, 0, 0, 19, 15, 1, 0, 0, 0, 19, 17, 1, 0, 0, 0, 20, 21, 1, 0, 0, 0, 21, 22, 5, 0, 0, 1, 22, 1, 1, 0, 0, 0, 23, 25, 5, 2, 0, 0, 24, 23, 1, 0, 0, 0, 24, 25, 1, 0, 0, 0, 25, 27, 1, 0, 0, 0, 26, 28, 3, 6, 3, 0, 27, 26, 1, 0, 0, 0, 27, 28, 1, 0, 0, 0, 28, 30, 1, 0, 0, 0, 29, 31, 3, 4, 2, 0, 30, 29, 1, 0, 0, 0, 30, 31, 1, 0, 0, 0, 31, 33, 1, 0, 0, 0, 32, 34, 3, 8, 4, 0, 33, 32, 1, 0, 0, 0, 33, 34, 1, 0, 0, 0, 34, 36, 1, 0, 0, 0, 35, 37, 3, 10, 5, 0, 36, 35, 1, 0, 0, 0, 36, 37, 1, 0, 0, 0, 37, 3, 1, 0, 0, 0, 38, 39, 5, 2, 0, 0, 39, 5, 1, 0, 0, 0, 40, 41, 3, 12, 6, 0, 41, 7, 1, 0, 0, 0, 42, 43, 3, 12, 6, 0, 43, 44, 5, 2, 0, 0, 44, 46, 1, 0, 0, 0, 45, 42, 1, 0, 0, 0, 46, 49, 1, 0, 0, 0, 47, 45, 1, 0, 0, 0, 47, 48, 1, 0, 0, 0, 48, 51, 1, 0, 0, 0, 49, 47, 1, 0, 0, 0, 50, 52, 3, 12, 6, 0, 51, 50, 1, 0, 0, 0, 51, 52, 1, 0, 0, 0, 52, 54, 1, 0, 0, 0, 53, 55, 5, 2, 0, 0, 54, 53, 1, 0, 0, 0, 54, 55, 1, 0, 0, 0, 55, 9, 1, 0, 0, 0, 56, 58, 5, 1, 0, 0, 57, 59, 5, 2, 0, 0, 58, 57, 1, 0, 0, 0, 58, 59, 1, 0, 0, 0, 59, 64, 1, 0, 0, 0, 60, 62, 3, 12, 6, 0, 61, 63, 5, 2, 0, 0, 62, 61, 1, 0, 0, 0, 62, 63, 1, 0, 0, 0, 63, 65, 1, 0, 0, 0, 64, 60, 1, 0, 0, 0, 65, 66, 1, 0, 0, 0, 66, 64, 1, 0, 0, 0, 66, 67, 1, 0, 0, 0, 67, 11, 1, 0, 0, 0, 68, 69, 7, 0, 0, 0, 69, 13, 1, 0, 0, 0, 13, 17, 19, 24, 27, 30, 33, 36, 47, 51, 54, 58, 62, 66] \ No newline at end of file diff --git a/handlers/sshd_config/parser/handlers/sshd_config/Config.tokens b/handlers/sshd_config/parser/handlers/sshd_config/Config.tokens new file mode 100644 index 0000000..fa8c415 --- /dev/null +++ b/handlers/sshd_config/parser/handlers/sshd_config/Config.tokens @@ -0,0 +1,6 @@ +HASH=1 +WHITESPACE=2 +STRING=3 +NEWLINE=4 +QUOTED_STRING=5 +'#'=1 diff --git a/handlers/sshd_config/parser/handlers/sshd_config/ConfigLexer.interp b/handlers/sshd_config/parser/handlers/sshd_config/ConfigLexer.interp new file mode 100644 index 0000000..c093cfb --- /dev/null +++ b/handlers/sshd_config/parser/handlers/sshd_config/ConfigLexer.interp @@ -0,0 +1,32 @@ +token literal names: +null +'#' +null +null +null +null + +token symbolic names: +null +HASH +WHITESPACE +STRING +NEWLINE +QUOTED_STRING + +rule names: +HASH +WHITESPACE +STRING +NEWLINE +QUOTED_STRING + +channel names: +DEFAULT_TOKEN_CHANNEL +HIDDEN + +mode names: +DEFAULT_MODE + +atn: +[4, 0, 5, 46, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 1, 0, 1, 0, 1, 1, 4, 1, 15, 8, 1, 11, 1, 12, 1, 16, 1, 2, 4, 2, 20, 8, 2, 11, 2, 12, 2, 21, 1, 3, 3, 3, 25, 8, 3, 1, 3, 1, 3, 1, 4, 1, 4, 3, 4, 31, 8, 4, 1, 4, 1, 4, 1, 4, 5, 4, 36, 8, 4, 10, 4, 12, 4, 39, 9, 4, 1, 4, 3, 4, 42, 8, 4, 1, 4, 3, 4, 45, 8, 4, 0, 0, 5, 1, 1, 3, 2, 5, 3, 7, 4, 9, 5, 1, 0, 2, 2, 0, 9, 9, 32, 32, 4, 0, 9, 10, 13, 13, 32, 32, 34, 35, 52, 0, 1, 1, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, 5, 1, 0, 0, 0, 0, 7, 1, 0, 0, 0, 0, 9, 1, 0, 0, 0, 1, 11, 1, 0, 0, 0, 3, 14, 1, 0, 0, 0, 5, 19, 1, 0, 0, 0, 7, 24, 1, 0, 0, 0, 9, 28, 1, 0, 0, 0, 11, 12, 5, 35, 0, 0, 12, 2, 1, 0, 0, 0, 13, 15, 7, 0, 0, 0, 14, 13, 1, 0, 0, 0, 15, 16, 1, 0, 0, 0, 16, 14, 1, 0, 0, 0, 16, 17, 1, 0, 0, 0, 17, 4, 1, 0, 0, 0, 18, 20, 8, 1, 0, 0, 19, 18, 1, 0, 0, 0, 20, 21, 1, 0, 0, 0, 21, 19, 1, 0, 0, 0, 21, 22, 1, 0, 0, 0, 22, 6, 1, 0, 0, 0, 23, 25, 5, 13, 0, 0, 24, 23, 1, 0, 0, 0, 24, 25, 1, 0, 0, 0, 25, 26, 1, 0, 0, 0, 26, 27, 5, 10, 0, 0, 27, 8, 1, 0, 0, 0, 28, 30, 5, 34, 0, 0, 29, 31, 3, 3, 1, 0, 30, 29, 1, 0, 0, 0, 30, 31, 1, 0, 0, 0, 31, 37, 1, 0, 0, 0, 32, 33, 3, 5, 2, 0, 33, 34, 3, 3, 1, 0, 34, 36, 1, 0, 0, 0, 35, 32, 1, 0, 0, 0, 36, 39, 1, 0, 0, 0, 37, 35, 1, 0, 0, 0, 37, 38, 1, 0, 0, 0, 38, 41, 1, 0, 0, 0, 39, 37, 1, 0, 0, 0, 40, 42, 3, 5, 2, 0, 41, 40, 1, 0, 0, 0, 41, 42, 1, 0, 0, 0, 42, 44, 1, 0, 0, 0, 43, 45, 5, 34, 0, 0, 44, 43, 1, 0, 0, 0, 44, 45, 1, 0, 0, 0, 45, 10, 1, 0, 0, 0, 8, 0, 16, 21, 24, 30, 37, 41, 44, 0] \ No newline at end of file diff --git a/handlers/sshd_config/parser/handlers/sshd_config/ConfigLexer.tokens b/handlers/sshd_config/parser/handlers/sshd_config/ConfigLexer.tokens new file mode 100644 index 0000000..fa8c415 --- /dev/null +++ b/handlers/sshd_config/parser/handlers/sshd_config/ConfigLexer.tokens @@ -0,0 +1,6 @@ +HASH=1 +WHITESPACE=2 +STRING=3 +NEWLINE=4 +QUOTED_STRING=5 +'#'=1 diff --git a/handlers/sshd_config/parser/handlers/sshd_config/config_base_listener.go b/handlers/sshd_config/parser/handlers/sshd_config/config_base_listener.go new file mode 100644 index 0000000..00727a5 --- /dev/null +++ b/handlers/sshd_config/parser/handlers/sshd_config/config_base_listener.go @@ -0,0 +1,64 @@ +// Code generated from handlers/sshd_config/Config.g4 by ANTLR 4.13.0. DO NOT EDIT. + +package parser // Config + +import "github.com/antlr4-go/antlr/v4" + +// BaseConfigListener is a complete listener for a parse tree produced by ConfigParser. +type BaseConfigListener struct{} + +var _ ConfigListener = &BaseConfigListener{} + +// VisitTerminal is called when a terminal node is visited. +func (s *BaseConfigListener) VisitTerminal(node antlr.TerminalNode) {} + +// VisitErrorNode is called when an error node is visited. +func (s *BaseConfigListener) VisitErrorNode(node antlr.ErrorNode) {} + +// EnterEveryRule is called when any rule is entered. +func (s *BaseConfigListener) EnterEveryRule(ctx antlr.ParserRuleContext) {} + +// ExitEveryRule is called when any rule is exited. +func (s *BaseConfigListener) ExitEveryRule(ctx antlr.ParserRuleContext) {} + +// EnterLineStatement is called when production lineStatement is entered. +func (s *BaseConfigListener) EnterLineStatement(ctx *LineStatementContext) {} + +// ExitLineStatement is called when production lineStatement is exited. +func (s *BaseConfigListener) ExitLineStatement(ctx *LineStatementContext) {} + +// EnterEntry is called when production entry is entered. +func (s *BaseConfigListener) EnterEntry(ctx *EntryContext) {} + +// ExitEntry is called when production entry is exited. +func (s *BaseConfigListener) ExitEntry(ctx *EntryContext) {} + +// EnterSeparator is called when production separator is entered. +func (s *BaseConfigListener) EnterSeparator(ctx *SeparatorContext) {} + +// ExitSeparator is called when production separator is exited. +func (s *BaseConfigListener) ExitSeparator(ctx *SeparatorContext) {} + +// EnterKey is called when production key is entered. +func (s *BaseConfigListener) EnterKey(ctx *KeyContext) {} + +// ExitKey is called when production key is exited. +func (s *BaseConfigListener) ExitKey(ctx *KeyContext) {} + +// EnterValue is called when production value is entered. +func (s *BaseConfigListener) EnterValue(ctx *ValueContext) {} + +// ExitValue is called when production value is exited. +func (s *BaseConfigListener) ExitValue(ctx *ValueContext) {} + +// EnterLeadingComment is called when production leadingComment is entered. +func (s *BaseConfigListener) EnterLeadingComment(ctx *LeadingCommentContext) {} + +// ExitLeadingComment is called when production leadingComment is exited. +func (s *BaseConfigListener) ExitLeadingComment(ctx *LeadingCommentContext) {} + +// EnterString is called when production string is entered. +func (s *BaseConfigListener) EnterString(ctx *StringContext) {} + +// ExitString is called when production string is exited. +func (s *BaseConfigListener) ExitString(ctx *StringContext) {} diff --git a/handlers/sshd_config/parser/handlers/sshd_config/config_lexer.go b/handlers/sshd_config/parser/handlers/sshd_config/config_lexer.go new file mode 100644 index 0000000..2852942 --- /dev/null +++ b/handlers/sshd_config/parser/handlers/sshd_config/config_lexer.go @@ -0,0 +1,122 @@ +// Code generated from handlers/sshd_config/Config.g4 by ANTLR 4.13.0. DO NOT EDIT. + +package parser + +import ( + "fmt" + "github.com/antlr4-go/antlr/v4" + "sync" + "unicode" +) + +// Suppress unused import error +var _ = fmt.Printf +var _ = sync.Once{} +var _ = unicode.IsLetter + +type ConfigLexer struct { + *antlr.BaseLexer + channelNames []string + modeNames []string + // TODO: EOF string +} + +var ConfigLexerLexerStaticData struct { + once sync.Once + serializedATN []int32 + ChannelNames []string + ModeNames []string + LiteralNames []string + SymbolicNames []string + RuleNames []string + PredictionContextCache *antlr.PredictionContextCache + atn *antlr.ATN + decisionToDFA []*antlr.DFA +} + +func configlexerLexerInit() { + staticData := &ConfigLexerLexerStaticData + staticData.ChannelNames = []string{ + "DEFAULT_TOKEN_CHANNEL", "HIDDEN", + } + staticData.ModeNames = []string{ + "DEFAULT_MODE", + } + staticData.LiteralNames = []string{ + "", "'#'", + } + staticData.SymbolicNames = []string{ + "", "HASH", "WHITESPACE", "STRING", "NEWLINE", "QUOTED_STRING", + } + staticData.RuleNames = []string{ + "HASH", "WHITESPACE", "STRING", "NEWLINE", "QUOTED_STRING", + } + staticData.PredictionContextCache = antlr.NewPredictionContextCache() + staticData.serializedATN = []int32{ + 4, 0, 5, 46, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, + 4, 7, 4, 1, 0, 1, 0, 1, 1, 4, 1, 15, 8, 1, 11, 1, 12, 1, 16, 1, 2, 4, 2, + 20, 8, 2, 11, 2, 12, 2, 21, 1, 3, 3, 3, 25, 8, 3, 1, 3, 1, 3, 1, 4, 1, + 4, 3, 4, 31, 8, 4, 1, 4, 1, 4, 1, 4, 5, 4, 36, 8, 4, 10, 4, 12, 4, 39, + 9, 4, 1, 4, 3, 4, 42, 8, 4, 1, 4, 3, 4, 45, 8, 4, 0, 0, 5, 1, 1, 3, 2, + 5, 3, 7, 4, 9, 5, 1, 0, 2, 2, 0, 9, 9, 32, 32, 4, 0, 9, 10, 13, 13, 32, + 32, 34, 35, 52, 0, 1, 1, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, 5, 1, 0, 0, 0, 0, + 7, 1, 0, 0, 0, 0, 9, 1, 0, 0, 0, 1, 11, 1, 0, 0, 0, 3, 14, 1, 0, 0, 0, + 5, 19, 1, 0, 0, 0, 7, 24, 1, 0, 0, 0, 9, 28, 1, 0, 0, 0, 11, 12, 5, 35, + 0, 0, 12, 2, 1, 0, 0, 0, 13, 15, 7, 0, 0, 0, 14, 13, 1, 0, 0, 0, 15, 16, + 1, 0, 0, 0, 16, 14, 1, 0, 0, 0, 16, 17, 1, 0, 0, 0, 17, 4, 1, 0, 0, 0, + 18, 20, 8, 1, 0, 0, 19, 18, 1, 0, 0, 0, 20, 21, 1, 0, 0, 0, 21, 19, 1, + 0, 0, 0, 21, 22, 1, 0, 0, 0, 22, 6, 1, 0, 0, 0, 23, 25, 5, 13, 0, 0, 24, + 23, 1, 0, 0, 0, 24, 25, 1, 0, 0, 0, 25, 26, 1, 0, 0, 0, 26, 27, 5, 10, + 0, 0, 27, 8, 1, 0, 0, 0, 28, 30, 5, 34, 0, 0, 29, 31, 3, 3, 1, 0, 30, 29, + 1, 0, 0, 0, 30, 31, 1, 0, 0, 0, 31, 37, 1, 0, 0, 0, 32, 33, 3, 5, 2, 0, + 33, 34, 3, 3, 1, 0, 34, 36, 1, 0, 0, 0, 35, 32, 1, 0, 0, 0, 36, 39, 1, + 0, 0, 0, 37, 35, 1, 0, 0, 0, 37, 38, 1, 0, 0, 0, 38, 41, 1, 0, 0, 0, 39, + 37, 1, 0, 0, 0, 40, 42, 3, 5, 2, 0, 41, 40, 1, 0, 0, 0, 41, 42, 1, 0, 0, + 0, 42, 44, 1, 0, 0, 0, 43, 45, 5, 34, 0, 0, 44, 43, 1, 0, 0, 0, 44, 45, + 1, 0, 0, 0, 45, 10, 1, 0, 0, 0, 8, 0, 16, 21, 24, 30, 37, 41, 44, 0, + } + deserializer := antlr.NewATNDeserializer(nil) + staticData.atn = deserializer.Deserialize(staticData.serializedATN) + atn := staticData.atn + staticData.decisionToDFA = make([]*antlr.DFA, len(atn.DecisionToState)) + decisionToDFA := staticData.decisionToDFA + for index, state := range atn.DecisionToState { + decisionToDFA[index] = antlr.NewDFA(state, index) + } +} + +// ConfigLexerInit initializes any static state used to implement ConfigLexer. By default the +// static state used to implement the lexer is lazily initialized during the first call to +// NewConfigLexer(). You can call this function if you wish to initialize the static state ahead +// of time. +func ConfigLexerInit() { + staticData := &ConfigLexerLexerStaticData + staticData.once.Do(configlexerLexerInit) +} + +// NewConfigLexer produces a new lexer instance for the optional input antlr.CharStream. +func NewConfigLexer(input antlr.CharStream) *ConfigLexer { + ConfigLexerInit() + l := new(ConfigLexer) + l.BaseLexer = antlr.NewBaseLexer(input) + staticData := &ConfigLexerLexerStaticData + l.Interpreter = antlr.NewLexerATNSimulator(l, staticData.atn, staticData.decisionToDFA, staticData.PredictionContextCache) + l.channelNames = staticData.ChannelNames + l.modeNames = staticData.ModeNames + l.RuleNames = staticData.RuleNames + l.LiteralNames = staticData.LiteralNames + l.SymbolicNames = staticData.SymbolicNames + l.GrammarFileName = "Config.g4" + // TODO: l.EOF = antlr.TokenEOF + + return l +} + +// ConfigLexer tokens. +const ( + ConfigLexerHASH = 1 + ConfigLexerWHITESPACE = 2 + ConfigLexerSTRING = 3 + ConfigLexerNEWLINE = 4 + ConfigLexerQUOTED_STRING = 5 +) diff --git a/handlers/sshd_config/parser/handlers/sshd_config/config_listener.go b/handlers/sshd_config/parser/handlers/sshd_config/config_listener.go new file mode 100644 index 0000000..b6e827b --- /dev/null +++ b/handlers/sshd_config/parser/handlers/sshd_config/config_listener.go @@ -0,0 +1,52 @@ +// Code generated from handlers/sshd_config/Config.g4 by ANTLR 4.13.0. DO NOT EDIT. + +package parser // Config + +import "github.com/antlr4-go/antlr/v4" + +// ConfigListener is a complete listener for a parse tree produced by ConfigParser. +type ConfigListener interface { + antlr.ParseTreeListener + + // EnterLineStatement is called when entering the lineStatement production. + EnterLineStatement(c *LineStatementContext) + + // EnterEntry is called when entering the entry production. + EnterEntry(c *EntryContext) + + // EnterSeparator is called when entering the separator production. + EnterSeparator(c *SeparatorContext) + + // EnterKey is called when entering the key production. + EnterKey(c *KeyContext) + + // EnterValue is called when entering the value production. + EnterValue(c *ValueContext) + + // EnterLeadingComment is called when entering the leadingComment production. + EnterLeadingComment(c *LeadingCommentContext) + + // EnterString is called when entering the string production. + EnterString(c *StringContext) + + // ExitLineStatement is called when exiting the lineStatement production. + ExitLineStatement(c *LineStatementContext) + + // ExitEntry is called when exiting the entry production. + ExitEntry(c *EntryContext) + + // ExitSeparator is called when exiting the separator production. + ExitSeparator(c *SeparatorContext) + + // ExitKey is called when exiting the key production. + ExitKey(c *KeyContext) + + // ExitValue is called when exiting the value production. + ExitValue(c *ValueContext) + + // ExitLeadingComment is called when exiting the leadingComment production. + ExitLeadingComment(c *LeadingCommentContext) + + // ExitString is called when exiting the string production. + ExitString(c *StringContext) +} diff --git a/handlers/sshd_config/parser/handlers/sshd_config/config_parser.go b/handlers/sshd_config/parser/handlers/sshd_config/config_parser.go new file mode 100644 index 0000000..50f9bab --- /dev/null +++ b/handlers/sshd_config/parser/handlers/sshd_config/config_parser.go @@ -0,0 +1,1254 @@ +// Code generated from handlers/sshd_config/Config.g4 by ANTLR 4.13.0. DO NOT EDIT. + +package parser // Config + +import ( + "fmt" + "strconv" + "sync" + + "github.com/antlr4-go/antlr/v4" +) + +// Suppress unused import errors +var _ = fmt.Printf +var _ = strconv.Itoa +var _ = sync.Once{} + +type ConfigParser struct { + *antlr.BaseParser +} + +var ConfigParserStaticData struct { + once sync.Once + serializedATN []int32 + LiteralNames []string + SymbolicNames []string + RuleNames []string + PredictionContextCache *antlr.PredictionContextCache + atn *antlr.ATN + decisionToDFA []*antlr.DFA +} + +func configParserInit() { + staticData := &ConfigParserStaticData + staticData.LiteralNames = []string{ + "", "'#'", + } + staticData.SymbolicNames = []string{ + "", "HASH", "WHITESPACE", "STRING", "NEWLINE", "QUOTED_STRING", + } + staticData.RuleNames = []string{ + "lineStatement", "entry", "separator", "key", "value", "leadingComment", + "string", + } + staticData.PredictionContextCache = antlr.NewPredictionContextCache() + staticData.serializedATN = []int32{ + 4, 1, 5, 71, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, + 2, 5, 7, 5, 2, 6, 7, 6, 1, 0, 1, 0, 1, 0, 3, 0, 18, 8, 0, 3, 0, 20, 8, + 0, 1, 0, 1, 0, 1, 1, 3, 1, 25, 8, 1, 1, 1, 3, 1, 28, 8, 1, 1, 1, 3, 1, + 31, 8, 1, 1, 1, 3, 1, 34, 8, 1, 1, 1, 3, 1, 37, 8, 1, 1, 2, 1, 2, 1, 3, + 1, 3, 1, 4, 1, 4, 1, 4, 5, 4, 46, 8, 4, 10, 4, 12, 4, 49, 9, 4, 1, 4, 3, + 4, 52, 8, 4, 1, 4, 3, 4, 55, 8, 4, 1, 5, 1, 5, 3, 5, 59, 8, 5, 1, 5, 1, + 5, 3, 5, 63, 8, 5, 4, 5, 65, 8, 5, 11, 5, 12, 5, 66, 1, 6, 1, 6, 1, 6, + 0, 0, 7, 0, 2, 4, 6, 8, 10, 12, 0, 1, 2, 0, 3, 3, 5, 5, 77, 0, 19, 1, 0, + 0, 0, 2, 24, 1, 0, 0, 0, 4, 38, 1, 0, 0, 0, 6, 40, 1, 0, 0, 0, 8, 47, 1, + 0, 0, 0, 10, 56, 1, 0, 0, 0, 12, 68, 1, 0, 0, 0, 14, 20, 3, 2, 1, 0, 15, + 20, 3, 10, 5, 0, 16, 18, 5, 2, 0, 0, 17, 16, 1, 0, 0, 0, 17, 18, 1, 0, + 0, 0, 18, 20, 1, 0, 0, 0, 19, 14, 1, 0, 0, 0, 19, 15, 1, 0, 0, 0, 19, 17, + 1, 0, 0, 0, 20, 21, 1, 0, 0, 0, 21, 22, 5, 0, 0, 1, 22, 1, 1, 0, 0, 0, + 23, 25, 5, 2, 0, 0, 24, 23, 1, 0, 0, 0, 24, 25, 1, 0, 0, 0, 25, 27, 1, + 0, 0, 0, 26, 28, 3, 6, 3, 0, 27, 26, 1, 0, 0, 0, 27, 28, 1, 0, 0, 0, 28, + 30, 1, 0, 0, 0, 29, 31, 3, 4, 2, 0, 30, 29, 1, 0, 0, 0, 30, 31, 1, 0, 0, + 0, 31, 33, 1, 0, 0, 0, 32, 34, 3, 8, 4, 0, 33, 32, 1, 0, 0, 0, 33, 34, + 1, 0, 0, 0, 34, 36, 1, 0, 0, 0, 35, 37, 3, 10, 5, 0, 36, 35, 1, 0, 0, 0, + 36, 37, 1, 0, 0, 0, 37, 3, 1, 0, 0, 0, 38, 39, 5, 2, 0, 0, 39, 5, 1, 0, + 0, 0, 40, 41, 3, 12, 6, 0, 41, 7, 1, 0, 0, 0, 42, 43, 3, 12, 6, 0, 43, + 44, 5, 2, 0, 0, 44, 46, 1, 0, 0, 0, 45, 42, 1, 0, 0, 0, 46, 49, 1, 0, 0, + 0, 47, 45, 1, 0, 0, 0, 47, 48, 1, 0, 0, 0, 48, 51, 1, 0, 0, 0, 49, 47, + 1, 0, 0, 0, 50, 52, 3, 12, 6, 0, 51, 50, 1, 0, 0, 0, 51, 52, 1, 0, 0, 0, + 52, 54, 1, 0, 0, 0, 53, 55, 5, 2, 0, 0, 54, 53, 1, 0, 0, 0, 54, 55, 1, + 0, 0, 0, 55, 9, 1, 0, 0, 0, 56, 58, 5, 1, 0, 0, 57, 59, 5, 2, 0, 0, 58, + 57, 1, 0, 0, 0, 58, 59, 1, 0, 0, 0, 59, 64, 1, 0, 0, 0, 60, 62, 3, 12, + 6, 0, 61, 63, 5, 2, 0, 0, 62, 61, 1, 0, 0, 0, 62, 63, 1, 0, 0, 0, 63, 65, + 1, 0, 0, 0, 64, 60, 1, 0, 0, 0, 65, 66, 1, 0, 0, 0, 66, 64, 1, 0, 0, 0, + 66, 67, 1, 0, 0, 0, 67, 11, 1, 0, 0, 0, 68, 69, 7, 0, 0, 0, 69, 13, 1, + 0, 0, 0, 13, 17, 19, 24, 27, 30, 33, 36, 47, 51, 54, 58, 62, 66, + } + deserializer := antlr.NewATNDeserializer(nil) + staticData.atn = deserializer.Deserialize(staticData.serializedATN) + atn := staticData.atn + staticData.decisionToDFA = make([]*antlr.DFA, len(atn.DecisionToState)) + decisionToDFA := staticData.decisionToDFA + for index, state := range atn.DecisionToState { + decisionToDFA[index] = antlr.NewDFA(state, index) + } +} + +// ConfigParserInit initializes any static state used to implement ConfigParser. By default the +// static state used to implement the parser is lazily initialized during the first call to +// NewConfigParser(). You can call this function if you wish to initialize the static state ahead +// of time. +func ConfigParserInit() { + staticData := &ConfigParserStaticData + staticData.once.Do(configParserInit) +} + +// NewConfigParser produces a new parser instance for the optional input antlr.TokenStream. +func NewConfigParser(input antlr.TokenStream) *ConfigParser { + ConfigParserInit() + this := new(ConfigParser) + this.BaseParser = antlr.NewBaseParser(input) + staticData := &ConfigParserStaticData + this.Interpreter = antlr.NewParserATNSimulator(this, staticData.atn, staticData.decisionToDFA, staticData.PredictionContextCache) + this.RuleNames = staticData.RuleNames + this.LiteralNames = staticData.LiteralNames + this.SymbolicNames = staticData.SymbolicNames + this.GrammarFileName = "Config.g4" + + return this +} + +// ConfigParser tokens. +const ( + ConfigParserEOF = antlr.TokenEOF + ConfigParserHASH = 1 + ConfigParserWHITESPACE = 2 + ConfigParserSTRING = 3 + ConfigParserNEWLINE = 4 + ConfigParserQUOTED_STRING = 5 +) + +// ConfigParser rules. +const ( + ConfigParserRULE_lineStatement = 0 + ConfigParserRULE_entry = 1 + ConfigParserRULE_separator = 2 + ConfigParserRULE_key = 3 + ConfigParserRULE_value = 4 + ConfigParserRULE_leadingComment = 5 + ConfigParserRULE_string = 6 +) + +// ILineStatementContext is an interface to support dynamic dispatch. +type ILineStatementContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + + // Getter signatures + EOF() antlr.TerminalNode + Entry() IEntryContext + LeadingComment() ILeadingCommentContext + WHITESPACE() antlr.TerminalNode + + // IsLineStatementContext differentiates from other interfaces. + IsLineStatementContext() +} + +type LineStatementContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptyLineStatementContext() *LineStatementContext { + var p = new(LineStatementContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_lineStatement + return p +} + +func InitEmptyLineStatementContext(p *LineStatementContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_lineStatement +} + +func (*LineStatementContext) IsLineStatementContext() {} + +func NewLineStatementContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *LineStatementContext { + var p = new(LineStatementContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = ConfigParserRULE_lineStatement + + return p +} + +func (s *LineStatementContext) GetParser() antlr.Parser { return s.parser } + +func (s *LineStatementContext) EOF() antlr.TerminalNode { + return s.GetToken(ConfigParserEOF, 0) +} + +func (s *LineStatementContext) Entry() IEntryContext { + var t antlr.RuleContext + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(IEntryContext); ok { + t = ctx.(antlr.RuleContext) + break + } + } + + if t == nil { + return nil + } + + return t.(IEntryContext) +} + +func (s *LineStatementContext) LeadingComment() ILeadingCommentContext { + var t antlr.RuleContext + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(ILeadingCommentContext); ok { + t = ctx.(antlr.RuleContext) + break + } + } + + if t == nil { + return nil + } + + return t.(ILeadingCommentContext) +} + +func (s *LineStatementContext) WHITESPACE() antlr.TerminalNode { + return s.GetToken(ConfigParserWHITESPACE, 0) +} + +func (s *LineStatementContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *LineStatementContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +func (s *LineStatementContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.EnterLineStatement(s) + } +} + +func (s *LineStatementContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.ExitLineStatement(s) + } +} + +func (p *ConfigParser) LineStatement() (localctx ILineStatementContext) { + localctx = NewLineStatementContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 0, ConfigParserRULE_lineStatement) + var _la int + + p.EnterOuterAlt(localctx, 1) + p.SetState(19) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + + switch p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 1, p.GetParserRuleContext()) { + case 1: + { + p.SetState(14) + p.Entry() + } + + case 2: + { + p.SetState(15) + p.LeadingComment() + } + + case 3: + p.SetState(17) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + if _la == ConfigParserWHITESPACE { + { + p.SetState(16) + p.Match(ConfigParserWHITESPACE) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + + } + + case antlr.ATNInvalidAltNumber: + goto errorExit + } + { + p.SetState(21) + p.Match(ConfigParserEOF) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} + +// IEntryContext is an interface to support dynamic dispatch. +type IEntryContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + + // Getter signatures + WHITESPACE() antlr.TerminalNode + Key() IKeyContext + Separator() ISeparatorContext + Value() IValueContext + LeadingComment() ILeadingCommentContext + + // IsEntryContext differentiates from other interfaces. + IsEntryContext() +} + +type EntryContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptyEntryContext() *EntryContext { + var p = new(EntryContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_entry + return p +} + +func InitEmptyEntryContext(p *EntryContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_entry +} + +func (*EntryContext) IsEntryContext() {} + +func NewEntryContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *EntryContext { + var p = new(EntryContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = ConfigParserRULE_entry + + return p +} + +func (s *EntryContext) GetParser() antlr.Parser { return s.parser } + +func (s *EntryContext) WHITESPACE() antlr.TerminalNode { + return s.GetToken(ConfigParserWHITESPACE, 0) +} + +func (s *EntryContext) Key() IKeyContext { + var t antlr.RuleContext + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(IKeyContext); ok { + t = ctx.(antlr.RuleContext) + break + } + } + + if t == nil { + return nil + } + + return t.(IKeyContext) +} + +func (s *EntryContext) Separator() ISeparatorContext { + var t antlr.RuleContext + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(ISeparatorContext); ok { + t = ctx.(antlr.RuleContext) + break + } + } + + if t == nil { + return nil + } + + return t.(ISeparatorContext) +} + +func (s *EntryContext) Value() IValueContext { + var t antlr.RuleContext + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(IValueContext); ok { + t = ctx.(antlr.RuleContext) + break + } + } + + if t == nil { + return nil + } + + return t.(IValueContext) +} + +func (s *EntryContext) LeadingComment() ILeadingCommentContext { + var t antlr.RuleContext + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(ILeadingCommentContext); ok { + t = ctx.(antlr.RuleContext) + break + } + } + + if t == nil { + return nil + } + + return t.(ILeadingCommentContext) +} + +func (s *EntryContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *EntryContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +func (s *EntryContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.EnterEntry(s) + } +} + +func (s *EntryContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.ExitEntry(s) + } +} + +func (p *ConfigParser) Entry() (localctx IEntryContext) { + localctx = NewEntryContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 2, ConfigParserRULE_entry) + var _la int + + p.EnterOuterAlt(localctx, 1) + p.SetState(24) + p.GetErrorHandler().Sync(p) + + if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 2, p.GetParserRuleContext()) == 1 { + { + p.SetState(23) + p.Match(ConfigParserWHITESPACE) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + + } else if p.HasError() { // JIM + goto errorExit + } + p.SetState(27) + p.GetErrorHandler().Sync(p) + + if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 3, p.GetParserRuleContext()) == 1 { + { + p.SetState(26) + p.Key() + } + + } else if p.HasError() { // JIM + goto errorExit + } + p.SetState(30) + p.GetErrorHandler().Sync(p) + + if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 4, p.GetParserRuleContext()) == 1 { + { + p.SetState(29) + p.Separator() + } + + } else if p.HasError() { // JIM + goto errorExit + } + p.SetState(33) + p.GetErrorHandler().Sync(p) + + if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 5, p.GetParserRuleContext()) == 1 { + { + p.SetState(32) + p.Value() + } + + } else if p.HasError() { // JIM + goto errorExit + } + p.SetState(36) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + if _la == ConfigParserHASH { + { + p.SetState(35) + p.LeadingComment() + } + + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} + +// ISeparatorContext is an interface to support dynamic dispatch. +type ISeparatorContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + + // Getter signatures + WHITESPACE() antlr.TerminalNode + + // IsSeparatorContext differentiates from other interfaces. + IsSeparatorContext() +} + +type SeparatorContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptySeparatorContext() *SeparatorContext { + var p = new(SeparatorContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_separator + return p +} + +func InitEmptySeparatorContext(p *SeparatorContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_separator +} + +func (*SeparatorContext) IsSeparatorContext() {} + +func NewSeparatorContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *SeparatorContext { + var p = new(SeparatorContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = ConfigParserRULE_separator + + return p +} + +func (s *SeparatorContext) GetParser() antlr.Parser { return s.parser } + +func (s *SeparatorContext) WHITESPACE() antlr.TerminalNode { + return s.GetToken(ConfigParserWHITESPACE, 0) +} + +func (s *SeparatorContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *SeparatorContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +func (s *SeparatorContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.EnterSeparator(s) + } +} + +func (s *SeparatorContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.ExitSeparator(s) + } +} + +func (p *ConfigParser) Separator() (localctx ISeparatorContext) { + localctx = NewSeparatorContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 4, ConfigParserRULE_separator) + p.EnterOuterAlt(localctx, 1) + { + p.SetState(38) + p.Match(ConfigParserWHITESPACE) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} + +// IKeyContext is an interface to support dynamic dispatch. +type IKeyContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + + // Getter signatures + String_() IStringContext + + // IsKeyContext differentiates from other interfaces. + IsKeyContext() +} + +type KeyContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptyKeyContext() *KeyContext { + var p = new(KeyContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_key + return p +} + +func InitEmptyKeyContext(p *KeyContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_key +} + +func (*KeyContext) IsKeyContext() {} + +func NewKeyContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *KeyContext { + var p = new(KeyContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = ConfigParserRULE_key + + return p +} + +func (s *KeyContext) GetParser() antlr.Parser { return s.parser } + +func (s *KeyContext) String_() IStringContext { + var t antlr.RuleContext + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(IStringContext); ok { + t = ctx.(antlr.RuleContext) + break + } + } + + if t == nil { + return nil + } + + return t.(IStringContext) +} + +func (s *KeyContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *KeyContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +func (s *KeyContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.EnterKey(s) + } +} + +func (s *KeyContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.ExitKey(s) + } +} + +func (p *ConfigParser) Key() (localctx IKeyContext) { + localctx = NewKeyContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 6, ConfigParserRULE_key) + p.EnterOuterAlt(localctx, 1) + { + p.SetState(40) + p.String_() + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} + +// IValueContext is an interface to support dynamic dispatch. +type IValueContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + + // Getter signatures + AllString_() []IStringContext + String_(i int) IStringContext + AllWHITESPACE() []antlr.TerminalNode + WHITESPACE(i int) antlr.TerminalNode + + // IsValueContext differentiates from other interfaces. + IsValueContext() +} + +type ValueContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptyValueContext() *ValueContext { + var p = new(ValueContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_value + return p +} + +func InitEmptyValueContext(p *ValueContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_value +} + +func (*ValueContext) IsValueContext() {} + +func NewValueContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *ValueContext { + var p = new(ValueContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = ConfigParserRULE_value + + return p +} + +func (s *ValueContext) GetParser() antlr.Parser { return s.parser } + +func (s *ValueContext) AllString_() []IStringContext { + children := s.GetChildren() + len := 0 + for _, ctx := range children { + if _, ok := ctx.(IStringContext); ok { + len++ + } + } + + tst := make([]IStringContext, len) + i := 0 + for _, ctx := range children { + if t, ok := ctx.(IStringContext); ok { + tst[i] = t.(IStringContext) + i++ + } + } + + return tst +} + +func (s *ValueContext) String_(i int) IStringContext { + var t antlr.RuleContext + j := 0 + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(IStringContext); ok { + if j == i { + t = ctx.(antlr.RuleContext) + break + } + j++ + } + } + + if t == nil { + return nil + } + + return t.(IStringContext) +} + +func (s *ValueContext) AllWHITESPACE() []antlr.TerminalNode { + return s.GetTokens(ConfigParserWHITESPACE) +} + +func (s *ValueContext) WHITESPACE(i int) antlr.TerminalNode { + return s.GetToken(ConfigParserWHITESPACE, i) +} + +func (s *ValueContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *ValueContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +func (s *ValueContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.EnterValue(s) + } +} + +func (s *ValueContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.ExitValue(s) + } +} + +func (p *ConfigParser) Value() (localctx IValueContext) { + localctx = NewValueContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 8, ConfigParserRULE_value) + var _la int + + var _alt int + + p.EnterOuterAlt(localctx, 1) + p.SetState(47) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _alt = p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 7, p.GetParserRuleContext()) + if p.HasError() { + goto errorExit + } + for _alt != 2 && _alt != antlr.ATNInvalidAltNumber { + if _alt == 1 { + { + p.SetState(42) + p.String_() + } + { + p.SetState(43) + p.Match(ConfigParserWHITESPACE) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + + } + p.SetState(49) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _alt = p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 7, p.GetParserRuleContext()) + if p.HasError() { + goto errorExit + } + } + p.SetState(51) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + if _la == ConfigParserSTRING || _la == ConfigParserQUOTED_STRING { + { + p.SetState(50) + p.String_() + } + + } + p.SetState(54) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + if _la == ConfigParserWHITESPACE { + { + p.SetState(53) + p.Match(ConfigParserWHITESPACE) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} + +// ILeadingCommentContext is an interface to support dynamic dispatch. +type ILeadingCommentContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + + // Getter signatures + HASH() antlr.TerminalNode + AllWHITESPACE() []antlr.TerminalNode + WHITESPACE(i int) antlr.TerminalNode + AllString_() []IStringContext + String_(i int) IStringContext + + // IsLeadingCommentContext differentiates from other interfaces. + IsLeadingCommentContext() +} + +type LeadingCommentContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptyLeadingCommentContext() *LeadingCommentContext { + var p = new(LeadingCommentContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_leadingComment + return p +} + +func InitEmptyLeadingCommentContext(p *LeadingCommentContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_leadingComment +} + +func (*LeadingCommentContext) IsLeadingCommentContext() {} + +func NewLeadingCommentContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *LeadingCommentContext { + var p = new(LeadingCommentContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = ConfigParserRULE_leadingComment + + return p +} + +func (s *LeadingCommentContext) GetParser() antlr.Parser { return s.parser } + +func (s *LeadingCommentContext) HASH() antlr.TerminalNode { + return s.GetToken(ConfigParserHASH, 0) +} + +func (s *LeadingCommentContext) AllWHITESPACE() []antlr.TerminalNode { + return s.GetTokens(ConfigParserWHITESPACE) +} + +func (s *LeadingCommentContext) WHITESPACE(i int) antlr.TerminalNode { + return s.GetToken(ConfigParserWHITESPACE, i) +} + +func (s *LeadingCommentContext) AllString_() []IStringContext { + children := s.GetChildren() + len := 0 + for _, ctx := range children { + if _, ok := ctx.(IStringContext); ok { + len++ + } + } + + tst := make([]IStringContext, len) + i := 0 + for _, ctx := range children { + if t, ok := ctx.(IStringContext); ok { + tst[i] = t.(IStringContext) + i++ + } + } + + return tst +} + +func (s *LeadingCommentContext) String_(i int) IStringContext { + var t antlr.RuleContext + j := 0 + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(IStringContext); ok { + if j == i { + t = ctx.(antlr.RuleContext) + break + } + j++ + } + } + + if t == nil { + return nil + } + + return t.(IStringContext) +} + +func (s *LeadingCommentContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *LeadingCommentContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +func (s *LeadingCommentContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.EnterLeadingComment(s) + } +} + +func (s *LeadingCommentContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.ExitLeadingComment(s) + } +} + +func (p *ConfigParser) LeadingComment() (localctx ILeadingCommentContext) { + localctx = NewLeadingCommentContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 10, ConfigParserRULE_leadingComment) + var _la int + + p.EnterOuterAlt(localctx, 1) + { + p.SetState(56) + p.Match(ConfigParserHASH) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + p.SetState(58) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + if _la == ConfigParserWHITESPACE { + { + p.SetState(57) + p.Match(ConfigParserWHITESPACE) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + + } + p.SetState(64) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + for ok := true; ok; ok = _la == ConfigParserSTRING || _la == ConfigParserQUOTED_STRING { + { + p.SetState(60) + p.String_() + } + p.SetState(62) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + if _la == ConfigParserWHITESPACE { + { + p.SetState(61) + p.Match(ConfigParserWHITESPACE) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + + } + + p.SetState(66) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} + +// IStringContext is an interface to support dynamic dispatch. +type IStringContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + + // Getter signatures + QUOTED_STRING() antlr.TerminalNode + STRING() antlr.TerminalNode + + // IsStringContext differentiates from other interfaces. + IsStringContext() +} + +type StringContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptyStringContext() *StringContext { + var p = new(StringContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_string + return p +} + +func InitEmptyStringContext(p *StringContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_string +} + +func (*StringContext) IsStringContext() {} + +func NewStringContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *StringContext { + var p = new(StringContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = ConfigParserRULE_string + + return p +} + +func (s *StringContext) GetParser() antlr.Parser { return s.parser } + +func (s *StringContext) QUOTED_STRING() antlr.TerminalNode { + return s.GetToken(ConfigParserQUOTED_STRING, 0) +} + +func (s *StringContext) STRING() antlr.TerminalNode { + return s.GetToken(ConfigParserSTRING, 0) +} + +func (s *StringContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *StringContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +func (s *StringContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.EnterString(s) + } +} + +func (s *StringContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.ExitString(s) + } +} + +func (p *ConfigParser) String_() (localctx IStringContext) { + localctx = NewStringContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 12, ConfigParserRULE_string) + var _la int + + p.EnterOuterAlt(localctx, 1) + { + p.SetState(68) + _la = p.GetTokenStream().LA(1) + + if !(_la == ConfigParserSTRING || _la == ConfigParserQUOTED_STRING) { + p.GetErrorHandler().RecoverInline(p) + } else { + p.GetErrorHandler().ReportMatch(p) + p.Consume() + } + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} diff --git a/handlers/sshd_config/shared.go b/handlers/sshd_config/shared.go index aa2d56f..3f850a5 100644 --- a/handlers/sshd_config/shared.go +++ b/handlers/sshd_config/shared.go @@ -7,9 +7,9 @@ import ( protocol "github.com/tliron/glsp/protocol_3_16" ) -type SSHDocument struct { +type SSHDDocument struct { Config *ast.SSHDConfig Indexes *indexes.SSHDIndexes } -var DocumentParserMap = map[protocol.DocumentUri]*SSHDocument{} +var DocumentParserMap = map[protocol.DocumentUri]*SSHDDocument{} diff --git a/handlers/sshd_config/test_utils/input.go b/handlers/sshd_config/test_utils/input.go index 4f6f5fd..cc6e59c 100644 --- a/handlers/sshd_config/test_utils/input.go +++ b/handlers/sshd_config/test_utils/input.go @@ -11,9 +11,9 @@ import ( func DocumentFromInput( t *testing.T, content string, -) *sshdconfig.SSHDocument { +) *sshdconfig.SSHDDocument { input := utils.Dedent(content) - c := ast.NewSSHConfig() + c := ast.NewSSHDConfig() errors := c.Parse(input) if len(errors) > 0 { @@ -26,7 +26,7 @@ func DocumentFromInput( t.Fatalf("Index error: %v", errors) } - return &sshdconfig.SSHDocument{ + return &sshdconfig.SSHDDocument{ Config: c, Indexes: i, } From 846851d50b4fc20441d6a132c854a70f81ac50ce Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Sun, 22 Sep 2024 12:30:08 +0200 Subject: [PATCH 072/133] fix: Bugfixes --- handlers/aliases/ast/listener.go | 2 +- handlers/aliases/ast/parser.go | 2 +- .../aliases/{ => ast}/parser/Aliases.interp | 0 .../aliases/{ => ast}/parser/Aliases.tokens | 0 .../{ => ast}/parser/AliasesLexer.interp | 0 .../{ => ast}/parser/AliasesLexer.tokens | 0 .../{ => ast}/parser/aliases_base_listener.go | 0 .../aliases/{ => ast}/parser/aliases_lexer.go | 0 .../{ => ast}/parser/aliases_listener.go | 0 .../{ => ast}/parser/aliases_parser.go | 0 handlers/sshd_config/analyzer/match.go | 4 +- handlers/sshd_config/ast/parser_test.go | 10 +- handlers/sshd_config/ast/sshd_config.go | 2 +- .../sshd_config/handlers/completions_match.go | 2 +- .../sshd_config/handlers/formatting_nodes.go | 2 +- .../sshd_config/match-parser/Match.interp | 23 - .../sshd_config/match-parser/Match.tokens | 4 - .../match-parser/MatchLexer.interp | 26 - .../match-parser/MatchLexer.tokens | 4 - .../match-parser/match_base_listener.go | 58 - .../sshd_config/match-parser/match_lexer.go | 109 -- .../match-parser/match_listener.go | 46 - .../sshd_config/match-parser/match_parser.go | 961 ------------- .../parser/handlers/sshd_config/Config.interp | 28 - .../parser/handlers/sshd_config/Config.tokens | 6 - .../handlers/sshd_config/ConfigLexer.interp | 32 - .../handlers/sshd_config/ConfigLexer.tokens | 6 - .../sshd_config/config_base_listener.go | 64 - .../handlers/sshd_config/config_lexer.go | 122 -- .../handlers/sshd_config/config_listener.go | 52 - .../handlers/sshd_config/config_parser.go | 1254 ----------------- 31 files changed, 16 insertions(+), 2803 deletions(-) rename handlers/aliases/{ => ast}/parser/Aliases.interp (100%) rename handlers/aliases/{ => ast}/parser/Aliases.tokens (100%) rename handlers/aliases/{ => ast}/parser/AliasesLexer.interp (100%) rename handlers/aliases/{ => ast}/parser/AliasesLexer.tokens (100%) rename handlers/aliases/{ => ast}/parser/aliases_base_listener.go (100%) rename handlers/aliases/{ => ast}/parser/aliases_lexer.go (100%) rename handlers/aliases/{ => ast}/parser/aliases_listener.go (100%) rename handlers/aliases/{ => ast}/parser/aliases_parser.go (100%) delete mode 100644 handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/Match.interp delete mode 100644 handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/Match.tokens delete mode 100644 handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/MatchLexer.interp delete mode 100644 handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/MatchLexer.tokens delete mode 100644 handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/match_base_listener.go delete mode 100644 handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/match_lexer.go delete mode 100644 handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/match_listener.go delete mode 100644 handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/match_parser.go delete mode 100644 handlers/sshd_config/parser/handlers/sshd_config/Config.interp delete mode 100644 handlers/sshd_config/parser/handlers/sshd_config/Config.tokens delete mode 100644 handlers/sshd_config/parser/handlers/sshd_config/ConfigLexer.interp delete mode 100644 handlers/sshd_config/parser/handlers/sshd_config/ConfigLexer.tokens delete mode 100644 handlers/sshd_config/parser/handlers/sshd_config/config_base_listener.go delete mode 100644 handlers/sshd_config/parser/handlers/sshd_config/config_lexer.go delete mode 100644 handlers/sshd_config/parser/handlers/sshd_config/config_listener.go delete mode 100644 handlers/sshd_config/parser/handlers/sshd_config/config_parser.go diff --git a/handlers/aliases/ast/listener.go b/handlers/aliases/ast/listener.go index 0ccd6b9..3a5c112 100644 --- a/handlers/aliases/ast/listener.go +++ b/handlers/aliases/ast/listener.go @@ -2,7 +2,7 @@ package ast import ( "config-lsp/common" - "config-lsp/handlers/aliases/parser" + "config-lsp/handlers/aliases/ast/parser" "github.com/antlr4-go/antlr/v4" ) diff --git a/handlers/aliases/ast/parser.go b/handlers/aliases/ast/parser.go index e0384c9..44bcdec 100644 --- a/handlers/aliases/ast/parser.go +++ b/handlers/aliases/ast/parser.go @@ -2,7 +2,7 @@ package ast import ( "config-lsp/common" - "config-lsp/handlers/aliases/parser" + "config-lsp/handlers/aliases/ast/parser" "config-lsp/utils" "regexp" diff --git a/handlers/aliases/parser/Aliases.interp b/handlers/aliases/ast/parser/Aliases.interp similarity index 100% rename from handlers/aliases/parser/Aliases.interp rename to handlers/aliases/ast/parser/Aliases.interp diff --git a/handlers/aliases/parser/Aliases.tokens b/handlers/aliases/ast/parser/Aliases.tokens similarity index 100% rename from handlers/aliases/parser/Aliases.tokens rename to handlers/aliases/ast/parser/Aliases.tokens diff --git a/handlers/aliases/parser/AliasesLexer.interp b/handlers/aliases/ast/parser/AliasesLexer.interp similarity index 100% rename from handlers/aliases/parser/AliasesLexer.interp rename to handlers/aliases/ast/parser/AliasesLexer.interp diff --git a/handlers/aliases/parser/AliasesLexer.tokens b/handlers/aliases/ast/parser/AliasesLexer.tokens similarity index 100% rename from handlers/aliases/parser/AliasesLexer.tokens rename to handlers/aliases/ast/parser/AliasesLexer.tokens diff --git a/handlers/aliases/parser/aliases_base_listener.go b/handlers/aliases/ast/parser/aliases_base_listener.go similarity index 100% rename from handlers/aliases/parser/aliases_base_listener.go rename to handlers/aliases/ast/parser/aliases_base_listener.go diff --git a/handlers/aliases/parser/aliases_lexer.go b/handlers/aliases/ast/parser/aliases_lexer.go similarity index 100% rename from handlers/aliases/parser/aliases_lexer.go rename to handlers/aliases/ast/parser/aliases_lexer.go diff --git a/handlers/aliases/parser/aliases_listener.go b/handlers/aliases/ast/parser/aliases_listener.go similarity index 100% rename from handlers/aliases/parser/aliases_listener.go rename to handlers/aliases/ast/parser/aliases_listener.go diff --git a/handlers/aliases/parser/aliases_parser.go b/handlers/aliases/ast/parser/aliases_parser.go similarity index 100% rename from handlers/aliases/parser/aliases_parser.go rename to handlers/aliases/ast/parser/aliases_parser.go diff --git a/handlers/sshd_config/analyzer/match.go b/handlers/sshd_config/analyzer/match.go index 9a2bb63..b508e86 100644 --- a/handlers/sshd_config/analyzer/match.go +++ b/handlers/sshd_config/analyzer/match.go @@ -54,11 +54,11 @@ func analyzeMatchBlocks( } func analyzeMatchValueNegation( - value *matchparser.matchparser, + value *matchparser.MatchValue, ) []common.LSPError { errs := make([]common.LSPError, 0) - positionsAsList := utils.AllIndexes(value.Value.Value, "!") + positionsAsList := utils.AllIndexes(value.Value.Raw, "!") positions := utils.SliceToMap(positionsAsList, struct{}{}) delete(positions, 0) diff --git a/handlers/sshd_config/ast/parser_test.go b/handlers/sshd_config/ast/parser_test.go index ca2ceb8..28081ff 100644 --- a/handlers/sshd_config/ast/parser_test.go +++ b/handlers/sshd_config/ast/parser_test.go @@ -59,7 +59,7 @@ PasswordAuthentication yes } } -func TestMatchSimpleBlock( +func TestSimpleMatchBlock( t *testing.T, ) { input := utils.Dedent(` @@ -92,6 +92,10 @@ Match Address 192.168.0.1 t.Errorf("Expected second entry to be 'Match Address 192.168.0.1', but got: %v", secondEntry.MatchOption.Value) } + if !(secondEntry.Options.Size() == 1) { + t.Errorf("Expected 1 option in match block, but got: %v", secondEntry.Options) + } + if !(secondEntry.Start.Line == 2 && secondEntry.Start.Character == 0 && secondEntry.End.Line == 3 && secondEntry.End.Character == 27) { t.Errorf("Expected second entry's location to be 2:0-3:25, but got: %v", secondEntry.LocationRange) } @@ -201,6 +205,10 @@ Match Address 192.168.0.2 t.Errorf("Expected 2 options in second match block, but got: %v", secondEntry.Options) } + if !(secondEntry.Options.Size() == 2) { + t.Errorf("Expected 2 options in second match block, but got: %v", secondEntry.Options) + } + rawThirdEntry, _ := secondEntry.Options.Get(uint32(3)) thirdEntry := rawThirdEntry.(*SSHDOption) if !(thirdEntry.Key.Value.Value == "PasswordAuthentication" && thirdEntry.OptionValue.Value.Value == "yes" && thirdEntry.LocationRange.Start.Line == 3) { diff --git a/handlers/sshd_config/ast/sshd_config.go b/handlers/sshd_config/ast/sshd_config.go index 28fbb75..73513e2 100644 --- a/handlers/sshd_config/ast/sshd_config.go +++ b/handlers/sshd_config/ast/sshd_config.go @@ -47,7 +47,7 @@ type SSHDOption struct { type SSHDMatchBlock struct { common.LocationRange MatchOption *SSHDOption - MatchValue *matchparser.matchparser + MatchValue *matchparser.Match // [uint32]*SSHDOption -> line number -> *SSHDOption Options *treemap.Map diff --git a/handlers/sshd_config/handlers/completions_match.go b/handlers/sshd_config/handlers/completions_match.go index 9d225a1..a5dfa73 100644 --- a/handlers/sshd_config/handlers/completions_match.go +++ b/handlers/sshd_config/handlers/completions_match.go @@ -11,7 +11,7 @@ import ( func getMatchCompletions( d *sshdconfig.SSHDDocument, cursor common.CursorPosition, - match *matchparser.matchparser, + match *matchparser.Match, ) ([]protocol.CompletionItem, error) { if match == nil || len(match.Entries) == 0 { completions := getMatchCriteriaCompletions() diff --git a/handlers/sshd_config/handlers/formatting_nodes.go b/handlers/sshd_config/handlers/formatting_nodes.go index 1f521f7..b94b27d 100644 --- a/handlers/sshd_config/handlers/formatting_nodes.go +++ b/handlers/sshd_config/handlers/formatting_nodes.go @@ -80,7 +80,7 @@ func formatSSHDMatchBlock( } func formatMatchToString( - match *matchparser.matchparser, + match *matchparser.Match, ) string { entriesAsStrings := utils.Map( match.Entries, diff --git a/handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/Match.interp b/handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/Match.interp deleted file mode 100644 index 491bdd3..0000000 --- a/handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/Match.interp +++ /dev/null @@ -1,23 +0,0 @@ -token literal names: -null -',' -null -null - -token symbolic names: -null -COMMA -STRING -WHITESPACE - -rule names: -root -matchEntry -separator -criteria -values -value - - -atn: -[4, 1, 3, 52, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 2, 5, 7, 5, 1, 0, 3, 0, 14, 8, 0, 1, 0, 1, 0, 3, 0, 18, 8, 0, 5, 0, 20, 8, 0, 10, 0, 12, 0, 23, 9, 0, 1, 0, 1, 0, 1, 1, 1, 1, 3, 1, 29, 8, 1, 1, 1, 3, 1, 32, 8, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, 3, 4, 39, 8, 4, 1, 4, 1, 4, 3, 4, 43, 8, 4, 5, 4, 45, 8, 4, 10, 4, 12, 4, 48, 9, 4, 1, 5, 1, 5, 1, 5, 0, 0, 6, 0, 2, 4, 6, 8, 10, 0, 0, 53, 0, 13, 1, 0, 0, 0, 2, 26, 1, 0, 0, 0, 4, 33, 1, 0, 0, 0, 6, 35, 1, 0, 0, 0, 8, 38, 1, 0, 0, 0, 10, 49, 1, 0, 0, 0, 12, 14, 3, 2, 1, 0, 13, 12, 1, 0, 0, 0, 13, 14, 1, 0, 0, 0, 14, 21, 1, 0, 0, 0, 15, 17, 5, 3, 0, 0, 16, 18, 3, 2, 1, 0, 17, 16, 1, 0, 0, 0, 17, 18, 1, 0, 0, 0, 18, 20, 1, 0, 0, 0, 19, 15, 1, 0, 0, 0, 20, 23, 1, 0, 0, 0, 21, 19, 1, 0, 0, 0, 21, 22, 1, 0, 0, 0, 22, 24, 1, 0, 0, 0, 23, 21, 1, 0, 0, 0, 24, 25, 5, 0, 0, 1, 25, 1, 1, 0, 0, 0, 26, 28, 3, 6, 3, 0, 27, 29, 3, 4, 2, 0, 28, 27, 1, 0, 0, 0, 28, 29, 1, 0, 0, 0, 29, 31, 1, 0, 0, 0, 30, 32, 3, 8, 4, 0, 31, 30, 1, 0, 0, 0, 31, 32, 1, 0, 0, 0, 32, 3, 1, 0, 0, 0, 33, 34, 5, 3, 0, 0, 34, 5, 1, 0, 0, 0, 35, 36, 5, 2, 0, 0, 36, 7, 1, 0, 0, 0, 37, 39, 3, 10, 5, 0, 38, 37, 1, 0, 0, 0, 38, 39, 1, 0, 0, 0, 39, 46, 1, 0, 0, 0, 40, 42, 5, 1, 0, 0, 41, 43, 3, 10, 5, 0, 42, 41, 1, 0, 0, 0, 42, 43, 1, 0, 0, 0, 43, 45, 1, 0, 0, 0, 44, 40, 1, 0, 0, 0, 45, 48, 1, 0, 0, 0, 46, 44, 1, 0, 0, 0, 46, 47, 1, 0, 0, 0, 47, 9, 1, 0, 0, 0, 48, 46, 1, 0, 0, 0, 49, 50, 5, 2, 0, 0, 50, 11, 1, 0, 0, 0, 8, 13, 17, 21, 28, 31, 38, 42, 46] \ No newline at end of file diff --git a/handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/Match.tokens b/handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/Match.tokens deleted file mode 100644 index 9172656..0000000 --- a/handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/Match.tokens +++ /dev/null @@ -1,4 +0,0 @@ -COMMA=1 -STRING=2 -WHITESPACE=3 -','=1 diff --git a/handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/MatchLexer.interp b/handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/MatchLexer.interp deleted file mode 100644 index 90a8247..0000000 --- a/handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/MatchLexer.interp +++ /dev/null @@ -1,26 +0,0 @@ -token literal names: -null -',' -null -null - -token symbolic names: -null -COMMA -STRING -WHITESPACE - -rule names: -COMMA -STRING -WHITESPACE - -channel names: -DEFAULT_TOKEN_CHANNEL -HIDDEN - -mode names: -DEFAULT_MODE - -atn: -[4, 0, 3, 19, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 1, 0, 1, 0, 1, 1, 4, 1, 11, 8, 1, 11, 1, 12, 1, 12, 1, 2, 4, 2, 16, 8, 2, 11, 2, 12, 2, 17, 0, 0, 3, 1, 1, 3, 2, 5, 3, 1, 0, 2, 5, 0, 9, 10, 13, 13, 32, 32, 35, 35, 44, 44, 2, 0, 9, 9, 32, 32, 20, 0, 1, 1, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, 5, 1, 0, 0, 0, 1, 7, 1, 0, 0, 0, 3, 10, 1, 0, 0, 0, 5, 15, 1, 0, 0, 0, 7, 8, 5, 44, 0, 0, 8, 2, 1, 0, 0, 0, 9, 11, 8, 0, 0, 0, 10, 9, 1, 0, 0, 0, 11, 12, 1, 0, 0, 0, 12, 10, 1, 0, 0, 0, 12, 13, 1, 0, 0, 0, 13, 4, 1, 0, 0, 0, 14, 16, 7, 1, 0, 0, 15, 14, 1, 0, 0, 0, 16, 17, 1, 0, 0, 0, 17, 15, 1, 0, 0, 0, 17, 18, 1, 0, 0, 0, 18, 6, 1, 0, 0, 0, 3, 0, 12, 17, 0] \ No newline at end of file diff --git a/handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/MatchLexer.tokens b/handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/MatchLexer.tokens deleted file mode 100644 index 9172656..0000000 --- a/handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/MatchLexer.tokens +++ /dev/null @@ -1,4 +0,0 @@ -COMMA=1 -STRING=2 -WHITESPACE=3 -','=1 diff --git a/handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/match_base_listener.go b/handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/match_base_listener.go deleted file mode 100644 index f9cb3e5..0000000 --- a/handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/match_base_listener.go +++ /dev/null @@ -1,58 +0,0 @@ -// Code generated from handlers/sshd_config/match-parser/Match.g4 by ANTLR 4.13.0. DO NOT EDIT. - -package parser // Match - -import "github.com/antlr4-go/antlr/v4" - -// BaseMatchListener is a complete listener for a parse tree produced by MatchParser. -type BaseMatchListener struct{} - -var _ MatchListener = &BaseMatchListener{} - -// VisitTerminal is called when a terminal node is visited. -func (s *BaseMatchListener) VisitTerminal(node antlr.TerminalNode) {} - -// VisitErrorNode is called when an error node is visited. -func (s *BaseMatchListener) VisitErrorNode(node antlr.ErrorNode) {} - -// EnterEveryRule is called when any rule is entered. -func (s *BaseMatchListener) EnterEveryRule(ctx antlr.ParserRuleContext) {} - -// ExitEveryRule is called when any rule is exited. -func (s *BaseMatchListener) ExitEveryRule(ctx antlr.ParserRuleContext) {} - -// EnterRoot is called when production root is entered. -func (s *BaseMatchListener) EnterRoot(ctx *RootContext) {} - -// ExitRoot is called when production root is exited. -func (s *BaseMatchListener) ExitRoot(ctx *RootContext) {} - -// EnterMatchEntry is called when production matchEntry is entered. -func (s *BaseMatchListener) EnterMatchEntry(ctx *MatchEntryContext) {} - -// ExitMatchEntry is called when production matchEntry is exited. -func (s *BaseMatchListener) ExitMatchEntry(ctx *MatchEntryContext) {} - -// EnterSeparator is called when production separator is entered. -func (s *BaseMatchListener) EnterSeparator(ctx *SeparatorContext) {} - -// ExitSeparator is called when production separator is exited. -func (s *BaseMatchListener) ExitSeparator(ctx *SeparatorContext) {} - -// EnterCriteria is called when production criteria is entered. -func (s *BaseMatchListener) EnterCriteria(ctx *CriteriaContext) {} - -// ExitCriteria is called when production criteria is exited. -func (s *BaseMatchListener) ExitCriteria(ctx *CriteriaContext) {} - -// EnterValues is called when production values is entered. -func (s *BaseMatchListener) EnterValues(ctx *ValuesContext) {} - -// ExitValues is called when production values is exited. -func (s *BaseMatchListener) ExitValues(ctx *ValuesContext) {} - -// EnterValue is called when production value is entered. -func (s *BaseMatchListener) EnterValue(ctx *ValueContext) {} - -// ExitValue is called when production value is exited. -func (s *BaseMatchListener) ExitValue(ctx *ValueContext) {} diff --git a/handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/match_lexer.go b/handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/match_lexer.go deleted file mode 100644 index 42d3891..0000000 --- a/handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/match_lexer.go +++ /dev/null @@ -1,109 +0,0 @@ -// Code generated from handlers/sshd_config/match-parser/Match.g4 by ANTLR 4.13.0. DO NOT EDIT. - -package parser - -import ( - "fmt" - "github.com/antlr4-go/antlr/v4" - "sync" - "unicode" -) - -// Suppress unused import error -var _ = fmt.Printf -var _ = sync.Once{} -var _ = unicode.IsLetter - -type MatchLexer struct { - *antlr.BaseLexer - channelNames []string - modeNames []string - // TODO: EOF string -} - -var MatchLexerLexerStaticData struct { - once sync.Once - serializedATN []int32 - ChannelNames []string - ModeNames []string - LiteralNames []string - SymbolicNames []string - RuleNames []string - PredictionContextCache *antlr.PredictionContextCache - atn *antlr.ATN - decisionToDFA []*antlr.DFA -} - -func matchlexerLexerInit() { - staticData := &MatchLexerLexerStaticData - staticData.ChannelNames = []string{ - "DEFAULT_TOKEN_CHANNEL", "HIDDEN", - } - staticData.ModeNames = []string{ - "DEFAULT_MODE", - } - staticData.LiteralNames = []string{ - "", "','", - } - staticData.SymbolicNames = []string{ - "", "COMMA", "STRING", "WHITESPACE", - } - staticData.RuleNames = []string{ - "COMMA", "STRING", "WHITESPACE", - } - staticData.PredictionContextCache = antlr.NewPredictionContextCache() - staticData.serializedATN = []int32{ - 4, 0, 3, 19, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 1, 0, 1, 0, 1, - 1, 4, 1, 11, 8, 1, 11, 1, 12, 1, 12, 1, 2, 4, 2, 16, 8, 2, 11, 2, 12, 2, - 17, 0, 0, 3, 1, 1, 3, 2, 5, 3, 1, 0, 2, 5, 0, 9, 10, 13, 13, 32, 32, 35, - 35, 44, 44, 2, 0, 9, 9, 32, 32, 20, 0, 1, 1, 0, 0, 0, 0, 3, 1, 0, 0, 0, - 0, 5, 1, 0, 0, 0, 1, 7, 1, 0, 0, 0, 3, 10, 1, 0, 0, 0, 5, 15, 1, 0, 0, - 0, 7, 8, 5, 44, 0, 0, 8, 2, 1, 0, 0, 0, 9, 11, 8, 0, 0, 0, 10, 9, 1, 0, - 0, 0, 11, 12, 1, 0, 0, 0, 12, 10, 1, 0, 0, 0, 12, 13, 1, 0, 0, 0, 13, 4, - 1, 0, 0, 0, 14, 16, 7, 1, 0, 0, 15, 14, 1, 0, 0, 0, 16, 17, 1, 0, 0, 0, - 17, 15, 1, 0, 0, 0, 17, 18, 1, 0, 0, 0, 18, 6, 1, 0, 0, 0, 3, 0, 12, 17, - 0, - } - deserializer := antlr.NewATNDeserializer(nil) - staticData.atn = deserializer.Deserialize(staticData.serializedATN) - atn := staticData.atn - staticData.decisionToDFA = make([]*antlr.DFA, len(atn.DecisionToState)) - decisionToDFA := staticData.decisionToDFA - for index, state := range atn.DecisionToState { - decisionToDFA[index] = antlr.NewDFA(state, index) - } -} - -// MatchLexerInit initializes any static state used to implement MatchLexer. By default the -// static state used to implement the lexer is lazily initialized during the first call to -// NewMatchLexer(). You can call this function if you wish to initialize the static state ahead -// of time. -func MatchLexerInit() { - staticData := &MatchLexerLexerStaticData - staticData.once.Do(matchlexerLexerInit) -} - -// NewMatchLexer produces a new lexer instance for the optional input antlr.CharStream. -func NewMatchLexer(input antlr.CharStream) *MatchLexer { - MatchLexerInit() - l := new(MatchLexer) - l.BaseLexer = antlr.NewBaseLexer(input) - staticData := &MatchLexerLexerStaticData - l.Interpreter = antlr.NewLexerATNSimulator(l, staticData.atn, staticData.decisionToDFA, staticData.PredictionContextCache) - l.channelNames = staticData.ChannelNames - l.modeNames = staticData.ModeNames - l.RuleNames = staticData.RuleNames - l.LiteralNames = staticData.LiteralNames - l.SymbolicNames = staticData.SymbolicNames - l.GrammarFileName = "Match.g4" - // TODO: l.EOF = antlr.TokenEOF - - return l -} - -// MatchLexer tokens. -const ( - MatchLexerCOMMA = 1 - MatchLexerSTRING = 2 - MatchLexerWHITESPACE = 3 -) diff --git a/handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/match_listener.go b/handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/match_listener.go deleted file mode 100644 index d13801e..0000000 --- a/handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/match_listener.go +++ /dev/null @@ -1,46 +0,0 @@ -// Code generated from handlers/sshd_config/match-parser/Match.g4 by ANTLR 4.13.0. DO NOT EDIT. - -package parser // Match - -import "github.com/antlr4-go/antlr/v4" - -// MatchListener is a complete listener for a parse tree produced by MatchParser. -type MatchListener interface { - antlr.ParseTreeListener - - // EnterRoot is called when entering the root production. - EnterRoot(c *RootContext) - - // EnterMatchEntry is called when entering the matchEntry production. - EnterMatchEntry(c *MatchEntryContext) - - // EnterSeparator is called when entering the separator production. - EnterSeparator(c *SeparatorContext) - - // EnterCriteria is called when entering the criteria production. - EnterCriteria(c *CriteriaContext) - - // EnterValues is called when entering the values production. - EnterValues(c *ValuesContext) - - // EnterValue is called when entering the value production. - EnterValue(c *ValueContext) - - // ExitRoot is called when exiting the root production. - ExitRoot(c *RootContext) - - // ExitMatchEntry is called when exiting the matchEntry production. - ExitMatchEntry(c *MatchEntryContext) - - // ExitSeparator is called when exiting the separator production. - ExitSeparator(c *SeparatorContext) - - // ExitCriteria is called when exiting the criteria production. - ExitCriteria(c *CriteriaContext) - - // ExitValues is called when exiting the values production. - ExitValues(c *ValuesContext) - - // ExitValue is called when exiting the value production. - ExitValue(c *ValueContext) -} diff --git a/handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/match_parser.go b/handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/match_parser.go deleted file mode 100644 index bde60cb..0000000 --- a/handlers/sshd_config/match-parser/handlers/sshd_config/match-parser/match_parser.go +++ /dev/null @@ -1,961 +0,0 @@ -// Code generated from handlers/sshd_config/match-parser/Match.g4 by ANTLR 4.13.0. DO NOT EDIT. - -package parser // Match - -import ( - "fmt" - "strconv" - "sync" - - "github.com/antlr4-go/antlr/v4" -) - -// Suppress unused import errors -var _ = fmt.Printf -var _ = strconv.Itoa -var _ = sync.Once{} - -type MatchParser struct { - *antlr.BaseParser -} - -var MatchParserStaticData struct { - once sync.Once - serializedATN []int32 - LiteralNames []string - SymbolicNames []string - RuleNames []string - PredictionContextCache *antlr.PredictionContextCache - atn *antlr.ATN - decisionToDFA []*antlr.DFA -} - -func matchParserInit() { - staticData := &MatchParserStaticData - staticData.LiteralNames = []string{ - "", "','", - } - staticData.SymbolicNames = []string{ - "", "COMMA", "STRING", "WHITESPACE", - } - staticData.RuleNames = []string{ - "root", "matchEntry", "separator", "criteria", "values", "value", - } - staticData.PredictionContextCache = antlr.NewPredictionContextCache() - staticData.serializedATN = []int32{ - 4, 1, 3, 52, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, - 2, 5, 7, 5, 1, 0, 3, 0, 14, 8, 0, 1, 0, 1, 0, 3, 0, 18, 8, 0, 5, 0, 20, - 8, 0, 10, 0, 12, 0, 23, 9, 0, 1, 0, 1, 0, 1, 1, 1, 1, 3, 1, 29, 8, 1, 1, - 1, 3, 1, 32, 8, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, 3, 4, 39, 8, 4, 1, 4, - 1, 4, 3, 4, 43, 8, 4, 5, 4, 45, 8, 4, 10, 4, 12, 4, 48, 9, 4, 1, 5, 1, - 5, 1, 5, 0, 0, 6, 0, 2, 4, 6, 8, 10, 0, 0, 53, 0, 13, 1, 0, 0, 0, 2, 26, - 1, 0, 0, 0, 4, 33, 1, 0, 0, 0, 6, 35, 1, 0, 0, 0, 8, 38, 1, 0, 0, 0, 10, - 49, 1, 0, 0, 0, 12, 14, 3, 2, 1, 0, 13, 12, 1, 0, 0, 0, 13, 14, 1, 0, 0, - 0, 14, 21, 1, 0, 0, 0, 15, 17, 5, 3, 0, 0, 16, 18, 3, 2, 1, 0, 17, 16, - 1, 0, 0, 0, 17, 18, 1, 0, 0, 0, 18, 20, 1, 0, 0, 0, 19, 15, 1, 0, 0, 0, - 20, 23, 1, 0, 0, 0, 21, 19, 1, 0, 0, 0, 21, 22, 1, 0, 0, 0, 22, 24, 1, - 0, 0, 0, 23, 21, 1, 0, 0, 0, 24, 25, 5, 0, 0, 1, 25, 1, 1, 0, 0, 0, 26, - 28, 3, 6, 3, 0, 27, 29, 3, 4, 2, 0, 28, 27, 1, 0, 0, 0, 28, 29, 1, 0, 0, - 0, 29, 31, 1, 0, 0, 0, 30, 32, 3, 8, 4, 0, 31, 30, 1, 0, 0, 0, 31, 32, - 1, 0, 0, 0, 32, 3, 1, 0, 0, 0, 33, 34, 5, 3, 0, 0, 34, 5, 1, 0, 0, 0, 35, - 36, 5, 2, 0, 0, 36, 7, 1, 0, 0, 0, 37, 39, 3, 10, 5, 0, 38, 37, 1, 0, 0, - 0, 38, 39, 1, 0, 0, 0, 39, 46, 1, 0, 0, 0, 40, 42, 5, 1, 0, 0, 41, 43, - 3, 10, 5, 0, 42, 41, 1, 0, 0, 0, 42, 43, 1, 0, 0, 0, 43, 45, 1, 0, 0, 0, - 44, 40, 1, 0, 0, 0, 45, 48, 1, 0, 0, 0, 46, 44, 1, 0, 0, 0, 46, 47, 1, - 0, 0, 0, 47, 9, 1, 0, 0, 0, 48, 46, 1, 0, 0, 0, 49, 50, 5, 2, 0, 0, 50, - 11, 1, 0, 0, 0, 8, 13, 17, 21, 28, 31, 38, 42, 46, - } - deserializer := antlr.NewATNDeserializer(nil) - staticData.atn = deserializer.Deserialize(staticData.serializedATN) - atn := staticData.atn - staticData.decisionToDFA = make([]*antlr.DFA, len(atn.DecisionToState)) - decisionToDFA := staticData.decisionToDFA - for index, state := range atn.DecisionToState { - decisionToDFA[index] = antlr.NewDFA(state, index) - } -} - -// MatchParserInit initializes any static state used to implement MatchParser. By default the -// static state used to implement the parser is lazily initialized during the first call to -// NewMatchParser(). You can call this function if you wish to initialize the static state ahead -// of time. -func MatchParserInit() { - staticData := &MatchParserStaticData - staticData.once.Do(matchParserInit) -} - -// NewMatchParser produces a new parser instance for the optional input antlr.TokenStream. -func NewMatchParser(input antlr.TokenStream) *MatchParser { - MatchParserInit() - this := new(MatchParser) - this.BaseParser = antlr.NewBaseParser(input) - staticData := &MatchParserStaticData - this.Interpreter = antlr.NewParserATNSimulator(this, staticData.atn, staticData.decisionToDFA, staticData.PredictionContextCache) - this.RuleNames = staticData.RuleNames - this.LiteralNames = staticData.LiteralNames - this.SymbolicNames = staticData.SymbolicNames - this.GrammarFileName = "Match.g4" - - return this -} - -// MatchParser tokens. -const ( - MatchParserEOF = antlr.TokenEOF - MatchParserCOMMA = 1 - MatchParserSTRING = 2 - MatchParserWHITESPACE = 3 -) - -// MatchParser rules. -const ( - MatchParserRULE_root = 0 - MatchParserRULE_matchEntry = 1 - MatchParserRULE_separator = 2 - MatchParserRULE_criteria = 3 - MatchParserRULE_values = 4 - MatchParserRULE_value = 5 -) - -// IRootContext is an interface to support dynamic dispatch. -type IRootContext interface { - antlr.ParserRuleContext - - // GetParser returns the parser. - GetParser() antlr.Parser - - // Getter signatures - EOF() antlr.TerminalNode - AllMatchEntry() []IMatchEntryContext - MatchEntry(i int) IMatchEntryContext - AllWHITESPACE() []antlr.TerminalNode - WHITESPACE(i int) antlr.TerminalNode - - // IsRootContext differentiates from other interfaces. - IsRootContext() -} - -type RootContext struct { - antlr.BaseParserRuleContext - parser antlr.Parser -} - -func NewEmptyRootContext() *RootContext { - var p = new(RootContext) - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) - p.RuleIndex = MatchParserRULE_root - return p -} - -func InitEmptyRootContext(p *RootContext) { - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) - p.RuleIndex = MatchParserRULE_root -} - -func (*RootContext) IsRootContext() {} - -func NewRootContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *RootContext { - var p = new(RootContext) - - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) - - p.parser = parser - p.RuleIndex = MatchParserRULE_root - - return p -} - -func (s *RootContext) GetParser() antlr.Parser { return s.parser } - -func (s *RootContext) EOF() antlr.TerminalNode { - return s.GetToken(MatchParserEOF, 0) -} - -func (s *RootContext) AllMatchEntry() []IMatchEntryContext { - children := s.GetChildren() - len := 0 - for _, ctx := range children { - if _, ok := ctx.(IMatchEntryContext); ok { - len++ - } - } - - tst := make([]IMatchEntryContext, len) - i := 0 - for _, ctx := range children { - if t, ok := ctx.(IMatchEntryContext); ok { - tst[i] = t.(IMatchEntryContext) - i++ - } - } - - return tst -} - -func (s *RootContext) MatchEntry(i int) IMatchEntryContext { - var t antlr.RuleContext - j := 0 - for _, ctx := range s.GetChildren() { - if _, ok := ctx.(IMatchEntryContext); ok { - if j == i { - t = ctx.(antlr.RuleContext) - break - } - j++ - } - } - - if t == nil { - return nil - } - - return t.(IMatchEntryContext) -} - -func (s *RootContext) AllWHITESPACE() []antlr.TerminalNode { - return s.GetTokens(MatchParserWHITESPACE) -} - -func (s *RootContext) WHITESPACE(i int) antlr.TerminalNode { - return s.GetToken(MatchParserWHITESPACE, i) -} - -func (s *RootContext) GetRuleContext() antlr.RuleContext { - return s -} - -func (s *RootContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { - return antlr.TreesStringTree(s, ruleNames, recog) -} - -func (s *RootContext) EnterRule(listener antlr.ParseTreeListener) { - if listenerT, ok := listener.(MatchListener); ok { - listenerT.EnterRoot(s) - } -} - -func (s *RootContext) ExitRule(listener antlr.ParseTreeListener) { - if listenerT, ok := listener.(MatchListener); ok { - listenerT.ExitRoot(s) - } -} - -func (p *MatchParser) Root() (localctx IRootContext) { - localctx = NewRootContext(p, p.GetParserRuleContext(), p.GetState()) - p.EnterRule(localctx, 0, MatchParserRULE_root) - var _la int - - p.EnterOuterAlt(localctx, 1) - p.SetState(13) - p.GetErrorHandler().Sync(p) - if p.HasError() { - goto errorExit - } - _la = p.GetTokenStream().LA(1) - - if _la == MatchParserSTRING { - { - p.SetState(12) - p.MatchEntry() - } - - } - p.SetState(21) - p.GetErrorHandler().Sync(p) - if p.HasError() { - goto errorExit - } - _la = p.GetTokenStream().LA(1) - - for _la == MatchParserWHITESPACE { - { - p.SetState(15) - p.Match(MatchParserWHITESPACE) - if p.HasError() { - // Recognition error - abort rule - goto errorExit - } - } - p.SetState(17) - p.GetErrorHandler().Sync(p) - if p.HasError() { - goto errorExit - } - _la = p.GetTokenStream().LA(1) - - if _la == MatchParserSTRING { - { - p.SetState(16) - p.MatchEntry() - } - - } - - p.SetState(23) - p.GetErrorHandler().Sync(p) - if p.HasError() { - goto errorExit - } - _la = p.GetTokenStream().LA(1) - } - { - p.SetState(24) - p.Match(MatchParserEOF) - if p.HasError() { - // Recognition error - abort rule - goto errorExit - } - } - -errorExit: - if p.HasError() { - v := p.GetError() - localctx.SetException(v) - p.GetErrorHandler().ReportError(p, v) - p.GetErrorHandler().Recover(p, v) - p.SetError(nil) - } - p.ExitRule() - return localctx - goto errorExit // Trick to prevent compiler error if the label is not used -} - -// IMatchEntryContext is an interface to support dynamic dispatch. -type IMatchEntryContext interface { - antlr.ParserRuleContext - - // GetParser returns the parser. - GetParser() antlr.Parser - - // Getter signatures - Criteria() ICriteriaContext - Separator() ISeparatorContext - Values() IValuesContext - - // IsMatchEntryContext differentiates from other interfaces. - IsMatchEntryContext() -} - -type MatchEntryContext struct { - antlr.BaseParserRuleContext - parser antlr.Parser -} - -func NewEmptyMatchEntryContext() *MatchEntryContext { - var p = new(MatchEntryContext) - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) - p.RuleIndex = MatchParserRULE_matchEntry - return p -} - -func InitEmptyMatchEntryContext(p *MatchEntryContext) { - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) - p.RuleIndex = MatchParserRULE_matchEntry -} - -func (*MatchEntryContext) IsMatchEntryContext() {} - -func NewMatchEntryContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *MatchEntryContext { - var p = new(MatchEntryContext) - - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) - - p.parser = parser - p.RuleIndex = MatchParserRULE_matchEntry - - return p -} - -func (s *MatchEntryContext) GetParser() antlr.Parser { return s.parser } - -func (s *MatchEntryContext) Criteria() ICriteriaContext { - var t antlr.RuleContext - for _, ctx := range s.GetChildren() { - if _, ok := ctx.(ICriteriaContext); ok { - t = ctx.(antlr.RuleContext) - break - } - } - - if t == nil { - return nil - } - - return t.(ICriteriaContext) -} - -func (s *MatchEntryContext) Separator() ISeparatorContext { - var t antlr.RuleContext - for _, ctx := range s.GetChildren() { - if _, ok := ctx.(ISeparatorContext); ok { - t = ctx.(antlr.RuleContext) - break - } - } - - if t == nil { - return nil - } - - return t.(ISeparatorContext) -} - -func (s *MatchEntryContext) Values() IValuesContext { - var t antlr.RuleContext - for _, ctx := range s.GetChildren() { - if _, ok := ctx.(IValuesContext); ok { - t = ctx.(antlr.RuleContext) - break - } - } - - if t == nil { - return nil - } - - return t.(IValuesContext) -} - -func (s *MatchEntryContext) GetRuleContext() antlr.RuleContext { - return s -} - -func (s *MatchEntryContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { - return antlr.TreesStringTree(s, ruleNames, recog) -} - -func (s *MatchEntryContext) EnterRule(listener antlr.ParseTreeListener) { - if listenerT, ok := listener.(MatchListener); ok { - listenerT.EnterMatchEntry(s) - } -} - -func (s *MatchEntryContext) ExitRule(listener antlr.ParseTreeListener) { - if listenerT, ok := listener.(MatchListener); ok { - listenerT.ExitMatchEntry(s) - } -} - -func (p *MatchParser) MatchEntry() (localctx IMatchEntryContext) { - localctx = NewMatchEntryContext(p, p.GetParserRuleContext(), p.GetState()) - p.EnterRule(localctx, 2, MatchParserRULE_matchEntry) - p.EnterOuterAlt(localctx, 1) - { - p.SetState(26) - p.Criteria() - } - p.SetState(28) - p.GetErrorHandler().Sync(p) - - if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 3, p.GetParserRuleContext()) == 1 { - { - p.SetState(27) - p.Separator() - } - - } else if p.HasError() { // JIM - goto errorExit - } - p.SetState(31) - p.GetErrorHandler().Sync(p) - - if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 4, p.GetParserRuleContext()) == 1 { - { - p.SetState(30) - p.Values() - } - - } else if p.HasError() { // JIM - goto errorExit - } - -errorExit: - if p.HasError() { - v := p.GetError() - localctx.SetException(v) - p.GetErrorHandler().ReportError(p, v) - p.GetErrorHandler().Recover(p, v) - p.SetError(nil) - } - p.ExitRule() - return localctx - goto errorExit // Trick to prevent compiler error if the label is not used -} - -// ISeparatorContext is an interface to support dynamic dispatch. -type ISeparatorContext interface { - antlr.ParserRuleContext - - // GetParser returns the parser. - GetParser() antlr.Parser - - // Getter signatures - WHITESPACE() antlr.TerminalNode - - // IsSeparatorContext differentiates from other interfaces. - IsSeparatorContext() -} - -type SeparatorContext struct { - antlr.BaseParserRuleContext - parser antlr.Parser -} - -func NewEmptySeparatorContext() *SeparatorContext { - var p = new(SeparatorContext) - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) - p.RuleIndex = MatchParserRULE_separator - return p -} - -func InitEmptySeparatorContext(p *SeparatorContext) { - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) - p.RuleIndex = MatchParserRULE_separator -} - -func (*SeparatorContext) IsSeparatorContext() {} - -func NewSeparatorContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *SeparatorContext { - var p = new(SeparatorContext) - - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) - - p.parser = parser - p.RuleIndex = MatchParserRULE_separator - - return p -} - -func (s *SeparatorContext) GetParser() antlr.Parser { return s.parser } - -func (s *SeparatorContext) WHITESPACE() antlr.TerminalNode { - return s.GetToken(MatchParserWHITESPACE, 0) -} - -func (s *SeparatorContext) GetRuleContext() antlr.RuleContext { - return s -} - -func (s *SeparatorContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { - return antlr.TreesStringTree(s, ruleNames, recog) -} - -func (s *SeparatorContext) EnterRule(listener antlr.ParseTreeListener) { - if listenerT, ok := listener.(MatchListener); ok { - listenerT.EnterSeparator(s) - } -} - -func (s *SeparatorContext) ExitRule(listener antlr.ParseTreeListener) { - if listenerT, ok := listener.(MatchListener); ok { - listenerT.ExitSeparator(s) - } -} - -func (p *MatchParser) Separator() (localctx ISeparatorContext) { - localctx = NewSeparatorContext(p, p.GetParserRuleContext(), p.GetState()) - p.EnterRule(localctx, 4, MatchParserRULE_separator) - p.EnterOuterAlt(localctx, 1) - { - p.SetState(33) - p.Match(MatchParserWHITESPACE) - if p.HasError() { - // Recognition error - abort rule - goto errorExit - } - } - -errorExit: - if p.HasError() { - v := p.GetError() - localctx.SetException(v) - p.GetErrorHandler().ReportError(p, v) - p.GetErrorHandler().Recover(p, v) - p.SetError(nil) - } - p.ExitRule() - return localctx - goto errorExit // Trick to prevent compiler error if the label is not used -} - -// ICriteriaContext is an interface to support dynamic dispatch. -type ICriteriaContext interface { - antlr.ParserRuleContext - - // GetParser returns the parser. - GetParser() antlr.Parser - - // Getter signatures - STRING() antlr.TerminalNode - - // IsCriteriaContext differentiates from other interfaces. - IsCriteriaContext() -} - -type CriteriaContext struct { - antlr.BaseParserRuleContext - parser antlr.Parser -} - -func NewEmptyCriteriaContext() *CriteriaContext { - var p = new(CriteriaContext) - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) - p.RuleIndex = MatchParserRULE_criteria - return p -} - -func InitEmptyCriteriaContext(p *CriteriaContext) { - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) - p.RuleIndex = MatchParserRULE_criteria -} - -func (*CriteriaContext) IsCriteriaContext() {} - -func NewCriteriaContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *CriteriaContext { - var p = new(CriteriaContext) - - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) - - p.parser = parser - p.RuleIndex = MatchParserRULE_criteria - - return p -} - -func (s *CriteriaContext) GetParser() antlr.Parser { return s.parser } - -func (s *CriteriaContext) STRING() antlr.TerminalNode { - return s.GetToken(MatchParserSTRING, 0) -} - -func (s *CriteriaContext) GetRuleContext() antlr.RuleContext { - return s -} - -func (s *CriteriaContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { - return antlr.TreesStringTree(s, ruleNames, recog) -} - -func (s *CriteriaContext) EnterRule(listener antlr.ParseTreeListener) { - if listenerT, ok := listener.(MatchListener); ok { - listenerT.EnterCriteria(s) - } -} - -func (s *CriteriaContext) ExitRule(listener antlr.ParseTreeListener) { - if listenerT, ok := listener.(MatchListener); ok { - listenerT.ExitCriteria(s) - } -} - -func (p *MatchParser) Criteria() (localctx ICriteriaContext) { - localctx = NewCriteriaContext(p, p.GetParserRuleContext(), p.GetState()) - p.EnterRule(localctx, 6, MatchParserRULE_criteria) - p.EnterOuterAlt(localctx, 1) - { - p.SetState(35) - p.Match(MatchParserSTRING) - if p.HasError() { - // Recognition error - abort rule - goto errorExit - } - } - -errorExit: - if p.HasError() { - v := p.GetError() - localctx.SetException(v) - p.GetErrorHandler().ReportError(p, v) - p.GetErrorHandler().Recover(p, v) - p.SetError(nil) - } - p.ExitRule() - return localctx - goto errorExit // Trick to prevent compiler error if the label is not used -} - -// IValuesContext is an interface to support dynamic dispatch. -type IValuesContext interface { - antlr.ParserRuleContext - - // GetParser returns the parser. - GetParser() antlr.Parser - - // Getter signatures - AllValue() []IValueContext - Value(i int) IValueContext - AllCOMMA() []antlr.TerminalNode - COMMA(i int) antlr.TerminalNode - - // IsValuesContext differentiates from other interfaces. - IsValuesContext() -} - -type ValuesContext struct { - antlr.BaseParserRuleContext - parser antlr.Parser -} - -func NewEmptyValuesContext() *ValuesContext { - var p = new(ValuesContext) - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) - p.RuleIndex = MatchParserRULE_values - return p -} - -func InitEmptyValuesContext(p *ValuesContext) { - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) - p.RuleIndex = MatchParserRULE_values -} - -func (*ValuesContext) IsValuesContext() {} - -func NewValuesContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *ValuesContext { - var p = new(ValuesContext) - - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) - - p.parser = parser - p.RuleIndex = MatchParserRULE_values - - return p -} - -func (s *ValuesContext) GetParser() antlr.Parser { return s.parser } - -func (s *ValuesContext) AllValue() []IValueContext { - children := s.GetChildren() - len := 0 - for _, ctx := range children { - if _, ok := ctx.(IValueContext); ok { - len++ - } - } - - tst := make([]IValueContext, len) - i := 0 - for _, ctx := range children { - if t, ok := ctx.(IValueContext); ok { - tst[i] = t.(IValueContext) - i++ - } - } - - return tst -} - -func (s *ValuesContext) Value(i int) IValueContext { - var t antlr.RuleContext - j := 0 - for _, ctx := range s.GetChildren() { - if _, ok := ctx.(IValueContext); ok { - if j == i { - t = ctx.(antlr.RuleContext) - break - } - j++ - } - } - - if t == nil { - return nil - } - - return t.(IValueContext) -} - -func (s *ValuesContext) AllCOMMA() []antlr.TerminalNode { - return s.GetTokens(MatchParserCOMMA) -} - -func (s *ValuesContext) COMMA(i int) antlr.TerminalNode { - return s.GetToken(MatchParserCOMMA, i) -} - -func (s *ValuesContext) GetRuleContext() antlr.RuleContext { - return s -} - -func (s *ValuesContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { - return antlr.TreesStringTree(s, ruleNames, recog) -} - -func (s *ValuesContext) EnterRule(listener antlr.ParseTreeListener) { - if listenerT, ok := listener.(MatchListener); ok { - listenerT.EnterValues(s) - } -} - -func (s *ValuesContext) ExitRule(listener antlr.ParseTreeListener) { - if listenerT, ok := listener.(MatchListener); ok { - listenerT.ExitValues(s) - } -} - -func (p *MatchParser) Values() (localctx IValuesContext) { - localctx = NewValuesContext(p, p.GetParserRuleContext(), p.GetState()) - p.EnterRule(localctx, 8, MatchParserRULE_values) - var _la int - - p.EnterOuterAlt(localctx, 1) - p.SetState(38) - p.GetErrorHandler().Sync(p) - if p.HasError() { - goto errorExit - } - _la = p.GetTokenStream().LA(1) - - if _la == MatchParserSTRING { - { - p.SetState(37) - p.Value() - } - - } - p.SetState(46) - p.GetErrorHandler().Sync(p) - if p.HasError() { - goto errorExit - } - _la = p.GetTokenStream().LA(1) - - for _la == MatchParserCOMMA { - { - p.SetState(40) - p.Match(MatchParserCOMMA) - if p.HasError() { - // Recognition error - abort rule - goto errorExit - } - } - p.SetState(42) - p.GetErrorHandler().Sync(p) - if p.HasError() { - goto errorExit - } - _la = p.GetTokenStream().LA(1) - - if _la == MatchParserSTRING { - { - p.SetState(41) - p.Value() - } - - } - - p.SetState(48) - p.GetErrorHandler().Sync(p) - if p.HasError() { - goto errorExit - } - _la = p.GetTokenStream().LA(1) - } - -errorExit: - if p.HasError() { - v := p.GetError() - localctx.SetException(v) - p.GetErrorHandler().ReportError(p, v) - p.GetErrorHandler().Recover(p, v) - p.SetError(nil) - } - p.ExitRule() - return localctx - goto errorExit // Trick to prevent compiler error if the label is not used -} - -// IValueContext is an interface to support dynamic dispatch. -type IValueContext interface { - antlr.ParserRuleContext - - // GetParser returns the parser. - GetParser() antlr.Parser - - // Getter signatures - STRING() antlr.TerminalNode - - // IsValueContext differentiates from other interfaces. - IsValueContext() -} - -type ValueContext struct { - antlr.BaseParserRuleContext - parser antlr.Parser -} - -func NewEmptyValueContext() *ValueContext { - var p = new(ValueContext) - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) - p.RuleIndex = MatchParserRULE_value - return p -} - -func InitEmptyValueContext(p *ValueContext) { - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) - p.RuleIndex = MatchParserRULE_value -} - -func (*ValueContext) IsValueContext() {} - -func NewValueContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *ValueContext { - var p = new(ValueContext) - - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) - - p.parser = parser - p.RuleIndex = MatchParserRULE_value - - return p -} - -func (s *ValueContext) GetParser() antlr.Parser { return s.parser } - -func (s *ValueContext) STRING() antlr.TerminalNode { - return s.GetToken(MatchParserSTRING, 0) -} - -func (s *ValueContext) GetRuleContext() antlr.RuleContext { - return s -} - -func (s *ValueContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { - return antlr.TreesStringTree(s, ruleNames, recog) -} - -func (s *ValueContext) EnterRule(listener antlr.ParseTreeListener) { - if listenerT, ok := listener.(MatchListener); ok { - listenerT.EnterValue(s) - } -} - -func (s *ValueContext) ExitRule(listener antlr.ParseTreeListener) { - if listenerT, ok := listener.(MatchListener); ok { - listenerT.ExitValue(s) - } -} - -func (p *MatchParser) Value() (localctx IValueContext) { - localctx = NewValueContext(p, p.GetParserRuleContext(), p.GetState()) - p.EnterRule(localctx, 10, MatchParserRULE_value) - p.EnterOuterAlt(localctx, 1) - { - p.SetState(49) - p.Match(MatchParserSTRING) - if p.HasError() { - // Recognition error - abort rule - goto errorExit - } - } - -errorExit: - if p.HasError() { - v := p.GetError() - localctx.SetException(v) - p.GetErrorHandler().ReportError(p, v) - p.GetErrorHandler().Recover(p, v) - p.SetError(nil) - } - p.ExitRule() - return localctx - goto errorExit // Trick to prevent compiler error if the label is not used -} diff --git a/handlers/sshd_config/parser/handlers/sshd_config/Config.interp b/handlers/sshd_config/parser/handlers/sshd_config/Config.interp deleted file mode 100644 index e02ab96..0000000 --- a/handlers/sshd_config/parser/handlers/sshd_config/Config.interp +++ /dev/null @@ -1,28 +0,0 @@ -token literal names: -null -'#' -null -null -null -null - -token symbolic names: -null -HASH -WHITESPACE -STRING -NEWLINE -QUOTED_STRING - -rule names: -lineStatement -entry -separator -key -value -leadingComment -string - - -atn: -[4, 1, 5, 71, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 2, 5, 7, 5, 2, 6, 7, 6, 1, 0, 1, 0, 1, 0, 3, 0, 18, 8, 0, 3, 0, 20, 8, 0, 1, 0, 1, 0, 1, 1, 3, 1, 25, 8, 1, 1, 1, 3, 1, 28, 8, 1, 1, 1, 3, 1, 31, 8, 1, 1, 1, 3, 1, 34, 8, 1, 1, 1, 3, 1, 37, 8, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, 1, 4, 1, 4, 5, 4, 46, 8, 4, 10, 4, 12, 4, 49, 9, 4, 1, 4, 3, 4, 52, 8, 4, 1, 4, 3, 4, 55, 8, 4, 1, 5, 1, 5, 3, 5, 59, 8, 5, 1, 5, 1, 5, 3, 5, 63, 8, 5, 4, 5, 65, 8, 5, 11, 5, 12, 5, 66, 1, 6, 1, 6, 1, 6, 0, 0, 7, 0, 2, 4, 6, 8, 10, 12, 0, 1, 2, 0, 3, 3, 5, 5, 77, 0, 19, 1, 0, 0, 0, 2, 24, 1, 0, 0, 0, 4, 38, 1, 0, 0, 0, 6, 40, 1, 0, 0, 0, 8, 47, 1, 0, 0, 0, 10, 56, 1, 0, 0, 0, 12, 68, 1, 0, 0, 0, 14, 20, 3, 2, 1, 0, 15, 20, 3, 10, 5, 0, 16, 18, 5, 2, 0, 0, 17, 16, 1, 0, 0, 0, 17, 18, 1, 0, 0, 0, 18, 20, 1, 0, 0, 0, 19, 14, 1, 0, 0, 0, 19, 15, 1, 0, 0, 0, 19, 17, 1, 0, 0, 0, 20, 21, 1, 0, 0, 0, 21, 22, 5, 0, 0, 1, 22, 1, 1, 0, 0, 0, 23, 25, 5, 2, 0, 0, 24, 23, 1, 0, 0, 0, 24, 25, 1, 0, 0, 0, 25, 27, 1, 0, 0, 0, 26, 28, 3, 6, 3, 0, 27, 26, 1, 0, 0, 0, 27, 28, 1, 0, 0, 0, 28, 30, 1, 0, 0, 0, 29, 31, 3, 4, 2, 0, 30, 29, 1, 0, 0, 0, 30, 31, 1, 0, 0, 0, 31, 33, 1, 0, 0, 0, 32, 34, 3, 8, 4, 0, 33, 32, 1, 0, 0, 0, 33, 34, 1, 0, 0, 0, 34, 36, 1, 0, 0, 0, 35, 37, 3, 10, 5, 0, 36, 35, 1, 0, 0, 0, 36, 37, 1, 0, 0, 0, 37, 3, 1, 0, 0, 0, 38, 39, 5, 2, 0, 0, 39, 5, 1, 0, 0, 0, 40, 41, 3, 12, 6, 0, 41, 7, 1, 0, 0, 0, 42, 43, 3, 12, 6, 0, 43, 44, 5, 2, 0, 0, 44, 46, 1, 0, 0, 0, 45, 42, 1, 0, 0, 0, 46, 49, 1, 0, 0, 0, 47, 45, 1, 0, 0, 0, 47, 48, 1, 0, 0, 0, 48, 51, 1, 0, 0, 0, 49, 47, 1, 0, 0, 0, 50, 52, 3, 12, 6, 0, 51, 50, 1, 0, 0, 0, 51, 52, 1, 0, 0, 0, 52, 54, 1, 0, 0, 0, 53, 55, 5, 2, 0, 0, 54, 53, 1, 0, 0, 0, 54, 55, 1, 0, 0, 0, 55, 9, 1, 0, 0, 0, 56, 58, 5, 1, 0, 0, 57, 59, 5, 2, 0, 0, 58, 57, 1, 0, 0, 0, 58, 59, 1, 0, 0, 0, 59, 64, 1, 0, 0, 0, 60, 62, 3, 12, 6, 0, 61, 63, 5, 2, 0, 0, 62, 61, 1, 0, 0, 0, 62, 63, 1, 0, 0, 0, 63, 65, 1, 0, 0, 0, 64, 60, 1, 0, 0, 0, 65, 66, 1, 0, 0, 0, 66, 64, 1, 0, 0, 0, 66, 67, 1, 0, 0, 0, 67, 11, 1, 0, 0, 0, 68, 69, 7, 0, 0, 0, 69, 13, 1, 0, 0, 0, 13, 17, 19, 24, 27, 30, 33, 36, 47, 51, 54, 58, 62, 66] \ No newline at end of file diff --git a/handlers/sshd_config/parser/handlers/sshd_config/Config.tokens b/handlers/sshd_config/parser/handlers/sshd_config/Config.tokens deleted file mode 100644 index fa8c415..0000000 --- a/handlers/sshd_config/parser/handlers/sshd_config/Config.tokens +++ /dev/null @@ -1,6 +0,0 @@ -HASH=1 -WHITESPACE=2 -STRING=3 -NEWLINE=4 -QUOTED_STRING=5 -'#'=1 diff --git a/handlers/sshd_config/parser/handlers/sshd_config/ConfigLexer.interp b/handlers/sshd_config/parser/handlers/sshd_config/ConfigLexer.interp deleted file mode 100644 index c093cfb..0000000 --- a/handlers/sshd_config/parser/handlers/sshd_config/ConfigLexer.interp +++ /dev/null @@ -1,32 +0,0 @@ -token literal names: -null -'#' -null -null -null -null - -token symbolic names: -null -HASH -WHITESPACE -STRING -NEWLINE -QUOTED_STRING - -rule names: -HASH -WHITESPACE -STRING -NEWLINE -QUOTED_STRING - -channel names: -DEFAULT_TOKEN_CHANNEL -HIDDEN - -mode names: -DEFAULT_MODE - -atn: -[4, 0, 5, 46, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 1, 0, 1, 0, 1, 1, 4, 1, 15, 8, 1, 11, 1, 12, 1, 16, 1, 2, 4, 2, 20, 8, 2, 11, 2, 12, 2, 21, 1, 3, 3, 3, 25, 8, 3, 1, 3, 1, 3, 1, 4, 1, 4, 3, 4, 31, 8, 4, 1, 4, 1, 4, 1, 4, 5, 4, 36, 8, 4, 10, 4, 12, 4, 39, 9, 4, 1, 4, 3, 4, 42, 8, 4, 1, 4, 3, 4, 45, 8, 4, 0, 0, 5, 1, 1, 3, 2, 5, 3, 7, 4, 9, 5, 1, 0, 2, 2, 0, 9, 9, 32, 32, 4, 0, 9, 10, 13, 13, 32, 32, 34, 35, 52, 0, 1, 1, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, 5, 1, 0, 0, 0, 0, 7, 1, 0, 0, 0, 0, 9, 1, 0, 0, 0, 1, 11, 1, 0, 0, 0, 3, 14, 1, 0, 0, 0, 5, 19, 1, 0, 0, 0, 7, 24, 1, 0, 0, 0, 9, 28, 1, 0, 0, 0, 11, 12, 5, 35, 0, 0, 12, 2, 1, 0, 0, 0, 13, 15, 7, 0, 0, 0, 14, 13, 1, 0, 0, 0, 15, 16, 1, 0, 0, 0, 16, 14, 1, 0, 0, 0, 16, 17, 1, 0, 0, 0, 17, 4, 1, 0, 0, 0, 18, 20, 8, 1, 0, 0, 19, 18, 1, 0, 0, 0, 20, 21, 1, 0, 0, 0, 21, 19, 1, 0, 0, 0, 21, 22, 1, 0, 0, 0, 22, 6, 1, 0, 0, 0, 23, 25, 5, 13, 0, 0, 24, 23, 1, 0, 0, 0, 24, 25, 1, 0, 0, 0, 25, 26, 1, 0, 0, 0, 26, 27, 5, 10, 0, 0, 27, 8, 1, 0, 0, 0, 28, 30, 5, 34, 0, 0, 29, 31, 3, 3, 1, 0, 30, 29, 1, 0, 0, 0, 30, 31, 1, 0, 0, 0, 31, 37, 1, 0, 0, 0, 32, 33, 3, 5, 2, 0, 33, 34, 3, 3, 1, 0, 34, 36, 1, 0, 0, 0, 35, 32, 1, 0, 0, 0, 36, 39, 1, 0, 0, 0, 37, 35, 1, 0, 0, 0, 37, 38, 1, 0, 0, 0, 38, 41, 1, 0, 0, 0, 39, 37, 1, 0, 0, 0, 40, 42, 3, 5, 2, 0, 41, 40, 1, 0, 0, 0, 41, 42, 1, 0, 0, 0, 42, 44, 1, 0, 0, 0, 43, 45, 5, 34, 0, 0, 44, 43, 1, 0, 0, 0, 44, 45, 1, 0, 0, 0, 45, 10, 1, 0, 0, 0, 8, 0, 16, 21, 24, 30, 37, 41, 44, 0] \ No newline at end of file diff --git a/handlers/sshd_config/parser/handlers/sshd_config/ConfigLexer.tokens b/handlers/sshd_config/parser/handlers/sshd_config/ConfigLexer.tokens deleted file mode 100644 index fa8c415..0000000 --- a/handlers/sshd_config/parser/handlers/sshd_config/ConfigLexer.tokens +++ /dev/null @@ -1,6 +0,0 @@ -HASH=1 -WHITESPACE=2 -STRING=3 -NEWLINE=4 -QUOTED_STRING=5 -'#'=1 diff --git a/handlers/sshd_config/parser/handlers/sshd_config/config_base_listener.go b/handlers/sshd_config/parser/handlers/sshd_config/config_base_listener.go deleted file mode 100644 index 00727a5..0000000 --- a/handlers/sshd_config/parser/handlers/sshd_config/config_base_listener.go +++ /dev/null @@ -1,64 +0,0 @@ -// Code generated from handlers/sshd_config/Config.g4 by ANTLR 4.13.0. DO NOT EDIT. - -package parser // Config - -import "github.com/antlr4-go/antlr/v4" - -// BaseConfigListener is a complete listener for a parse tree produced by ConfigParser. -type BaseConfigListener struct{} - -var _ ConfigListener = &BaseConfigListener{} - -// VisitTerminal is called when a terminal node is visited. -func (s *BaseConfigListener) VisitTerminal(node antlr.TerminalNode) {} - -// VisitErrorNode is called when an error node is visited. -func (s *BaseConfigListener) VisitErrorNode(node antlr.ErrorNode) {} - -// EnterEveryRule is called when any rule is entered. -func (s *BaseConfigListener) EnterEveryRule(ctx antlr.ParserRuleContext) {} - -// ExitEveryRule is called when any rule is exited. -func (s *BaseConfigListener) ExitEveryRule(ctx antlr.ParserRuleContext) {} - -// EnterLineStatement is called when production lineStatement is entered. -func (s *BaseConfigListener) EnterLineStatement(ctx *LineStatementContext) {} - -// ExitLineStatement is called when production lineStatement is exited. -func (s *BaseConfigListener) ExitLineStatement(ctx *LineStatementContext) {} - -// EnterEntry is called when production entry is entered. -func (s *BaseConfigListener) EnterEntry(ctx *EntryContext) {} - -// ExitEntry is called when production entry is exited. -func (s *BaseConfigListener) ExitEntry(ctx *EntryContext) {} - -// EnterSeparator is called when production separator is entered. -func (s *BaseConfigListener) EnterSeparator(ctx *SeparatorContext) {} - -// ExitSeparator is called when production separator is exited. -func (s *BaseConfigListener) ExitSeparator(ctx *SeparatorContext) {} - -// EnterKey is called when production key is entered. -func (s *BaseConfigListener) EnterKey(ctx *KeyContext) {} - -// ExitKey is called when production key is exited. -func (s *BaseConfigListener) ExitKey(ctx *KeyContext) {} - -// EnterValue is called when production value is entered. -func (s *BaseConfigListener) EnterValue(ctx *ValueContext) {} - -// ExitValue is called when production value is exited. -func (s *BaseConfigListener) ExitValue(ctx *ValueContext) {} - -// EnterLeadingComment is called when production leadingComment is entered. -func (s *BaseConfigListener) EnterLeadingComment(ctx *LeadingCommentContext) {} - -// ExitLeadingComment is called when production leadingComment is exited. -func (s *BaseConfigListener) ExitLeadingComment(ctx *LeadingCommentContext) {} - -// EnterString is called when production string is entered. -func (s *BaseConfigListener) EnterString(ctx *StringContext) {} - -// ExitString is called when production string is exited. -func (s *BaseConfigListener) ExitString(ctx *StringContext) {} diff --git a/handlers/sshd_config/parser/handlers/sshd_config/config_lexer.go b/handlers/sshd_config/parser/handlers/sshd_config/config_lexer.go deleted file mode 100644 index 2852942..0000000 --- a/handlers/sshd_config/parser/handlers/sshd_config/config_lexer.go +++ /dev/null @@ -1,122 +0,0 @@ -// Code generated from handlers/sshd_config/Config.g4 by ANTLR 4.13.0. DO NOT EDIT. - -package parser - -import ( - "fmt" - "github.com/antlr4-go/antlr/v4" - "sync" - "unicode" -) - -// Suppress unused import error -var _ = fmt.Printf -var _ = sync.Once{} -var _ = unicode.IsLetter - -type ConfigLexer struct { - *antlr.BaseLexer - channelNames []string - modeNames []string - // TODO: EOF string -} - -var ConfigLexerLexerStaticData struct { - once sync.Once - serializedATN []int32 - ChannelNames []string - ModeNames []string - LiteralNames []string - SymbolicNames []string - RuleNames []string - PredictionContextCache *antlr.PredictionContextCache - atn *antlr.ATN - decisionToDFA []*antlr.DFA -} - -func configlexerLexerInit() { - staticData := &ConfigLexerLexerStaticData - staticData.ChannelNames = []string{ - "DEFAULT_TOKEN_CHANNEL", "HIDDEN", - } - staticData.ModeNames = []string{ - "DEFAULT_MODE", - } - staticData.LiteralNames = []string{ - "", "'#'", - } - staticData.SymbolicNames = []string{ - "", "HASH", "WHITESPACE", "STRING", "NEWLINE", "QUOTED_STRING", - } - staticData.RuleNames = []string{ - "HASH", "WHITESPACE", "STRING", "NEWLINE", "QUOTED_STRING", - } - staticData.PredictionContextCache = antlr.NewPredictionContextCache() - staticData.serializedATN = []int32{ - 4, 0, 5, 46, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, - 4, 7, 4, 1, 0, 1, 0, 1, 1, 4, 1, 15, 8, 1, 11, 1, 12, 1, 16, 1, 2, 4, 2, - 20, 8, 2, 11, 2, 12, 2, 21, 1, 3, 3, 3, 25, 8, 3, 1, 3, 1, 3, 1, 4, 1, - 4, 3, 4, 31, 8, 4, 1, 4, 1, 4, 1, 4, 5, 4, 36, 8, 4, 10, 4, 12, 4, 39, - 9, 4, 1, 4, 3, 4, 42, 8, 4, 1, 4, 3, 4, 45, 8, 4, 0, 0, 5, 1, 1, 3, 2, - 5, 3, 7, 4, 9, 5, 1, 0, 2, 2, 0, 9, 9, 32, 32, 4, 0, 9, 10, 13, 13, 32, - 32, 34, 35, 52, 0, 1, 1, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, 5, 1, 0, 0, 0, 0, - 7, 1, 0, 0, 0, 0, 9, 1, 0, 0, 0, 1, 11, 1, 0, 0, 0, 3, 14, 1, 0, 0, 0, - 5, 19, 1, 0, 0, 0, 7, 24, 1, 0, 0, 0, 9, 28, 1, 0, 0, 0, 11, 12, 5, 35, - 0, 0, 12, 2, 1, 0, 0, 0, 13, 15, 7, 0, 0, 0, 14, 13, 1, 0, 0, 0, 15, 16, - 1, 0, 0, 0, 16, 14, 1, 0, 0, 0, 16, 17, 1, 0, 0, 0, 17, 4, 1, 0, 0, 0, - 18, 20, 8, 1, 0, 0, 19, 18, 1, 0, 0, 0, 20, 21, 1, 0, 0, 0, 21, 19, 1, - 0, 0, 0, 21, 22, 1, 0, 0, 0, 22, 6, 1, 0, 0, 0, 23, 25, 5, 13, 0, 0, 24, - 23, 1, 0, 0, 0, 24, 25, 1, 0, 0, 0, 25, 26, 1, 0, 0, 0, 26, 27, 5, 10, - 0, 0, 27, 8, 1, 0, 0, 0, 28, 30, 5, 34, 0, 0, 29, 31, 3, 3, 1, 0, 30, 29, - 1, 0, 0, 0, 30, 31, 1, 0, 0, 0, 31, 37, 1, 0, 0, 0, 32, 33, 3, 5, 2, 0, - 33, 34, 3, 3, 1, 0, 34, 36, 1, 0, 0, 0, 35, 32, 1, 0, 0, 0, 36, 39, 1, - 0, 0, 0, 37, 35, 1, 0, 0, 0, 37, 38, 1, 0, 0, 0, 38, 41, 1, 0, 0, 0, 39, - 37, 1, 0, 0, 0, 40, 42, 3, 5, 2, 0, 41, 40, 1, 0, 0, 0, 41, 42, 1, 0, 0, - 0, 42, 44, 1, 0, 0, 0, 43, 45, 5, 34, 0, 0, 44, 43, 1, 0, 0, 0, 44, 45, - 1, 0, 0, 0, 45, 10, 1, 0, 0, 0, 8, 0, 16, 21, 24, 30, 37, 41, 44, 0, - } - deserializer := antlr.NewATNDeserializer(nil) - staticData.atn = deserializer.Deserialize(staticData.serializedATN) - atn := staticData.atn - staticData.decisionToDFA = make([]*antlr.DFA, len(atn.DecisionToState)) - decisionToDFA := staticData.decisionToDFA - for index, state := range atn.DecisionToState { - decisionToDFA[index] = antlr.NewDFA(state, index) - } -} - -// ConfigLexerInit initializes any static state used to implement ConfigLexer. By default the -// static state used to implement the lexer is lazily initialized during the first call to -// NewConfigLexer(). You can call this function if you wish to initialize the static state ahead -// of time. -func ConfigLexerInit() { - staticData := &ConfigLexerLexerStaticData - staticData.once.Do(configlexerLexerInit) -} - -// NewConfigLexer produces a new lexer instance for the optional input antlr.CharStream. -func NewConfigLexer(input antlr.CharStream) *ConfigLexer { - ConfigLexerInit() - l := new(ConfigLexer) - l.BaseLexer = antlr.NewBaseLexer(input) - staticData := &ConfigLexerLexerStaticData - l.Interpreter = antlr.NewLexerATNSimulator(l, staticData.atn, staticData.decisionToDFA, staticData.PredictionContextCache) - l.channelNames = staticData.ChannelNames - l.modeNames = staticData.ModeNames - l.RuleNames = staticData.RuleNames - l.LiteralNames = staticData.LiteralNames - l.SymbolicNames = staticData.SymbolicNames - l.GrammarFileName = "Config.g4" - // TODO: l.EOF = antlr.TokenEOF - - return l -} - -// ConfigLexer tokens. -const ( - ConfigLexerHASH = 1 - ConfigLexerWHITESPACE = 2 - ConfigLexerSTRING = 3 - ConfigLexerNEWLINE = 4 - ConfigLexerQUOTED_STRING = 5 -) diff --git a/handlers/sshd_config/parser/handlers/sshd_config/config_listener.go b/handlers/sshd_config/parser/handlers/sshd_config/config_listener.go deleted file mode 100644 index b6e827b..0000000 --- a/handlers/sshd_config/parser/handlers/sshd_config/config_listener.go +++ /dev/null @@ -1,52 +0,0 @@ -// Code generated from handlers/sshd_config/Config.g4 by ANTLR 4.13.0. DO NOT EDIT. - -package parser // Config - -import "github.com/antlr4-go/antlr/v4" - -// ConfigListener is a complete listener for a parse tree produced by ConfigParser. -type ConfigListener interface { - antlr.ParseTreeListener - - // EnterLineStatement is called when entering the lineStatement production. - EnterLineStatement(c *LineStatementContext) - - // EnterEntry is called when entering the entry production. - EnterEntry(c *EntryContext) - - // EnterSeparator is called when entering the separator production. - EnterSeparator(c *SeparatorContext) - - // EnterKey is called when entering the key production. - EnterKey(c *KeyContext) - - // EnterValue is called when entering the value production. - EnterValue(c *ValueContext) - - // EnterLeadingComment is called when entering the leadingComment production. - EnterLeadingComment(c *LeadingCommentContext) - - // EnterString is called when entering the string production. - EnterString(c *StringContext) - - // ExitLineStatement is called when exiting the lineStatement production. - ExitLineStatement(c *LineStatementContext) - - // ExitEntry is called when exiting the entry production. - ExitEntry(c *EntryContext) - - // ExitSeparator is called when exiting the separator production. - ExitSeparator(c *SeparatorContext) - - // ExitKey is called when exiting the key production. - ExitKey(c *KeyContext) - - // ExitValue is called when exiting the value production. - ExitValue(c *ValueContext) - - // ExitLeadingComment is called when exiting the leadingComment production. - ExitLeadingComment(c *LeadingCommentContext) - - // ExitString is called when exiting the string production. - ExitString(c *StringContext) -} diff --git a/handlers/sshd_config/parser/handlers/sshd_config/config_parser.go b/handlers/sshd_config/parser/handlers/sshd_config/config_parser.go deleted file mode 100644 index 50f9bab..0000000 --- a/handlers/sshd_config/parser/handlers/sshd_config/config_parser.go +++ /dev/null @@ -1,1254 +0,0 @@ -// Code generated from handlers/sshd_config/Config.g4 by ANTLR 4.13.0. DO NOT EDIT. - -package parser // Config - -import ( - "fmt" - "strconv" - "sync" - - "github.com/antlr4-go/antlr/v4" -) - -// Suppress unused import errors -var _ = fmt.Printf -var _ = strconv.Itoa -var _ = sync.Once{} - -type ConfigParser struct { - *antlr.BaseParser -} - -var ConfigParserStaticData struct { - once sync.Once - serializedATN []int32 - LiteralNames []string - SymbolicNames []string - RuleNames []string - PredictionContextCache *antlr.PredictionContextCache - atn *antlr.ATN - decisionToDFA []*antlr.DFA -} - -func configParserInit() { - staticData := &ConfigParserStaticData - staticData.LiteralNames = []string{ - "", "'#'", - } - staticData.SymbolicNames = []string{ - "", "HASH", "WHITESPACE", "STRING", "NEWLINE", "QUOTED_STRING", - } - staticData.RuleNames = []string{ - "lineStatement", "entry", "separator", "key", "value", "leadingComment", - "string", - } - staticData.PredictionContextCache = antlr.NewPredictionContextCache() - staticData.serializedATN = []int32{ - 4, 1, 5, 71, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, - 2, 5, 7, 5, 2, 6, 7, 6, 1, 0, 1, 0, 1, 0, 3, 0, 18, 8, 0, 3, 0, 20, 8, - 0, 1, 0, 1, 0, 1, 1, 3, 1, 25, 8, 1, 1, 1, 3, 1, 28, 8, 1, 1, 1, 3, 1, - 31, 8, 1, 1, 1, 3, 1, 34, 8, 1, 1, 1, 3, 1, 37, 8, 1, 1, 2, 1, 2, 1, 3, - 1, 3, 1, 4, 1, 4, 1, 4, 5, 4, 46, 8, 4, 10, 4, 12, 4, 49, 9, 4, 1, 4, 3, - 4, 52, 8, 4, 1, 4, 3, 4, 55, 8, 4, 1, 5, 1, 5, 3, 5, 59, 8, 5, 1, 5, 1, - 5, 3, 5, 63, 8, 5, 4, 5, 65, 8, 5, 11, 5, 12, 5, 66, 1, 6, 1, 6, 1, 6, - 0, 0, 7, 0, 2, 4, 6, 8, 10, 12, 0, 1, 2, 0, 3, 3, 5, 5, 77, 0, 19, 1, 0, - 0, 0, 2, 24, 1, 0, 0, 0, 4, 38, 1, 0, 0, 0, 6, 40, 1, 0, 0, 0, 8, 47, 1, - 0, 0, 0, 10, 56, 1, 0, 0, 0, 12, 68, 1, 0, 0, 0, 14, 20, 3, 2, 1, 0, 15, - 20, 3, 10, 5, 0, 16, 18, 5, 2, 0, 0, 17, 16, 1, 0, 0, 0, 17, 18, 1, 0, - 0, 0, 18, 20, 1, 0, 0, 0, 19, 14, 1, 0, 0, 0, 19, 15, 1, 0, 0, 0, 19, 17, - 1, 0, 0, 0, 20, 21, 1, 0, 0, 0, 21, 22, 5, 0, 0, 1, 22, 1, 1, 0, 0, 0, - 23, 25, 5, 2, 0, 0, 24, 23, 1, 0, 0, 0, 24, 25, 1, 0, 0, 0, 25, 27, 1, - 0, 0, 0, 26, 28, 3, 6, 3, 0, 27, 26, 1, 0, 0, 0, 27, 28, 1, 0, 0, 0, 28, - 30, 1, 0, 0, 0, 29, 31, 3, 4, 2, 0, 30, 29, 1, 0, 0, 0, 30, 31, 1, 0, 0, - 0, 31, 33, 1, 0, 0, 0, 32, 34, 3, 8, 4, 0, 33, 32, 1, 0, 0, 0, 33, 34, - 1, 0, 0, 0, 34, 36, 1, 0, 0, 0, 35, 37, 3, 10, 5, 0, 36, 35, 1, 0, 0, 0, - 36, 37, 1, 0, 0, 0, 37, 3, 1, 0, 0, 0, 38, 39, 5, 2, 0, 0, 39, 5, 1, 0, - 0, 0, 40, 41, 3, 12, 6, 0, 41, 7, 1, 0, 0, 0, 42, 43, 3, 12, 6, 0, 43, - 44, 5, 2, 0, 0, 44, 46, 1, 0, 0, 0, 45, 42, 1, 0, 0, 0, 46, 49, 1, 0, 0, - 0, 47, 45, 1, 0, 0, 0, 47, 48, 1, 0, 0, 0, 48, 51, 1, 0, 0, 0, 49, 47, - 1, 0, 0, 0, 50, 52, 3, 12, 6, 0, 51, 50, 1, 0, 0, 0, 51, 52, 1, 0, 0, 0, - 52, 54, 1, 0, 0, 0, 53, 55, 5, 2, 0, 0, 54, 53, 1, 0, 0, 0, 54, 55, 1, - 0, 0, 0, 55, 9, 1, 0, 0, 0, 56, 58, 5, 1, 0, 0, 57, 59, 5, 2, 0, 0, 58, - 57, 1, 0, 0, 0, 58, 59, 1, 0, 0, 0, 59, 64, 1, 0, 0, 0, 60, 62, 3, 12, - 6, 0, 61, 63, 5, 2, 0, 0, 62, 61, 1, 0, 0, 0, 62, 63, 1, 0, 0, 0, 63, 65, - 1, 0, 0, 0, 64, 60, 1, 0, 0, 0, 65, 66, 1, 0, 0, 0, 66, 64, 1, 0, 0, 0, - 66, 67, 1, 0, 0, 0, 67, 11, 1, 0, 0, 0, 68, 69, 7, 0, 0, 0, 69, 13, 1, - 0, 0, 0, 13, 17, 19, 24, 27, 30, 33, 36, 47, 51, 54, 58, 62, 66, - } - deserializer := antlr.NewATNDeserializer(nil) - staticData.atn = deserializer.Deserialize(staticData.serializedATN) - atn := staticData.atn - staticData.decisionToDFA = make([]*antlr.DFA, len(atn.DecisionToState)) - decisionToDFA := staticData.decisionToDFA - for index, state := range atn.DecisionToState { - decisionToDFA[index] = antlr.NewDFA(state, index) - } -} - -// ConfigParserInit initializes any static state used to implement ConfigParser. By default the -// static state used to implement the parser is lazily initialized during the first call to -// NewConfigParser(). You can call this function if you wish to initialize the static state ahead -// of time. -func ConfigParserInit() { - staticData := &ConfigParserStaticData - staticData.once.Do(configParserInit) -} - -// NewConfigParser produces a new parser instance for the optional input antlr.TokenStream. -func NewConfigParser(input antlr.TokenStream) *ConfigParser { - ConfigParserInit() - this := new(ConfigParser) - this.BaseParser = antlr.NewBaseParser(input) - staticData := &ConfigParserStaticData - this.Interpreter = antlr.NewParserATNSimulator(this, staticData.atn, staticData.decisionToDFA, staticData.PredictionContextCache) - this.RuleNames = staticData.RuleNames - this.LiteralNames = staticData.LiteralNames - this.SymbolicNames = staticData.SymbolicNames - this.GrammarFileName = "Config.g4" - - return this -} - -// ConfigParser tokens. -const ( - ConfigParserEOF = antlr.TokenEOF - ConfigParserHASH = 1 - ConfigParserWHITESPACE = 2 - ConfigParserSTRING = 3 - ConfigParserNEWLINE = 4 - ConfigParserQUOTED_STRING = 5 -) - -// ConfigParser rules. -const ( - ConfigParserRULE_lineStatement = 0 - ConfigParserRULE_entry = 1 - ConfigParserRULE_separator = 2 - ConfigParserRULE_key = 3 - ConfigParserRULE_value = 4 - ConfigParserRULE_leadingComment = 5 - ConfigParserRULE_string = 6 -) - -// ILineStatementContext is an interface to support dynamic dispatch. -type ILineStatementContext interface { - antlr.ParserRuleContext - - // GetParser returns the parser. - GetParser() antlr.Parser - - // Getter signatures - EOF() antlr.TerminalNode - Entry() IEntryContext - LeadingComment() ILeadingCommentContext - WHITESPACE() antlr.TerminalNode - - // IsLineStatementContext differentiates from other interfaces. - IsLineStatementContext() -} - -type LineStatementContext struct { - antlr.BaseParserRuleContext - parser antlr.Parser -} - -func NewEmptyLineStatementContext() *LineStatementContext { - var p = new(LineStatementContext) - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) - p.RuleIndex = ConfigParserRULE_lineStatement - return p -} - -func InitEmptyLineStatementContext(p *LineStatementContext) { - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) - p.RuleIndex = ConfigParserRULE_lineStatement -} - -func (*LineStatementContext) IsLineStatementContext() {} - -func NewLineStatementContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *LineStatementContext { - var p = new(LineStatementContext) - - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) - - p.parser = parser - p.RuleIndex = ConfigParserRULE_lineStatement - - return p -} - -func (s *LineStatementContext) GetParser() antlr.Parser { return s.parser } - -func (s *LineStatementContext) EOF() antlr.TerminalNode { - return s.GetToken(ConfigParserEOF, 0) -} - -func (s *LineStatementContext) Entry() IEntryContext { - var t antlr.RuleContext - for _, ctx := range s.GetChildren() { - if _, ok := ctx.(IEntryContext); ok { - t = ctx.(antlr.RuleContext) - break - } - } - - if t == nil { - return nil - } - - return t.(IEntryContext) -} - -func (s *LineStatementContext) LeadingComment() ILeadingCommentContext { - var t antlr.RuleContext - for _, ctx := range s.GetChildren() { - if _, ok := ctx.(ILeadingCommentContext); ok { - t = ctx.(antlr.RuleContext) - break - } - } - - if t == nil { - return nil - } - - return t.(ILeadingCommentContext) -} - -func (s *LineStatementContext) WHITESPACE() antlr.TerminalNode { - return s.GetToken(ConfigParserWHITESPACE, 0) -} - -func (s *LineStatementContext) GetRuleContext() antlr.RuleContext { - return s -} - -func (s *LineStatementContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { - return antlr.TreesStringTree(s, ruleNames, recog) -} - -func (s *LineStatementContext) EnterRule(listener antlr.ParseTreeListener) { - if listenerT, ok := listener.(ConfigListener); ok { - listenerT.EnterLineStatement(s) - } -} - -func (s *LineStatementContext) ExitRule(listener antlr.ParseTreeListener) { - if listenerT, ok := listener.(ConfigListener); ok { - listenerT.ExitLineStatement(s) - } -} - -func (p *ConfigParser) LineStatement() (localctx ILineStatementContext) { - localctx = NewLineStatementContext(p, p.GetParserRuleContext(), p.GetState()) - p.EnterRule(localctx, 0, ConfigParserRULE_lineStatement) - var _la int - - p.EnterOuterAlt(localctx, 1) - p.SetState(19) - p.GetErrorHandler().Sync(p) - if p.HasError() { - goto errorExit - } - - switch p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 1, p.GetParserRuleContext()) { - case 1: - { - p.SetState(14) - p.Entry() - } - - case 2: - { - p.SetState(15) - p.LeadingComment() - } - - case 3: - p.SetState(17) - p.GetErrorHandler().Sync(p) - if p.HasError() { - goto errorExit - } - _la = p.GetTokenStream().LA(1) - - if _la == ConfigParserWHITESPACE { - { - p.SetState(16) - p.Match(ConfigParserWHITESPACE) - if p.HasError() { - // Recognition error - abort rule - goto errorExit - } - } - - } - - case antlr.ATNInvalidAltNumber: - goto errorExit - } - { - p.SetState(21) - p.Match(ConfigParserEOF) - if p.HasError() { - // Recognition error - abort rule - goto errorExit - } - } - -errorExit: - if p.HasError() { - v := p.GetError() - localctx.SetException(v) - p.GetErrorHandler().ReportError(p, v) - p.GetErrorHandler().Recover(p, v) - p.SetError(nil) - } - p.ExitRule() - return localctx - goto errorExit // Trick to prevent compiler error if the label is not used -} - -// IEntryContext is an interface to support dynamic dispatch. -type IEntryContext interface { - antlr.ParserRuleContext - - // GetParser returns the parser. - GetParser() antlr.Parser - - // Getter signatures - WHITESPACE() antlr.TerminalNode - Key() IKeyContext - Separator() ISeparatorContext - Value() IValueContext - LeadingComment() ILeadingCommentContext - - // IsEntryContext differentiates from other interfaces. - IsEntryContext() -} - -type EntryContext struct { - antlr.BaseParserRuleContext - parser antlr.Parser -} - -func NewEmptyEntryContext() *EntryContext { - var p = new(EntryContext) - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) - p.RuleIndex = ConfigParserRULE_entry - return p -} - -func InitEmptyEntryContext(p *EntryContext) { - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) - p.RuleIndex = ConfigParserRULE_entry -} - -func (*EntryContext) IsEntryContext() {} - -func NewEntryContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *EntryContext { - var p = new(EntryContext) - - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) - - p.parser = parser - p.RuleIndex = ConfigParserRULE_entry - - return p -} - -func (s *EntryContext) GetParser() antlr.Parser { return s.parser } - -func (s *EntryContext) WHITESPACE() antlr.TerminalNode { - return s.GetToken(ConfigParserWHITESPACE, 0) -} - -func (s *EntryContext) Key() IKeyContext { - var t antlr.RuleContext - for _, ctx := range s.GetChildren() { - if _, ok := ctx.(IKeyContext); ok { - t = ctx.(antlr.RuleContext) - break - } - } - - if t == nil { - return nil - } - - return t.(IKeyContext) -} - -func (s *EntryContext) Separator() ISeparatorContext { - var t antlr.RuleContext - for _, ctx := range s.GetChildren() { - if _, ok := ctx.(ISeparatorContext); ok { - t = ctx.(antlr.RuleContext) - break - } - } - - if t == nil { - return nil - } - - return t.(ISeparatorContext) -} - -func (s *EntryContext) Value() IValueContext { - var t antlr.RuleContext - for _, ctx := range s.GetChildren() { - if _, ok := ctx.(IValueContext); ok { - t = ctx.(antlr.RuleContext) - break - } - } - - if t == nil { - return nil - } - - return t.(IValueContext) -} - -func (s *EntryContext) LeadingComment() ILeadingCommentContext { - var t antlr.RuleContext - for _, ctx := range s.GetChildren() { - if _, ok := ctx.(ILeadingCommentContext); ok { - t = ctx.(antlr.RuleContext) - break - } - } - - if t == nil { - return nil - } - - return t.(ILeadingCommentContext) -} - -func (s *EntryContext) GetRuleContext() antlr.RuleContext { - return s -} - -func (s *EntryContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { - return antlr.TreesStringTree(s, ruleNames, recog) -} - -func (s *EntryContext) EnterRule(listener antlr.ParseTreeListener) { - if listenerT, ok := listener.(ConfigListener); ok { - listenerT.EnterEntry(s) - } -} - -func (s *EntryContext) ExitRule(listener antlr.ParseTreeListener) { - if listenerT, ok := listener.(ConfigListener); ok { - listenerT.ExitEntry(s) - } -} - -func (p *ConfigParser) Entry() (localctx IEntryContext) { - localctx = NewEntryContext(p, p.GetParserRuleContext(), p.GetState()) - p.EnterRule(localctx, 2, ConfigParserRULE_entry) - var _la int - - p.EnterOuterAlt(localctx, 1) - p.SetState(24) - p.GetErrorHandler().Sync(p) - - if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 2, p.GetParserRuleContext()) == 1 { - { - p.SetState(23) - p.Match(ConfigParserWHITESPACE) - if p.HasError() { - // Recognition error - abort rule - goto errorExit - } - } - - } else if p.HasError() { // JIM - goto errorExit - } - p.SetState(27) - p.GetErrorHandler().Sync(p) - - if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 3, p.GetParserRuleContext()) == 1 { - { - p.SetState(26) - p.Key() - } - - } else if p.HasError() { // JIM - goto errorExit - } - p.SetState(30) - p.GetErrorHandler().Sync(p) - - if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 4, p.GetParserRuleContext()) == 1 { - { - p.SetState(29) - p.Separator() - } - - } else if p.HasError() { // JIM - goto errorExit - } - p.SetState(33) - p.GetErrorHandler().Sync(p) - - if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 5, p.GetParserRuleContext()) == 1 { - { - p.SetState(32) - p.Value() - } - - } else if p.HasError() { // JIM - goto errorExit - } - p.SetState(36) - p.GetErrorHandler().Sync(p) - if p.HasError() { - goto errorExit - } - _la = p.GetTokenStream().LA(1) - - if _la == ConfigParserHASH { - { - p.SetState(35) - p.LeadingComment() - } - - } - -errorExit: - if p.HasError() { - v := p.GetError() - localctx.SetException(v) - p.GetErrorHandler().ReportError(p, v) - p.GetErrorHandler().Recover(p, v) - p.SetError(nil) - } - p.ExitRule() - return localctx - goto errorExit // Trick to prevent compiler error if the label is not used -} - -// ISeparatorContext is an interface to support dynamic dispatch. -type ISeparatorContext interface { - antlr.ParserRuleContext - - // GetParser returns the parser. - GetParser() antlr.Parser - - // Getter signatures - WHITESPACE() antlr.TerminalNode - - // IsSeparatorContext differentiates from other interfaces. - IsSeparatorContext() -} - -type SeparatorContext struct { - antlr.BaseParserRuleContext - parser antlr.Parser -} - -func NewEmptySeparatorContext() *SeparatorContext { - var p = new(SeparatorContext) - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) - p.RuleIndex = ConfigParserRULE_separator - return p -} - -func InitEmptySeparatorContext(p *SeparatorContext) { - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) - p.RuleIndex = ConfigParserRULE_separator -} - -func (*SeparatorContext) IsSeparatorContext() {} - -func NewSeparatorContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *SeparatorContext { - var p = new(SeparatorContext) - - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) - - p.parser = parser - p.RuleIndex = ConfigParserRULE_separator - - return p -} - -func (s *SeparatorContext) GetParser() antlr.Parser { return s.parser } - -func (s *SeparatorContext) WHITESPACE() antlr.TerminalNode { - return s.GetToken(ConfigParserWHITESPACE, 0) -} - -func (s *SeparatorContext) GetRuleContext() antlr.RuleContext { - return s -} - -func (s *SeparatorContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { - return antlr.TreesStringTree(s, ruleNames, recog) -} - -func (s *SeparatorContext) EnterRule(listener antlr.ParseTreeListener) { - if listenerT, ok := listener.(ConfigListener); ok { - listenerT.EnterSeparator(s) - } -} - -func (s *SeparatorContext) ExitRule(listener antlr.ParseTreeListener) { - if listenerT, ok := listener.(ConfigListener); ok { - listenerT.ExitSeparator(s) - } -} - -func (p *ConfigParser) Separator() (localctx ISeparatorContext) { - localctx = NewSeparatorContext(p, p.GetParserRuleContext(), p.GetState()) - p.EnterRule(localctx, 4, ConfigParserRULE_separator) - p.EnterOuterAlt(localctx, 1) - { - p.SetState(38) - p.Match(ConfigParserWHITESPACE) - if p.HasError() { - // Recognition error - abort rule - goto errorExit - } - } - -errorExit: - if p.HasError() { - v := p.GetError() - localctx.SetException(v) - p.GetErrorHandler().ReportError(p, v) - p.GetErrorHandler().Recover(p, v) - p.SetError(nil) - } - p.ExitRule() - return localctx - goto errorExit // Trick to prevent compiler error if the label is not used -} - -// IKeyContext is an interface to support dynamic dispatch. -type IKeyContext interface { - antlr.ParserRuleContext - - // GetParser returns the parser. - GetParser() antlr.Parser - - // Getter signatures - String_() IStringContext - - // IsKeyContext differentiates from other interfaces. - IsKeyContext() -} - -type KeyContext struct { - antlr.BaseParserRuleContext - parser antlr.Parser -} - -func NewEmptyKeyContext() *KeyContext { - var p = new(KeyContext) - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) - p.RuleIndex = ConfigParserRULE_key - return p -} - -func InitEmptyKeyContext(p *KeyContext) { - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) - p.RuleIndex = ConfigParserRULE_key -} - -func (*KeyContext) IsKeyContext() {} - -func NewKeyContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *KeyContext { - var p = new(KeyContext) - - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) - - p.parser = parser - p.RuleIndex = ConfigParserRULE_key - - return p -} - -func (s *KeyContext) GetParser() antlr.Parser { return s.parser } - -func (s *KeyContext) String_() IStringContext { - var t antlr.RuleContext - for _, ctx := range s.GetChildren() { - if _, ok := ctx.(IStringContext); ok { - t = ctx.(antlr.RuleContext) - break - } - } - - if t == nil { - return nil - } - - return t.(IStringContext) -} - -func (s *KeyContext) GetRuleContext() antlr.RuleContext { - return s -} - -func (s *KeyContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { - return antlr.TreesStringTree(s, ruleNames, recog) -} - -func (s *KeyContext) EnterRule(listener antlr.ParseTreeListener) { - if listenerT, ok := listener.(ConfigListener); ok { - listenerT.EnterKey(s) - } -} - -func (s *KeyContext) ExitRule(listener antlr.ParseTreeListener) { - if listenerT, ok := listener.(ConfigListener); ok { - listenerT.ExitKey(s) - } -} - -func (p *ConfigParser) Key() (localctx IKeyContext) { - localctx = NewKeyContext(p, p.GetParserRuleContext(), p.GetState()) - p.EnterRule(localctx, 6, ConfigParserRULE_key) - p.EnterOuterAlt(localctx, 1) - { - p.SetState(40) - p.String_() - } - -errorExit: - if p.HasError() { - v := p.GetError() - localctx.SetException(v) - p.GetErrorHandler().ReportError(p, v) - p.GetErrorHandler().Recover(p, v) - p.SetError(nil) - } - p.ExitRule() - return localctx - goto errorExit // Trick to prevent compiler error if the label is not used -} - -// IValueContext is an interface to support dynamic dispatch. -type IValueContext interface { - antlr.ParserRuleContext - - // GetParser returns the parser. - GetParser() antlr.Parser - - // Getter signatures - AllString_() []IStringContext - String_(i int) IStringContext - AllWHITESPACE() []antlr.TerminalNode - WHITESPACE(i int) antlr.TerminalNode - - // IsValueContext differentiates from other interfaces. - IsValueContext() -} - -type ValueContext struct { - antlr.BaseParserRuleContext - parser antlr.Parser -} - -func NewEmptyValueContext() *ValueContext { - var p = new(ValueContext) - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) - p.RuleIndex = ConfigParserRULE_value - return p -} - -func InitEmptyValueContext(p *ValueContext) { - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) - p.RuleIndex = ConfigParserRULE_value -} - -func (*ValueContext) IsValueContext() {} - -func NewValueContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *ValueContext { - var p = new(ValueContext) - - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) - - p.parser = parser - p.RuleIndex = ConfigParserRULE_value - - return p -} - -func (s *ValueContext) GetParser() antlr.Parser { return s.parser } - -func (s *ValueContext) AllString_() []IStringContext { - children := s.GetChildren() - len := 0 - for _, ctx := range children { - if _, ok := ctx.(IStringContext); ok { - len++ - } - } - - tst := make([]IStringContext, len) - i := 0 - for _, ctx := range children { - if t, ok := ctx.(IStringContext); ok { - tst[i] = t.(IStringContext) - i++ - } - } - - return tst -} - -func (s *ValueContext) String_(i int) IStringContext { - var t antlr.RuleContext - j := 0 - for _, ctx := range s.GetChildren() { - if _, ok := ctx.(IStringContext); ok { - if j == i { - t = ctx.(antlr.RuleContext) - break - } - j++ - } - } - - if t == nil { - return nil - } - - return t.(IStringContext) -} - -func (s *ValueContext) AllWHITESPACE() []antlr.TerminalNode { - return s.GetTokens(ConfigParserWHITESPACE) -} - -func (s *ValueContext) WHITESPACE(i int) antlr.TerminalNode { - return s.GetToken(ConfigParserWHITESPACE, i) -} - -func (s *ValueContext) GetRuleContext() antlr.RuleContext { - return s -} - -func (s *ValueContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { - return antlr.TreesStringTree(s, ruleNames, recog) -} - -func (s *ValueContext) EnterRule(listener antlr.ParseTreeListener) { - if listenerT, ok := listener.(ConfigListener); ok { - listenerT.EnterValue(s) - } -} - -func (s *ValueContext) ExitRule(listener antlr.ParseTreeListener) { - if listenerT, ok := listener.(ConfigListener); ok { - listenerT.ExitValue(s) - } -} - -func (p *ConfigParser) Value() (localctx IValueContext) { - localctx = NewValueContext(p, p.GetParserRuleContext(), p.GetState()) - p.EnterRule(localctx, 8, ConfigParserRULE_value) - var _la int - - var _alt int - - p.EnterOuterAlt(localctx, 1) - p.SetState(47) - p.GetErrorHandler().Sync(p) - if p.HasError() { - goto errorExit - } - _alt = p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 7, p.GetParserRuleContext()) - if p.HasError() { - goto errorExit - } - for _alt != 2 && _alt != antlr.ATNInvalidAltNumber { - if _alt == 1 { - { - p.SetState(42) - p.String_() - } - { - p.SetState(43) - p.Match(ConfigParserWHITESPACE) - if p.HasError() { - // Recognition error - abort rule - goto errorExit - } - } - - } - p.SetState(49) - p.GetErrorHandler().Sync(p) - if p.HasError() { - goto errorExit - } - _alt = p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 7, p.GetParserRuleContext()) - if p.HasError() { - goto errorExit - } - } - p.SetState(51) - p.GetErrorHandler().Sync(p) - if p.HasError() { - goto errorExit - } - _la = p.GetTokenStream().LA(1) - - if _la == ConfigParserSTRING || _la == ConfigParserQUOTED_STRING { - { - p.SetState(50) - p.String_() - } - - } - p.SetState(54) - p.GetErrorHandler().Sync(p) - if p.HasError() { - goto errorExit - } - _la = p.GetTokenStream().LA(1) - - if _la == ConfigParserWHITESPACE { - { - p.SetState(53) - p.Match(ConfigParserWHITESPACE) - if p.HasError() { - // Recognition error - abort rule - goto errorExit - } - } - - } - -errorExit: - if p.HasError() { - v := p.GetError() - localctx.SetException(v) - p.GetErrorHandler().ReportError(p, v) - p.GetErrorHandler().Recover(p, v) - p.SetError(nil) - } - p.ExitRule() - return localctx - goto errorExit // Trick to prevent compiler error if the label is not used -} - -// ILeadingCommentContext is an interface to support dynamic dispatch. -type ILeadingCommentContext interface { - antlr.ParserRuleContext - - // GetParser returns the parser. - GetParser() antlr.Parser - - // Getter signatures - HASH() antlr.TerminalNode - AllWHITESPACE() []antlr.TerminalNode - WHITESPACE(i int) antlr.TerminalNode - AllString_() []IStringContext - String_(i int) IStringContext - - // IsLeadingCommentContext differentiates from other interfaces. - IsLeadingCommentContext() -} - -type LeadingCommentContext struct { - antlr.BaseParserRuleContext - parser antlr.Parser -} - -func NewEmptyLeadingCommentContext() *LeadingCommentContext { - var p = new(LeadingCommentContext) - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) - p.RuleIndex = ConfigParserRULE_leadingComment - return p -} - -func InitEmptyLeadingCommentContext(p *LeadingCommentContext) { - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) - p.RuleIndex = ConfigParserRULE_leadingComment -} - -func (*LeadingCommentContext) IsLeadingCommentContext() {} - -func NewLeadingCommentContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *LeadingCommentContext { - var p = new(LeadingCommentContext) - - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) - - p.parser = parser - p.RuleIndex = ConfigParserRULE_leadingComment - - return p -} - -func (s *LeadingCommentContext) GetParser() antlr.Parser { return s.parser } - -func (s *LeadingCommentContext) HASH() antlr.TerminalNode { - return s.GetToken(ConfigParserHASH, 0) -} - -func (s *LeadingCommentContext) AllWHITESPACE() []antlr.TerminalNode { - return s.GetTokens(ConfigParserWHITESPACE) -} - -func (s *LeadingCommentContext) WHITESPACE(i int) antlr.TerminalNode { - return s.GetToken(ConfigParserWHITESPACE, i) -} - -func (s *LeadingCommentContext) AllString_() []IStringContext { - children := s.GetChildren() - len := 0 - for _, ctx := range children { - if _, ok := ctx.(IStringContext); ok { - len++ - } - } - - tst := make([]IStringContext, len) - i := 0 - for _, ctx := range children { - if t, ok := ctx.(IStringContext); ok { - tst[i] = t.(IStringContext) - i++ - } - } - - return tst -} - -func (s *LeadingCommentContext) String_(i int) IStringContext { - var t antlr.RuleContext - j := 0 - for _, ctx := range s.GetChildren() { - if _, ok := ctx.(IStringContext); ok { - if j == i { - t = ctx.(antlr.RuleContext) - break - } - j++ - } - } - - if t == nil { - return nil - } - - return t.(IStringContext) -} - -func (s *LeadingCommentContext) GetRuleContext() antlr.RuleContext { - return s -} - -func (s *LeadingCommentContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { - return antlr.TreesStringTree(s, ruleNames, recog) -} - -func (s *LeadingCommentContext) EnterRule(listener antlr.ParseTreeListener) { - if listenerT, ok := listener.(ConfigListener); ok { - listenerT.EnterLeadingComment(s) - } -} - -func (s *LeadingCommentContext) ExitRule(listener antlr.ParseTreeListener) { - if listenerT, ok := listener.(ConfigListener); ok { - listenerT.ExitLeadingComment(s) - } -} - -func (p *ConfigParser) LeadingComment() (localctx ILeadingCommentContext) { - localctx = NewLeadingCommentContext(p, p.GetParserRuleContext(), p.GetState()) - p.EnterRule(localctx, 10, ConfigParserRULE_leadingComment) - var _la int - - p.EnterOuterAlt(localctx, 1) - { - p.SetState(56) - p.Match(ConfigParserHASH) - if p.HasError() { - // Recognition error - abort rule - goto errorExit - } - } - p.SetState(58) - p.GetErrorHandler().Sync(p) - if p.HasError() { - goto errorExit - } - _la = p.GetTokenStream().LA(1) - - if _la == ConfigParserWHITESPACE { - { - p.SetState(57) - p.Match(ConfigParserWHITESPACE) - if p.HasError() { - // Recognition error - abort rule - goto errorExit - } - } - - } - p.SetState(64) - p.GetErrorHandler().Sync(p) - if p.HasError() { - goto errorExit - } - _la = p.GetTokenStream().LA(1) - - for ok := true; ok; ok = _la == ConfigParserSTRING || _la == ConfigParserQUOTED_STRING { - { - p.SetState(60) - p.String_() - } - p.SetState(62) - p.GetErrorHandler().Sync(p) - if p.HasError() { - goto errorExit - } - _la = p.GetTokenStream().LA(1) - - if _la == ConfigParserWHITESPACE { - { - p.SetState(61) - p.Match(ConfigParserWHITESPACE) - if p.HasError() { - // Recognition error - abort rule - goto errorExit - } - } - - } - - p.SetState(66) - p.GetErrorHandler().Sync(p) - if p.HasError() { - goto errorExit - } - _la = p.GetTokenStream().LA(1) - } - -errorExit: - if p.HasError() { - v := p.GetError() - localctx.SetException(v) - p.GetErrorHandler().ReportError(p, v) - p.GetErrorHandler().Recover(p, v) - p.SetError(nil) - } - p.ExitRule() - return localctx - goto errorExit // Trick to prevent compiler error if the label is not used -} - -// IStringContext is an interface to support dynamic dispatch. -type IStringContext interface { - antlr.ParserRuleContext - - // GetParser returns the parser. - GetParser() antlr.Parser - - // Getter signatures - QUOTED_STRING() antlr.TerminalNode - STRING() antlr.TerminalNode - - // IsStringContext differentiates from other interfaces. - IsStringContext() -} - -type StringContext struct { - antlr.BaseParserRuleContext - parser antlr.Parser -} - -func NewEmptyStringContext() *StringContext { - var p = new(StringContext) - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) - p.RuleIndex = ConfigParserRULE_string - return p -} - -func InitEmptyStringContext(p *StringContext) { - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) - p.RuleIndex = ConfigParserRULE_string -} - -func (*StringContext) IsStringContext() {} - -func NewStringContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *StringContext { - var p = new(StringContext) - - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) - - p.parser = parser - p.RuleIndex = ConfigParserRULE_string - - return p -} - -func (s *StringContext) GetParser() antlr.Parser { return s.parser } - -func (s *StringContext) QUOTED_STRING() antlr.TerminalNode { - return s.GetToken(ConfigParserQUOTED_STRING, 0) -} - -func (s *StringContext) STRING() antlr.TerminalNode { - return s.GetToken(ConfigParserSTRING, 0) -} - -func (s *StringContext) GetRuleContext() antlr.RuleContext { - return s -} - -func (s *StringContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { - return antlr.TreesStringTree(s, ruleNames, recog) -} - -func (s *StringContext) EnterRule(listener antlr.ParseTreeListener) { - if listenerT, ok := listener.(ConfigListener); ok { - listenerT.EnterString(s) - } -} - -func (s *StringContext) ExitRule(listener antlr.ParseTreeListener) { - if listenerT, ok := listener.(ConfigListener); ok { - listenerT.ExitString(s) - } -} - -func (p *ConfigParser) String_() (localctx IStringContext) { - localctx = NewStringContext(p, p.GetParserRuleContext(), p.GetState()) - p.EnterRule(localctx, 12, ConfigParserRULE_string) - var _la int - - p.EnterOuterAlt(localctx, 1) - { - p.SetState(68) - _la = p.GetTokenStream().LA(1) - - if !(_la == ConfigParserSTRING || _la == ConfigParserQUOTED_STRING) { - p.GetErrorHandler().RecoverInline(p) - } else { - p.GetErrorHandler().ReportMatch(p) - p.Consume() - } - } - -errorExit: - if p.HasError() { - v := p.GetError() - localctx.SetException(v) - p.GetErrorHandler().ReportError(p, v) - p.GetErrorHandler().Recover(p, v) - p.SetError(nil) - } - p.ExitRule() - return localctx - goto errorExit // Trick to prevent compiler error if the label is not used -} From fc0dca8d32c99857e154a648dd43b7977529973f Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Sun, 22 Sep 2024 12:30:43 +0200 Subject: [PATCH 073/133] feat(ssh_config): Add first version of ssh_config --- handlers/ssh_config/ast/error-listener.go | 45 + handlers/ssh_config/ast/indexes.go | 35 + handlers/ssh_config/ast/listener.go | 171 +++ handlers/ssh_config/ast/parser.go | 85 ++ handlers/ssh_config/ast/parser/Config.interp | 5 +- handlers/ssh_config/ast/parser/Config.tokens | 1 + .../ssh_config/ast/parser/ConfigLexer.interp | 5 +- .../ssh_config/ast/parser/ConfigLexer.tokens | 1 + .../ast/parser/config_base_listener.go | 6 + .../ssh_config/ast/parser/config_lexer.go | 46 +- .../ssh_config/ast/parser/config_listener.go | 6 + .../ssh_config/ast/parser/config_parser.go | 384 ++++-- handlers/ssh_config/ast/parser_test.go | 129 ++ handlers/ssh_config/ast/ssh_config.go | 7 +- handlers/ssh_config/ast/ssh_config_fields.go | 76 ++ handlers/ssh_config/match-parser/Match.g4 | 45 + .../ssh_config/match-parser/error-listener.go | 45 + handlers/ssh_config/match-parser/listener.go | 132 ++ handlers/ssh_config/match-parser/match_ast.go | 56 + .../ssh_config/match-parser/match_fields.go | 62 + handlers/ssh_config/match-parser/parser.go | 54 + .../match-parser/parser/Match.interp | 26 + .../match-parser/parser/Match.tokens | 5 + .../match-parser/parser/MatchLexer.interp | 29 + .../match-parser/parser/MatchLexer.tokens | 5 + .../parser/match_base_listener.go | 64 + .../match-parser/parser/match_lexer.go | 118 ++ .../match-parser/parser/match_listener.go | 52 + .../match-parser/parser/match_parser.go | 1087 +++++++++++++++++ .../ssh_config/match-parser/parser_test.go | 143 +++ handlers/ssh_config/shared.go | 14 + 31 files changed, 2808 insertions(+), 131 deletions(-) create mode 100644 handlers/ssh_config/ast/error-listener.go create mode 100644 handlers/ssh_config/ast/indexes.go create mode 100644 handlers/ssh_config/ast/listener.go create mode 100644 handlers/ssh_config/ast/parser.go create mode 100644 handlers/ssh_config/ast/parser_test.go create mode 100644 handlers/ssh_config/match-parser/Match.g4 create mode 100644 handlers/ssh_config/match-parser/error-listener.go create mode 100644 handlers/ssh_config/match-parser/listener.go create mode 100644 handlers/ssh_config/match-parser/match_ast.go create mode 100644 handlers/ssh_config/match-parser/match_fields.go create mode 100644 handlers/ssh_config/match-parser/parser.go create mode 100644 handlers/ssh_config/match-parser/parser/Match.interp create mode 100644 handlers/ssh_config/match-parser/parser/Match.tokens create mode 100644 handlers/ssh_config/match-parser/parser/MatchLexer.interp create mode 100644 handlers/ssh_config/match-parser/parser/MatchLexer.tokens create mode 100644 handlers/ssh_config/match-parser/parser/match_base_listener.go create mode 100644 handlers/ssh_config/match-parser/parser/match_lexer.go create mode 100644 handlers/ssh_config/match-parser/parser/match_listener.go create mode 100644 handlers/ssh_config/match-parser/parser/match_parser.go create mode 100644 handlers/ssh_config/match-parser/parser_test.go create mode 100644 handlers/ssh_config/shared.go diff --git a/handlers/ssh_config/ast/error-listener.go b/handlers/ssh_config/ast/error-listener.go new file mode 100644 index 0000000..74d4387 --- /dev/null +++ b/handlers/ssh_config/ast/error-listener.go @@ -0,0 +1,45 @@ +package ast + +import ( + "config-lsp/common" + + "github.com/antlr4-go/antlr/v4" +) + +type errorListenerContext struct { + line uint32 +} + +type errorListener struct { + *antlr.DefaultErrorListener + Errors []common.LSPError + context errorListenerContext +} + +func (d *errorListener) SyntaxError( + recognizer antlr.Recognizer, + offendingSymbol interface{}, + _ int, + character int, + message string, + error antlr.RecognitionException, +) { + line := d.context.line + d.Errors = append(d.Errors, common.LSPError{ + Range: common.CreateSingleCharRange(uint32(line), uint32(character)), + Err: common.SyntaxError{ + Message: message, + }, + }) +} + +func createErrorListener( + line uint32, +) errorListener { + return errorListener{ + Errors: make([]common.LSPError, 0), + context: errorListenerContext{ + line: line, + }, + } +} diff --git a/handlers/ssh_config/ast/indexes.go b/handlers/ssh_config/ast/indexes.go new file mode 100644 index 0000000..109be56 --- /dev/null +++ b/handlers/ssh_config/ast/indexes.go @@ -0,0 +1,35 @@ +package ast + +import "config-lsp/common" + + +type ValidPath string + +func (v ValidPath) AsURI() string { + return "file://" + string(v) +} + +type SSHIndexIncludeValue struct { + common.LocationRange + Value string + + // Actual valid paths, these will be set by the analyzer + Paths []ValidPath +} + +type SSHIndexIncludeLine struct { + Values []*SSHIndexIncludeValue + Option *SSHOption + Block *SSHBlock +} + +type SSHIndexes struct { + Includes []*SSHIndexIncludeLine +} + +func NewSSHIndexes() *SSHIndexes { + return &SSHIndexes{ + Includes: make([]*SSHIndexIncludeLine, 0), + } +} + diff --git a/handlers/ssh_config/ast/listener.go b/handlers/ssh_config/ast/listener.go new file mode 100644 index 0000000..3adfe6e --- /dev/null +++ b/handlers/ssh_config/ast/listener.go @@ -0,0 +1,171 @@ +package ast + +import ( + "config-lsp/common" + commonparser "config-lsp/common/parser" + "config-lsp/handlers/ssh_config/ast/parser" + "config-lsp/handlers/ssh_config/match-parser" + "strings" + + "github.com/emirpasic/gods/maps/treemap" + gods "github.com/emirpasic/gods/utils" +) + +type sshListenerContext struct { + line uint32 + currentOption *SSHOption + currentBlock SSHBlock + currentKeyIsBlockOf *SSHBlockType + currentIndexes *SSHIndexes +} + +func createListenerContext() *sshListenerContext { + context := new(sshListenerContext) + context.currentIndexes = NewSSHIndexes() + + return context +} + +func createListener( + config *SSHConfig, + context *sshListenerContext, +) sshParserListener { + return sshParserListener{ + Config: config, + Errors: make([]common.LSPError, 0), + sshContext: context, + } +} + +type sshParserListener struct { + *parser.BaseConfigListener + Config *SSHConfig + Errors []common.LSPError + sshContext *sshListenerContext +} + +func (s *sshParserListener) EnterEntry(ctx *parser.EntryContext) { + location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext) + location.ChangeBothLines(s.sshContext.line) + + value := commonparser.ParseRawString(ctx.GetText(), commonparser.FullFeatures) + option := &SSHOption{ + LocationRange: location, + Value: value, + } + + s.sshContext.currentOption = option +} + +func (s *sshParserListener) EnterKey(ctx *parser.KeyContext) { + location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext) + location.ChangeBothLines(s.sshContext.line) + + text := ctx.GetText() + value := commonparser.ParseRawString(text, commonparser.FullFeatures) + key := strings.Trim( + value.Value, + " ", + ) + + switch strings.ToLower(text) { + case "match": + value := SSHBlockTypeMatch + s.sshContext.currentKeyIsBlockOf = &value + case "host": + value := SSHBlockTypeHost + s.sshContext.currentKeyIsBlockOf = &value + } + + s.sshContext.currentOption.Key = &SSHKey{ + LocationRange: location, + Value: value, + Key: key, + } +} + +func (s *sshParserListener) EnterSeparator(ctx *parser.SeparatorContext) { + location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext) + location.ChangeBothLines(s.sshContext.line) + + text := ctx.GetText() + value := commonparser.ParseRawString(text, commonparser.FullFeatures) + + s.sshContext.currentOption.Separator = &SSHSeparator{ + LocationRange: location, + Value: value, + } +} + +func (s *sshParserListener) EnterValue(ctx *parser.ValueContext) { + location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext) + location.ChangeBothLines(s.sshContext.line) + + value := commonparser.ParseRawString(ctx.GetText(), commonparser.FullFeatures) + s.sshContext.currentOption.OptionValue = &SSHValue{ + LocationRange: location, + Value: value, + } +} + +func (s *sshParserListener) ExitEntry(ctx *parser.EntryContext) { + location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext) + location.ChangeBothLines(s.sshContext.line) + + defer (func() { + s.sshContext.currentOption = nil + })() + + if s.sshContext.currentKeyIsBlockOf != nil { + switch *s.sshContext.currentKeyIsBlockOf { + case SSHBlockTypeMatch: + var match *matchparser.Match + + matchParser := matchparser.NewMatch() + errors := matchParser.Parse( + s.sshContext.currentOption.OptionValue.Value.Raw, + location.Start.Line, + s.sshContext.currentOption.OptionValue.Start.Character, + ) + + if len(errors) > 0 { + for _, err := range errors { + s.Errors = append(s.Errors, common.LSPError{ + Range: err.Range.ShiftHorizontal(s.sshContext.currentOption.Start.Character), + Err: err.Err, + }) + } + } else { + match = matchParser + } + + matchBlock := &SSHMatchBlock{ + LocationRange: location, + MatchOption: s.sshContext.currentOption, + MatchValue: match, + Options: treemap.NewWith(gods.UInt32Comparator), + } + + s.Config.Options.Put( + location.Start.Line, + matchBlock, + ) + + s.sshContext.currentKeyIsBlockOf = nil + s.sshContext.currentBlock = matchBlock + } + + return + } + + if s.sshContext.currentBlock == nil { + s.Config.Options.Put( + location.Start.Line, + s.sshContext.currentOption, + ) + } else { + block := s.sshContext.currentBlock + block.AddOption(s.sshContext.currentOption) + block.SetEnd(location.End) + } +} diff --git a/handlers/ssh_config/ast/parser.go b/handlers/ssh_config/ast/parser.go new file mode 100644 index 0000000..c6298d7 --- /dev/null +++ b/handlers/ssh_config/ast/parser.go @@ -0,0 +1,85 @@ +package ast + +import ( + "config-lsp/common" + "config-lsp/handlers/ssh_config/ast/parser" + "config-lsp/utils" + "regexp" + + "github.com/antlr4-go/antlr/v4" + "github.com/emirpasic/gods/maps/treemap" + + gods "github.com/emirpasic/gods/utils" +) + +func NewSSHConfig() *SSHConfig { + config := &SSHConfig{} + config.Clear() + + return config +} + +func (c *SSHConfig) Clear() { + c.Options = treemap.NewWith(gods.UInt32Comparator) + c.CommentLines = map[uint32]struct{}{} +} + +var commentPattern = regexp.MustCompile(`^\s*#.*$`) +var emptyPattern = regexp.MustCompile(`^\s*$`) + +func (c *SSHConfig) Parse(input string) []common.LSPError { + errors := make([]common.LSPError, 0) + lines := utils.SplitIntoLines(input) + context := createListenerContext() + + for rawLineNumber, line := range lines { + context.line = uint32(rawLineNumber) + + if emptyPattern.MatchString(line) { + continue + } + + if commentPattern.MatchString(line) { + c.CommentLines[context.line] = struct{}{} + continue + } + + errors = append( + errors, + c.parseStatement(context, line)..., + ) + } + + return errors +} + +func (c *SSHConfig) parseStatement( + context *sshListenerContext, + input string, +) []common.LSPError { + stream := antlr.NewInputStream(input) + + lexerErrorListener := createErrorListener(context.line) + lexer := parser.NewConfigLexer(stream) + lexer.RemoveErrorListeners() + lexer.AddErrorListener(&lexerErrorListener) + + tokenStream := antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel) + + parserErrorListener := createErrorListener(context.line) + antlrParser := parser.NewConfigParser(tokenStream) + antlrParser.RemoveErrorListeners() + antlrParser.AddErrorListener(&parserErrorListener) + + listener := createListener(c, context) + antlr.ParseTreeWalkerDefault.Walk( + &listener, + antlrParser.LineStatement(), + ) + + errors := lexerErrorListener.Errors + errors = append(errors, parserErrorListener.Errors...) + errors = append(errors, listener.Errors...) + + return errors +} diff --git a/handlers/ssh_config/ast/parser/Config.interp b/handlers/ssh_config/ast/parser/Config.interp index 2832f42..e02ab96 100644 --- a/handlers/ssh_config/ast/parser/Config.interp +++ b/handlers/ssh_config/ast/parser/Config.interp @@ -4,6 +4,7 @@ null null null null +null token symbolic names: null @@ -11,6 +12,7 @@ HASH WHITESPACE STRING NEWLINE +QUOTED_STRING rule names: lineStatement @@ -19,7 +21,8 @@ separator key value leadingComment +string atn: -[4, 1, 4, 66, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 2, 5, 7, 5, 1, 0, 1, 0, 1, 0, 3, 0, 16, 8, 0, 3, 0, 18, 8, 0, 1, 0, 1, 0, 1, 1, 3, 1, 23, 8, 1, 1, 1, 3, 1, 26, 8, 1, 1, 1, 3, 1, 29, 8, 1, 1, 1, 3, 1, 32, 8, 1, 1, 1, 3, 1, 35, 8, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, 1, 4, 5, 4, 43, 8, 4, 10, 4, 12, 4, 46, 9, 4, 1, 4, 3, 4, 49, 8, 4, 1, 4, 3, 4, 52, 8, 4, 1, 5, 1, 5, 3, 5, 56, 8, 5, 1, 5, 1, 5, 3, 5, 60, 8, 5, 4, 5, 62, 8, 5, 11, 5, 12, 5, 63, 1, 5, 0, 0, 6, 0, 2, 4, 6, 8, 10, 0, 0, 73, 0, 17, 1, 0, 0, 0, 2, 22, 1, 0, 0, 0, 4, 36, 1, 0, 0, 0, 6, 38, 1, 0, 0, 0, 8, 44, 1, 0, 0, 0, 10, 53, 1, 0, 0, 0, 12, 18, 3, 2, 1, 0, 13, 18, 3, 10, 5, 0, 14, 16, 5, 2, 0, 0, 15, 14, 1, 0, 0, 0, 15, 16, 1, 0, 0, 0, 16, 18, 1, 0, 0, 0, 17, 12, 1, 0, 0, 0, 17, 13, 1, 0, 0, 0, 17, 15, 1, 0, 0, 0, 18, 19, 1, 0, 0, 0, 19, 20, 5, 0, 0, 1, 20, 1, 1, 0, 0, 0, 21, 23, 5, 2, 0, 0, 22, 21, 1, 0, 0, 0, 22, 23, 1, 0, 0, 0, 23, 25, 1, 0, 0, 0, 24, 26, 3, 6, 3, 0, 25, 24, 1, 0, 0, 0, 25, 26, 1, 0, 0, 0, 26, 28, 1, 0, 0, 0, 27, 29, 3, 4, 2, 0, 28, 27, 1, 0, 0, 0, 28, 29, 1, 0, 0, 0, 29, 31, 1, 0, 0, 0, 30, 32, 3, 8, 4, 0, 31, 30, 1, 0, 0, 0, 31, 32, 1, 0, 0, 0, 32, 34, 1, 0, 0, 0, 33, 35, 3, 10, 5, 0, 34, 33, 1, 0, 0, 0, 34, 35, 1, 0, 0, 0, 35, 3, 1, 0, 0, 0, 36, 37, 5, 2, 0, 0, 37, 5, 1, 0, 0, 0, 38, 39, 5, 3, 0, 0, 39, 7, 1, 0, 0, 0, 40, 41, 5, 3, 0, 0, 41, 43, 5, 2, 0, 0, 42, 40, 1, 0, 0, 0, 43, 46, 1, 0, 0, 0, 44, 42, 1, 0, 0, 0, 44, 45, 1, 0, 0, 0, 45, 48, 1, 0, 0, 0, 46, 44, 1, 0, 0, 0, 47, 49, 5, 3, 0, 0, 48, 47, 1, 0, 0, 0, 48, 49, 1, 0, 0, 0, 49, 51, 1, 0, 0, 0, 50, 52, 5, 2, 0, 0, 51, 50, 1, 0, 0, 0, 51, 52, 1, 0, 0, 0, 52, 9, 1, 0, 0, 0, 53, 55, 5, 1, 0, 0, 54, 56, 5, 2, 0, 0, 55, 54, 1, 0, 0, 0, 55, 56, 1, 0, 0, 0, 56, 61, 1, 0, 0, 0, 57, 59, 5, 3, 0, 0, 58, 60, 5, 2, 0, 0, 59, 58, 1, 0, 0, 0, 59, 60, 1, 0, 0, 0, 60, 62, 1, 0, 0, 0, 61, 57, 1, 0, 0, 0, 62, 63, 1, 0, 0, 0, 63, 61, 1, 0, 0, 0, 63, 64, 1, 0, 0, 0, 64, 11, 1, 0, 0, 0, 13, 15, 17, 22, 25, 28, 31, 34, 44, 48, 51, 55, 59, 63] \ No newline at end of file +[4, 1, 5, 71, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 2, 5, 7, 5, 2, 6, 7, 6, 1, 0, 1, 0, 1, 0, 3, 0, 18, 8, 0, 3, 0, 20, 8, 0, 1, 0, 1, 0, 1, 1, 3, 1, 25, 8, 1, 1, 1, 3, 1, 28, 8, 1, 1, 1, 3, 1, 31, 8, 1, 1, 1, 3, 1, 34, 8, 1, 1, 1, 3, 1, 37, 8, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, 1, 4, 1, 4, 5, 4, 46, 8, 4, 10, 4, 12, 4, 49, 9, 4, 1, 4, 3, 4, 52, 8, 4, 1, 4, 3, 4, 55, 8, 4, 1, 5, 1, 5, 3, 5, 59, 8, 5, 1, 5, 1, 5, 3, 5, 63, 8, 5, 4, 5, 65, 8, 5, 11, 5, 12, 5, 66, 1, 6, 1, 6, 1, 6, 0, 0, 7, 0, 2, 4, 6, 8, 10, 12, 0, 1, 2, 0, 3, 3, 5, 5, 77, 0, 19, 1, 0, 0, 0, 2, 24, 1, 0, 0, 0, 4, 38, 1, 0, 0, 0, 6, 40, 1, 0, 0, 0, 8, 47, 1, 0, 0, 0, 10, 56, 1, 0, 0, 0, 12, 68, 1, 0, 0, 0, 14, 20, 3, 2, 1, 0, 15, 20, 3, 10, 5, 0, 16, 18, 5, 2, 0, 0, 17, 16, 1, 0, 0, 0, 17, 18, 1, 0, 0, 0, 18, 20, 1, 0, 0, 0, 19, 14, 1, 0, 0, 0, 19, 15, 1, 0, 0, 0, 19, 17, 1, 0, 0, 0, 20, 21, 1, 0, 0, 0, 21, 22, 5, 0, 0, 1, 22, 1, 1, 0, 0, 0, 23, 25, 5, 2, 0, 0, 24, 23, 1, 0, 0, 0, 24, 25, 1, 0, 0, 0, 25, 27, 1, 0, 0, 0, 26, 28, 3, 6, 3, 0, 27, 26, 1, 0, 0, 0, 27, 28, 1, 0, 0, 0, 28, 30, 1, 0, 0, 0, 29, 31, 3, 4, 2, 0, 30, 29, 1, 0, 0, 0, 30, 31, 1, 0, 0, 0, 31, 33, 1, 0, 0, 0, 32, 34, 3, 8, 4, 0, 33, 32, 1, 0, 0, 0, 33, 34, 1, 0, 0, 0, 34, 36, 1, 0, 0, 0, 35, 37, 3, 10, 5, 0, 36, 35, 1, 0, 0, 0, 36, 37, 1, 0, 0, 0, 37, 3, 1, 0, 0, 0, 38, 39, 5, 2, 0, 0, 39, 5, 1, 0, 0, 0, 40, 41, 3, 12, 6, 0, 41, 7, 1, 0, 0, 0, 42, 43, 3, 12, 6, 0, 43, 44, 5, 2, 0, 0, 44, 46, 1, 0, 0, 0, 45, 42, 1, 0, 0, 0, 46, 49, 1, 0, 0, 0, 47, 45, 1, 0, 0, 0, 47, 48, 1, 0, 0, 0, 48, 51, 1, 0, 0, 0, 49, 47, 1, 0, 0, 0, 50, 52, 3, 12, 6, 0, 51, 50, 1, 0, 0, 0, 51, 52, 1, 0, 0, 0, 52, 54, 1, 0, 0, 0, 53, 55, 5, 2, 0, 0, 54, 53, 1, 0, 0, 0, 54, 55, 1, 0, 0, 0, 55, 9, 1, 0, 0, 0, 56, 58, 5, 1, 0, 0, 57, 59, 5, 2, 0, 0, 58, 57, 1, 0, 0, 0, 58, 59, 1, 0, 0, 0, 59, 64, 1, 0, 0, 0, 60, 62, 3, 12, 6, 0, 61, 63, 5, 2, 0, 0, 62, 61, 1, 0, 0, 0, 62, 63, 1, 0, 0, 0, 63, 65, 1, 0, 0, 0, 64, 60, 1, 0, 0, 0, 65, 66, 1, 0, 0, 0, 66, 64, 1, 0, 0, 0, 66, 67, 1, 0, 0, 0, 67, 11, 1, 0, 0, 0, 68, 69, 7, 0, 0, 0, 69, 13, 1, 0, 0, 0, 13, 17, 19, 24, 27, 30, 33, 36, 47, 51, 54, 58, 62, 66] \ No newline at end of file diff --git a/handlers/ssh_config/ast/parser/Config.tokens b/handlers/ssh_config/ast/parser/Config.tokens index aacc14c..fa8c415 100644 --- a/handlers/ssh_config/ast/parser/Config.tokens +++ b/handlers/ssh_config/ast/parser/Config.tokens @@ -2,4 +2,5 @@ HASH=1 WHITESPACE=2 STRING=3 NEWLINE=4 +QUOTED_STRING=5 '#'=1 diff --git a/handlers/ssh_config/ast/parser/ConfigLexer.interp b/handlers/ssh_config/ast/parser/ConfigLexer.interp index d61e14d..c093cfb 100644 --- a/handlers/ssh_config/ast/parser/ConfigLexer.interp +++ b/handlers/ssh_config/ast/parser/ConfigLexer.interp @@ -4,6 +4,7 @@ null null null null +null token symbolic names: null @@ -11,12 +12,14 @@ HASH WHITESPACE STRING NEWLINE +QUOTED_STRING rule names: HASH WHITESPACE STRING NEWLINE +QUOTED_STRING channel names: DEFAULT_TOKEN_CHANNEL @@ -26,4 +29,4 @@ mode names: DEFAULT_MODE atn: -[4, 0, 4, 26, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 1, 0, 1, 0, 1, 1, 4, 1, 13, 8, 1, 11, 1, 12, 1, 14, 1, 2, 4, 2, 18, 8, 2, 11, 2, 12, 2, 19, 1, 3, 3, 3, 23, 8, 3, 1, 3, 1, 3, 0, 0, 4, 1, 1, 3, 2, 5, 3, 7, 4, 1, 0, 2, 2, 0, 9, 9, 32, 32, 4, 0, 9, 10, 13, 13, 32, 32, 35, 35, 28, 0, 1, 1, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, 5, 1, 0, 0, 0, 0, 7, 1, 0, 0, 0, 1, 9, 1, 0, 0, 0, 3, 12, 1, 0, 0, 0, 5, 17, 1, 0, 0, 0, 7, 22, 1, 0, 0, 0, 9, 10, 5, 35, 0, 0, 10, 2, 1, 0, 0, 0, 11, 13, 7, 0, 0, 0, 12, 11, 1, 0, 0, 0, 13, 14, 1, 0, 0, 0, 14, 12, 1, 0, 0, 0, 14, 15, 1, 0, 0, 0, 15, 4, 1, 0, 0, 0, 16, 18, 8, 1, 0, 0, 17, 16, 1, 0, 0, 0, 18, 19, 1, 0, 0, 0, 19, 17, 1, 0, 0, 0, 19, 20, 1, 0, 0, 0, 20, 6, 1, 0, 0, 0, 21, 23, 5, 13, 0, 0, 22, 21, 1, 0, 0, 0, 22, 23, 1, 0, 0, 0, 23, 24, 1, 0, 0, 0, 24, 25, 5, 10, 0, 0, 25, 8, 1, 0, 0, 0, 4, 0, 14, 19, 22, 0] \ No newline at end of file +[4, 0, 5, 46, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 1, 0, 1, 0, 1, 1, 4, 1, 15, 8, 1, 11, 1, 12, 1, 16, 1, 2, 4, 2, 20, 8, 2, 11, 2, 12, 2, 21, 1, 3, 3, 3, 25, 8, 3, 1, 3, 1, 3, 1, 4, 1, 4, 3, 4, 31, 8, 4, 1, 4, 1, 4, 1, 4, 5, 4, 36, 8, 4, 10, 4, 12, 4, 39, 9, 4, 1, 4, 3, 4, 42, 8, 4, 1, 4, 3, 4, 45, 8, 4, 0, 0, 5, 1, 1, 3, 2, 5, 3, 7, 4, 9, 5, 1, 0, 2, 2, 0, 9, 9, 32, 32, 4, 0, 9, 10, 13, 13, 32, 32, 34, 35, 52, 0, 1, 1, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, 5, 1, 0, 0, 0, 0, 7, 1, 0, 0, 0, 0, 9, 1, 0, 0, 0, 1, 11, 1, 0, 0, 0, 3, 14, 1, 0, 0, 0, 5, 19, 1, 0, 0, 0, 7, 24, 1, 0, 0, 0, 9, 28, 1, 0, 0, 0, 11, 12, 5, 35, 0, 0, 12, 2, 1, 0, 0, 0, 13, 15, 7, 0, 0, 0, 14, 13, 1, 0, 0, 0, 15, 16, 1, 0, 0, 0, 16, 14, 1, 0, 0, 0, 16, 17, 1, 0, 0, 0, 17, 4, 1, 0, 0, 0, 18, 20, 8, 1, 0, 0, 19, 18, 1, 0, 0, 0, 20, 21, 1, 0, 0, 0, 21, 19, 1, 0, 0, 0, 21, 22, 1, 0, 0, 0, 22, 6, 1, 0, 0, 0, 23, 25, 5, 13, 0, 0, 24, 23, 1, 0, 0, 0, 24, 25, 1, 0, 0, 0, 25, 26, 1, 0, 0, 0, 26, 27, 5, 10, 0, 0, 27, 8, 1, 0, 0, 0, 28, 30, 5, 34, 0, 0, 29, 31, 3, 3, 1, 0, 30, 29, 1, 0, 0, 0, 30, 31, 1, 0, 0, 0, 31, 37, 1, 0, 0, 0, 32, 33, 3, 5, 2, 0, 33, 34, 3, 3, 1, 0, 34, 36, 1, 0, 0, 0, 35, 32, 1, 0, 0, 0, 36, 39, 1, 0, 0, 0, 37, 35, 1, 0, 0, 0, 37, 38, 1, 0, 0, 0, 38, 41, 1, 0, 0, 0, 39, 37, 1, 0, 0, 0, 40, 42, 3, 5, 2, 0, 41, 40, 1, 0, 0, 0, 41, 42, 1, 0, 0, 0, 42, 44, 1, 0, 0, 0, 43, 45, 5, 34, 0, 0, 44, 43, 1, 0, 0, 0, 44, 45, 1, 0, 0, 0, 45, 10, 1, 0, 0, 0, 8, 0, 16, 21, 24, 30, 37, 41, 44, 0] \ No newline at end of file diff --git a/handlers/ssh_config/ast/parser/ConfigLexer.tokens b/handlers/ssh_config/ast/parser/ConfigLexer.tokens index aacc14c..fa8c415 100644 --- a/handlers/ssh_config/ast/parser/ConfigLexer.tokens +++ b/handlers/ssh_config/ast/parser/ConfigLexer.tokens @@ -2,4 +2,5 @@ HASH=1 WHITESPACE=2 STRING=3 NEWLINE=4 +QUOTED_STRING=5 '#'=1 diff --git a/handlers/ssh_config/ast/parser/config_base_listener.go b/handlers/ssh_config/ast/parser/config_base_listener.go index ac8bdac..00e7840 100644 --- a/handlers/ssh_config/ast/parser/config_base_listener.go +++ b/handlers/ssh_config/ast/parser/config_base_listener.go @@ -56,3 +56,9 @@ func (s *BaseConfigListener) EnterLeadingComment(ctx *LeadingCommentContext) {} // ExitLeadingComment is called when production leadingComment is exited. func (s *BaseConfigListener) ExitLeadingComment(ctx *LeadingCommentContext) {} + +// EnterString is called when production string is entered. +func (s *BaseConfigListener) EnterString(ctx *StringContext) {} + +// ExitString is called when production string is exited. +func (s *BaseConfigListener) ExitString(ctx *StringContext) {} diff --git a/handlers/ssh_config/ast/parser/config_lexer.go b/handlers/ssh_config/ast/parser/config_lexer.go index ace491d..021f1fc 100644 --- a/handlers/ssh_config/ast/parser/config_lexer.go +++ b/handlers/ssh_config/ast/parser/config_lexer.go @@ -46,25 +46,34 @@ func configlexerLexerInit() { "", "'#'", } staticData.SymbolicNames = []string{ - "", "HASH", "WHITESPACE", "STRING", "NEWLINE", + "", "HASH", "WHITESPACE", "STRING", "NEWLINE", "QUOTED_STRING", } staticData.RuleNames = []string{ - "HASH", "WHITESPACE", "STRING", "NEWLINE", + "HASH", "WHITESPACE", "STRING", "NEWLINE", "QUOTED_STRING", } staticData.PredictionContextCache = antlr.NewPredictionContextCache() staticData.serializedATN = []int32{ - 4, 0, 4, 26, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 1, - 0, 1, 0, 1, 1, 4, 1, 13, 8, 1, 11, 1, 12, 1, 14, 1, 2, 4, 2, 18, 8, 2, - 11, 2, 12, 2, 19, 1, 3, 3, 3, 23, 8, 3, 1, 3, 1, 3, 0, 0, 4, 1, 1, 3, 2, - 5, 3, 7, 4, 1, 0, 2, 2, 0, 9, 9, 32, 32, 4, 0, 9, 10, 13, 13, 32, 32, 35, - 35, 28, 0, 1, 1, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, 5, 1, 0, 0, 0, 0, 7, 1, - 0, 0, 0, 1, 9, 1, 0, 0, 0, 3, 12, 1, 0, 0, 0, 5, 17, 1, 0, 0, 0, 7, 22, - 1, 0, 0, 0, 9, 10, 5, 35, 0, 0, 10, 2, 1, 0, 0, 0, 11, 13, 7, 0, 0, 0, - 12, 11, 1, 0, 0, 0, 13, 14, 1, 0, 0, 0, 14, 12, 1, 0, 0, 0, 14, 15, 1, - 0, 0, 0, 15, 4, 1, 0, 0, 0, 16, 18, 8, 1, 0, 0, 17, 16, 1, 0, 0, 0, 18, - 19, 1, 0, 0, 0, 19, 17, 1, 0, 0, 0, 19, 20, 1, 0, 0, 0, 20, 6, 1, 0, 0, - 0, 21, 23, 5, 13, 0, 0, 22, 21, 1, 0, 0, 0, 22, 23, 1, 0, 0, 0, 23, 24, - 1, 0, 0, 0, 24, 25, 5, 10, 0, 0, 25, 8, 1, 0, 0, 0, 4, 0, 14, 19, 22, 0, + 4, 0, 5, 46, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, + 4, 7, 4, 1, 0, 1, 0, 1, 1, 4, 1, 15, 8, 1, 11, 1, 12, 1, 16, 1, 2, 4, 2, + 20, 8, 2, 11, 2, 12, 2, 21, 1, 3, 3, 3, 25, 8, 3, 1, 3, 1, 3, 1, 4, 1, + 4, 3, 4, 31, 8, 4, 1, 4, 1, 4, 1, 4, 5, 4, 36, 8, 4, 10, 4, 12, 4, 39, + 9, 4, 1, 4, 3, 4, 42, 8, 4, 1, 4, 3, 4, 45, 8, 4, 0, 0, 5, 1, 1, 3, 2, + 5, 3, 7, 4, 9, 5, 1, 0, 2, 2, 0, 9, 9, 32, 32, 4, 0, 9, 10, 13, 13, 32, + 32, 34, 35, 52, 0, 1, 1, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, 5, 1, 0, 0, 0, 0, + 7, 1, 0, 0, 0, 0, 9, 1, 0, 0, 0, 1, 11, 1, 0, 0, 0, 3, 14, 1, 0, 0, 0, + 5, 19, 1, 0, 0, 0, 7, 24, 1, 0, 0, 0, 9, 28, 1, 0, 0, 0, 11, 12, 5, 35, + 0, 0, 12, 2, 1, 0, 0, 0, 13, 15, 7, 0, 0, 0, 14, 13, 1, 0, 0, 0, 15, 16, + 1, 0, 0, 0, 16, 14, 1, 0, 0, 0, 16, 17, 1, 0, 0, 0, 17, 4, 1, 0, 0, 0, + 18, 20, 8, 1, 0, 0, 19, 18, 1, 0, 0, 0, 20, 21, 1, 0, 0, 0, 21, 19, 1, + 0, 0, 0, 21, 22, 1, 0, 0, 0, 22, 6, 1, 0, 0, 0, 23, 25, 5, 13, 0, 0, 24, + 23, 1, 0, 0, 0, 24, 25, 1, 0, 0, 0, 25, 26, 1, 0, 0, 0, 26, 27, 5, 10, + 0, 0, 27, 8, 1, 0, 0, 0, 28, 30, 5, 34, 0, 0, 29, 31, 3, 3, 1, 0, 30, 29, + 1, 0, 0, 0, 30, 31, 1, 0, 0, 0, 31, 37, 1, 0, 0, 0, 32, 33, 3, 5, 2, 0, + 33, 34, 3, 3, 1, 0, 34, 36, 1, 0, 0, 0, 35, 32, 1, 0, 0, 0, 36, 39, 1, + 0, 0, 0, 37, 35, 1, 0, 0, 0, 37, 38, 1, 0, 0, 0, 38, 41, 1, 0, 0, 0, 39, + 37, 1, 0, 0, 0, 40, 42, 3, 5, 2, 0, 41, 40, 1, 0, 0, 0, 41, 42, 1, 0, 0, + 0, 42, 44, 1, 0, 0, 0, 43, 45, 5, 34, 0, 0, 44, 43, 1, 0, 0, 0, 44, 45, + 1, 0, 0, 0, 45, 10, 1, 0, 0, 0, 8, 0, 16, 21, 24, 30, 37, 41, 44, 0, } deserializer := antlr.NewATNDeserializer(nil) staticData.atn = deserializer.Deserialize(staticData.serializedATN) @@ -105,8 +114,9 @@ func NewConfigLexer(input antlr.CharStream) *ConfigLexer { // ConfigLexer tokens. const ( - ConfigLexerHASH = 1 - ConfigLexerWHITESPACE = 2 - ConfigLexerSTRING = 3 - ConfigLexerNEWLINE = 4 + ConfigLexerHASH = 1 + ConfigLexerWHITESPACE = 2 + ConfigLexerSTRING = 3 + ConfigLexerNEWLINE = 4 + ConfigLexerQUOTED_STRING = 5 ) diff --git a/handlers/ssh_config/ast/parser/config_listener.go b/handlers/ssh_config/ast/parser/config_listener.go index 0384e3c..1acf598 100644 --- a/handlers/ssh_config/ast/parser/config_listener.go +++ b/handlers/ssh_config/ast/parser/config_listener.go @@ -26,6 +26,9 @@ type ConfigListener interface { // EnterLeadingComment is called when entering the leadingComment production. EnterLeadingComment(c *LeadingCommentContext) + // EnterString is called when entering the string production. + EnterString(c *StringContext) + // ExitLineStatement is called when exiting the lineStatement production. ExitLineStatement(c *LineStatementContext) @@ -43,4 +46,7 @@ type ConfigListener interface { // ExitLeadingComment is called when exiting the leadingComment production. ExitLeadingComment(c *LeadingCommentContext) + + // ExitString is called when exiting the string production. + ExitString(c *StringContext) } diff --git a/handlers/ssh_config/ast/parser/config_parser.go b/handlers/ssh_config/ast/parser/config_parser.go index 018bbb8..aefb1e3 100644 --- a/handlers/ssh_config/ast/parser/config_parser.go +++ b/handlers/ssh_config/ast/parser/config_parser.go @@ -36,42 +36,44 @@ func configParserInit() { "", "'#'", } staticData.SymbolicNames = []string{ - "", "HASH", "WHITESPACE", "STRING", "NEWLINE", + "", "HASH", "WHITESPACE", "STRING", "NEWLINE", "QUOTED_STRING", } staticData.RuleNames = []string{ "lineStatement", "entry", "separator", "key", "value", "leadingComment", + "string", } staticData.PredictionContextCache = antlr.NewPredictionContextCache() staticData.serializedATN = []int32{ - 4, 1, 4, 66, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, - 2, 5, 7, 5, 1, 0, 1, 0, 1, 0, 3, 0, 16, 8, 0, 3, 0, 18, 8, 0, 1, 0, 1, - 0, 1, 1, 3, 1, 23, 8, 1, 1, 1, 3, 1, 26, 8, 1, 1, 1, 3, 1, 29, 8, 1, 1, - 1, 3, 1, 32, 8, 1, 1, 1, 3, 1, 35, 8, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, - 1, 4, 5, 4, 43, 8, 4, 10, 4, 12, 4, 46, 9, 4, 1, 4, 3, 4, 49, 8, 4, 1, - 4, 3, 4, 52, 8, 4, 1, 5, 1, 5, 3, 5, 56, 8, 5, 1, 5, 1, 5, 3, 5, 60, 8, - 5, 4, 5, 62, 8, 5, 11, 5, 12, 5, 63, 1, 5, 0, 0, 6, 0, 2, 4, 6, 8, 10, - 0, 0, 73, 0, 17, 1, 0, 0, 0, 2, 22, 1, 0, 0, 0, 4, 36, 1, 0, 0, 0, 6, 38, - 1, 0, 0, 0, 8, 44, 1, 0, 0, 0, 10, 53, 1, 0, 0, 0, 12, 18, 3, 2, 1, 0, - 13, 18, 3, 10, 5, 0, 14, 16, 5, 2, 0, 0, 15, 14, 1, 0, 0, 0, 15, 16, 1, - 0, 0, 0, 16, 18, 1, 0, 0, 0, 17, 12, 1, 0, 0, 0, 17, 13, 1, 0, 0, 0, 17, - 15, 1, 0, 0, 0, 18, 19, 1, 0, 0, 0, 19, 20, 5, 0, 0, 1, 20, 1, 1, 0, 0, - 0, 21, 23, 5, 2, 0, 0, 22, 21, 1, 0, 0, 0, 22, 23, 1, 0, 0, 0, 23, 25, - 1, 0, 0, 0, 24, 26, 3, 6, 3, 0, 25, 24, 1, 0, 0, 0, 25, 26, 1, 0, 0, 0, - 26, 28, 1, 0, 0, 0, 27, 29, 3, 4, 2, 0, 28, 27, 1, 0, 0, 0, 28, 29, 1, - 0, 0, 0, 29, 31, 1, 0, 0, 0, 30, 32, 3, 8, 4, 0, 31, 30, 1, 0, 0, 0, 31, - 32, 1, 0, 0, 0, 32, 34, 1, 0, 0, 0, 33, 35, 3, 10, 5, 0, 34, 33, 1, 0, - 0, 0, 34, 35, 1, 0, 0, 0, 35, 3, 1, 0, 0, 0, 36, 37, 5, 2, 0, 0, 37, 5, - 1, 0, 0, 0, 38, 39, 5, 3, 0, 0, 39, 7, 1, 0, 0, 0, 40, 41, 5, 3, 0, 0, - 41, 43, 5, 2, 0, 0, 42, 40, 1, 0, 0, 0, 43, 46, 1, 0, 0, 0, 44, 42, 1, - 0, 0, 0, 44, 45, 1, 0, 0, 0, 45, 48, 1, 0, 0, 0, 46, 44, 1, 0, 0, 0, 47, - 49, 5, 3, 0, 0, 48, 47, 1, 0, 0, 0, 48, 49, 1, 0, 0, 0, 49, 51, 1, 0, 0, - 0, 50, 52, 5, 2, 0, 0, 51, 50, 1, 0, 0, 0, 51, 52, 1, 0, 0, 0, 52, 9, 1, - 0, 0, 0, 53, 55, 5, 1, 0, 0, 54, 56, 5, 2, 0, 0, 55, 54, 1, 0, 0, 0, 55, - 56, 1, 0, 0, 0, 56, 61, 1, 0, 0, 0, 57, 59, 5, 3, 0, 0, 58, 60, 5, 2, 0, - 0, 59, 58, 1, 0, 0, 0, 59, 60, 1, 0, 0, 0, 60, 62, 1, 0, 0, 0, 61, 57, - 1, 0, 0, 0, 62, 63, 1, 0, 0, 0, 63, 61, 1, 0, 0, 0, 63, 64, 1, 0, 0, 0, - 64, 11, 1, 0, 0, 0, 13, 15, 17, 22, 25, 28, 31, 34, 44, 48, 51, 55, 59, - 63, + 4, 1, 5, 71, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, + 2, 5, 7, 5, 2, 6, 7, 6, 1, 0, 1, 0, 1, 0, 3, 0, 18, 8, 0, 3, 0, 20, 8, + 0, 1, 0, 1, 0, 1, 1, 3, 1, 25, 8, 1, 1, 1, 3, 1, 28, 8, 1, 1, 1, 3, 1, + 31, 8, 1, 1, 1, 3, 1, 34, 8, 1, 1, 1, 3, 1, 37, 8, 1, 1, 2, 1, 2, 1, 3, + 1, 3, 1, 4, 1, 4, 1, 4, 5, 4, 46, 8, 4, 10, 4, 12, 4, 49, 9, 4, 1, 4, 3, + 4, 52, 8, 4, 1, 4, 3, 4, 55, 8, 4, 1, 5, 1, 5, 3, 5, 59, 8, 5, 1, 5, 1, + 5, 3, 5, 63, 8, 5, 4, 5, 65, 8, 5, 11, 5, 12, 5, 66, 1, 6, 1, 6, 1, 6, + 0, 0, 7, 0, 2, 4, 6, 8, 10, 12, 0, 1, 2, 0, 3, 3, 5, 5, 77, 0, 19, 1, 0, + 0, 0, 2, 24, 1, 0, 0, 0, 4, 38, 1, 0, 0, 0, 6, 40, 1, 0, 0, 0, 8, 47, 1, + 0, 0, 0, 10, 56, 1, 0, 0, 0, 12, 68, 1, 0, 0, 0, 14, 20, 3, 2, 1, 0, 15, + 20, 3, 10, 5, 0, 16, 18, 5, 2, 0, 0, 17, 16, 1, 0, 0, 0, 17, 18, 1, 0, + 0, 0, 18, 20, 1, 0, 0, 0, 19, 14, 1, 0, 0, 0, 19, 15, 1, 0, 0, 0, 19, 17, + 1, 0, 0, 0, 20, 21, 1, 0, 0, 0, 21, 22, 5, 0, 0, 1, 22, 1, 1, 0, 0, 0, + 23, 25, 5, 2, 0, 0, 24, 23, 1, 0, 0, 0, 24, 25, 1, 0, 0, 0, 25, 27, 1, + 0, 0, 0, 26, 28, 3, 6, 3, 0, 27, 26, 1, 0, 0, 0, 27, 28, 1, 0, 0, 0, 28, + 30, 1, 0, 0, 0, 29, 31, 3, 4, 2, 0, 30, 29, 1, 0, 0, 0, 30, 31, 1, 0, 0, + 0, 31, 33, 1, 0, 0, 0, 32, 34, 3, 8, 4, 0, 33, 32, 1, 0, 0, 0, 33, 34, + 1, 0, 0, 0, 34, 36, 1, 0, 0, 0, 35, 37, 3, 10, 5, 0, 36, 35, 1, 0, 0, 0, + 36, 37, 1, 0, 0, 0, 37, 3, 1, 0, 0, 0, 38, 39, 5, 2, 0, 0, 39, 5, 1, 0, + 0, 0, 40, 41, 3, 12, 6, 0, 41, 7, 1, 0, 0, 0, 42, 43, 3, 12, 6, 0, 43, + 44, 5, 2, 0, 0, 44, 46, 1, 0, 0, 0, 45, 42, 1, 0, 0, 0, 46, 49, 1, 0, 0, + 0, 47, 45, 1, 0, 0, 0, 47, 48, 1, 0, 0, 0, 48, 51, 1, 0, 0, 0, 49, 47, + 1, 0, 0, 0, 50, 52, 3, 12, 6, 0, 51, 50, 1, 0, 0, 0, 51, 52, 1, 0, 0, 0, + 52, 54, 1, 0, 0, 0, 53, 55, 5, 2, 0, 0, 54, 53, 1, 0, 0, 0, 54, 55, 1, + 0, 0, 0, 55, 9, 1, 0, 0, 0, 56, 58, 5, 1, 0, 0, 57, 59, 5, 2, 0, 0, 58, + 57, 1, 0, 0, 0, 58, 59, 1, 0, 0, 0, 59, 64, 1, 0, 0, 0, 60, 62, 3, 12, + 6, 0, 61, 63, 5, 2, 0, 0, 62, 61, 1, 0, 0, 0, 62, 63, 1, 0, 0, 0, 63, 65, + 1, 0, 0, 0, 64, 60, 1, 0, 0, 0, 65, 66, 1, 0, 0, 0, 66, 64, 1, 0, 0, 0, + 66, 67, 1, 0, 0, 0, 67, 11, 1, 0, 0, 0, 68, 69, 7, 0, 0, 0, 69, 13, 1, + 0, 0, 0, 13, 17, 19, 24, 27, 30, 33, 36, 47, 51, 54, 58, 62, 66, } deserializer := antlr.NewATNDeserializer(nil) staticData.atn = deserializer.Deserialize(staticData.serializedATN) @@ -109,11 +111,12 @@ func NewConfigParser(input antlr.TokenStream) *ConfigParser { // ConfigParser tokens. const ( - ConfigParserEOF = antlr.TokenEOF - ConfigParserHASH = 1 - ConfigParserWHITESPACE = 2 - ConfigParserSTRING = 3 - ConfigParserNEWLINE = 4 + ConfigParserEOF = antlr.TokenEOF + ConfigParserHASH = 1 + ConfigParserWHITESPACE = 2 + ConfigParserSTRING = 3 + ConfigParserNEWLINE = 4 + ConfigParserQUOTED_STRING = 5 ) // ConfigParser rules. @@ -124,6 +127,7 @@ const ( ConfigParserRULE_key = 3 ConfigParserRULE_value = 4 ConfigParserRULE_leadingComment = 5 + ConfigParserRULE_string = 6 ) // ILineStatementContext is an interface to support dynamic dispatch. @@ -241,7 +245,7 @@ func (p *ConfigParser) LineStatement() (localctx ILineStatementContext) { var _la int p.EnterOuterAlt(localctx, 1) - p.SetState(17) + p.SetState(19) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -250,18 +254,18 @@ func (p *ConfigParser) LineStatement() (localctx ILineStatementContext) { switch p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 1, p.GetParserRuleContext()) { case 1: { - p.SetState(12) + p.SetState(14) p.Entry() } case 2: { - p.SetState(13) + p.SetState(15) p.LeadingComment() } case 3: - p.SetState(15) + p.SetState(17) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -270,7 +274,7 @@ func (p *ConfigParser) LineStatement() (localctx ILineStatementContext) { if _la == ConfigParserWHITESPACE { { - p.SetState(14) + p.SetState(16) p.Match(ConfigParserWHITESPACE) if p.HasError() { // Recognition error - abort rule @@ -284,7 +288,7 @@ func (p *ConfigParser) LineStatement() (localctx ILineStatementContext) { goto errorExit } { - p.SetState(19) + p.SetState(21) p.Match(ConfigParserEOF) if p.HasError() { // Recognition error - abort rule @@ -449,12 +453,12 @@ func (p *ConfigParser) Entry() (localctx IEntryContext) { var _la int p.EnterOuterAlt(localctx, 1) - p.SetState(22) + p.SetState(24) p.GetErrorHandler().Sync(p) if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 2, p.GetParserRuleContext()) == 1 { { - p.SetState(21) + p.SetState(23) p.Match(ConfigParserWHITESPACE) if p.HasError() { // Recognition error - abort rule @@ -465,43 +469,43 @@ func (p *ConfigParser) Entry() (localctx IEntryContext) { } else if p.HasError() { // JIM goto errorExit } - p.SetState(25) + p.SetState(27) p.GetErrorHandler().Sync(p) if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 3, p.GetParserRuleContext()) == 1 { { - p.SetState(24) + p.SetState(26) p.Key() } } else if p.HasError() { // JIM goto errorExit } - p.SetState(28) + p.SetState(30) p.GetErrorHandler().Sync(p) if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 4, p.GetParserRuleContext()) == 1 { { - p.SetState(27) + p.SetState(29) p.Separator() } } else if p.HasError() { // JIM goto errorExit } - p.SetState(31) + p.SetState(33) p.GetErrorHandler().Sync(p) if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 5, p.GetParserRuleContext()) == 1 { { - p.SetState(30) + p.SetState(32) p.Value() } } else if p.HasError() { // JIM goto errorExit } - p.SetState(34) + p.SetState(36) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -510,7 +514,7 @@ func (p *ConfigParser) Entry() (localctx IEntryContext) { if _la == ConfigParserHASH { { - p.SetState(33) + p.SetState(35) p.LeadingComment() } @@ -604,7 +608,7 @@ func (p *ConfigParser) Separator() (localctx ISeparatorContext) { p.EnterRule(localctx, 4, ConfigParserRULE_separator) p.EnterOuterAlt(localctx, 1) { - p.SetState(36) + p.SetState(38) p.Match(ConfigParserWHITESPACE) if p.HasError() { // Recognition error - abort rule @@ -633,7 +637,7 @@ type IKeyContext interface { GetParser() antlr.Parser // Getter signatures - STRING() antlr.TerminalNode + String_() IStringContext // IsKeyContext differentiates from other interfaces. IsKeyContext() @@ -671,8 +675,20 @@ func NewKeyContext(parser antlr.Parser, parent antlr.ParserRuleContext, invoking func (s *KeyContext) GetParser() antlr.Parser { return s.parser } -func (s *KeyContext) STRING() antlr.TerminalNode { - return s.GetToken(ConfigParserSTRING, 0) +func (s *KeyContext) String_() IStringContext { + var t antlr.RuleContext + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(IStringContext); ok { + t = ctx.(antlr.RuleContext) + break + } + } + + if t == nil { + return nil + } + + return t.(IStringContext) } func (s *KeyContext) GetRuleContext() antlr.RuleContext { @@ -700,12 +716,8 @@ func (p *ConfigParser) Key() (localctx IKeyContext) { p.EnterRule(localctx, 6, ConfigParserRULE_key) p.EnterOuterAlt(localctx, 1) { - p.SetState(38) - p.Match(ConfigParserSTRING) - if p.HasError() { - // Recognition error - abort rule - goto errorExit - } + p.SetState(40) + p.String_() } errorExit: @@ -729,8 +741,8 @@ type IValueContext interface { GetParser() antlr.Parser // Getter signatures - AllSTRING() []antlr.TerminalNode - STRING(i int) antlr.TerminalNode + AllString_() []IStringContext + String_(i int) IStringContext AllWHITESPACE() []antlr.TerminalNode WHITESPACE(i int) antlr.TerminalNode @@ -770,12 +782,45 @@ func NewValueContext(parser antlr.Parser, parent antlr.ParserRuleContext, invoki func (s *ValueContext) GetParser() antlr.Parser { return s.parser } -func (s *ValueContext) AllSTRING() []antlr.TerminalNode { - return s.GetTokens(ConfigParserSTRING) +func (s *ValueContext) AllString_() []IStringContext { + children := s.GetChildren() + len := 0 + for _, ctx := range children { + if _, ok := ctx.(IStringContext); ok { + len++ + } + } + + tst := make([]IStringContext, len) + i := 0 + for _, ctx := range children { + if t, ok := ctx.(IStringContext); ok { + tst[i] = t.(IStringContext) + i++ + } + } + + return tst } -func (s *ValueContext) STRING(i int) antlr.TerminalNode { - return s.GetToken(ConfigParserSTRING, i) +func (s *ValueContext) String_(i int) IStringContext { + var t antlr.RuleContext + j := 0 + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(IStringContext); ok { + if j == i { + t = ctx.(antlr.RuleContext) + break + } + j++ + } + } + + if t == nil { + return nil + } + + return t.(IStringContext) } func (s *ValueContext) AllWHITESPACE() []antlr.TerminalNode { @@ -814,7 +859,7 @@ func (p *ConfigParser) Value() (localctx IValueContext) { var _alt int p.EnterOuterAlt(localctx, 1) - p.SetState(44) + p.SetState(47) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -826,15 +871,11 @@ func (p *ConfigParser) Value() (localctx IValueContext) { for _alt != 2 && _alt != antlr.ATNInvalidAltNumber { if _alt == 1 { { - p.SetState(40) - p.Match(ConfigParserSTRING) - if p.HasError() { - // Recognition error - abort rule - goto errorExit - } + p.SetState(42) + p.String_() } { - p.SetState(41) + p.SetState(43) p.Match(ConfigParserWHITESPACE) if p.HasError() { // Recognition error - abort rule @@ -843,7 +884,7 @@ func (p *ConfigParser) Value() (localctx IValueContext) { } } - p.SetState(46) + p.SetState(49) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -853,25 +894,21 @@ func (p *ConfigParser) Value() (localctx IValueContext) { goto errorExit } } - p.SetState(48) + p.SetState(51) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit } _la = p.GetTokenStream().LA(1) - if _la == ConfigParserSTRING { + if _la == ConfigParserSTRING || _la == ConfigParserQUOTED_STRING { { - p.SetState(47) - p.Match(ConfigParserSTRING) - if p.HasError() { - // Recognition error - abort rule - goto errorExit - } + p.SetState(50) + p.String_() } } - p.SetState(51) + p.SetState(54) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -880,7 +917,7 @@ func (p *ConfigParser) Value() (localctx IValueContext) { if _la == ConfigParserWHITESPACE { { - p.SetState(50) + p.SetState(53) p.Match(ConfigParserWHITESPACE) if p.HasError() { // Recognition error - abort rule @@ -914,8 +951,8 @@ type ILeadingCommentContext interface { HASH() antlr.TerminalNode AllWHITESPACE() []antlr.TerminalNode WHITESPACE(i int) antlr.TerminalNode - AllSTRING() []antlr.TerminalNode - STRING(i int) antlr.TerminalNode + AllString_() []IStringContext + String_(i int) IStringContext // IsLeadingCommentContext differentiates from other interfaces. IsLeadingCommentContext() @@ -965,12 +1002,45 @@ func (s *LeadingCommentContext) WHITESPACE(i int) antlr.TerminalNode { return s.GetToken(ConfigParserWHITESPACE, i) } -func (s *LeadingCommentContext) AllSTRING() []antlr.TerminalNode { - return s.GetTokens(ConfigParserSTRING) +func (s *LeadingCommentContext) AllString_() []IStringContext { + children := s.GetChildren() + len := 0 + for _, ctx := range children { + if _, ok := ctx.(IStringContext); ok { + len++ + } + } + + tst := make([]IStringContext, len) + i := 0 + for _, ctx := range children { + if t, ok := ctx.(IStringContext); ok { + tst[i] = t.(IStringContext) + i++ + } + } + + return tst } -func (s *LeadingCommentContext) STRING(i int) antlr.TerminalNode { - return s.GetToken(ConfigParserSTRING, i) +func (s *LeadingCommentContext) String_(i int) IStringContext { + var t antlr.RuleContext + j := 0 + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(IStringContext); ok { + if j == i { + t = ctx.(antlr.RuleContext) + break + } + j++ + } + } + + if t == nil { + return nil + } + + return t.(IStringContext) } func (s *LeadingCommentContext) GetRuleContext() antlr.RuleContext { @@ -1000,14 +1070,14 @@ func (p *ConfigParser) LeadingComment() (localctx ILeadingCommentContext) { p.EnterOuterAlt(localctx, 1) { - p.SetState(53) + p.SetState(56) p.Match(ConfigParserHASH) if p.HasError() { // Recognition error - abort rule goto errorExit } } - p.SetState(55) + p.SetState(58) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -1016,7 +1086,7 @@ func (p *ConfigParser) LeadingComment() (localctx ILeadingCommentContext) { if _la == ConfigParserWHITESPACE { { - p.SetState(54) + p.SetState(57) p.Match(ConfigParserWHITESPACE) if p.HasError() { // Recognition error - abort rule @@ -1025,23 +1095,19 @@ func (p *ConfigParser) LeadingComment() (localctx ILeadingCommentContext) { } } - p.SetState(61) + p.SetState(64) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit } _la = p.GetTokenStream().LA(1) - for ok := true; ok; ok = _la == ConfigParserSTRING { + for ok := true; ok; ok = _la == ConfigParserSTRING || _la == ConfigParserQUOTED_STRING { { - p.SetState(57) - p.Match(ConfigParserSTRING) - if p.HasError() { - // Recognition error - abort rule - goto errorExit - } + p.SetState(60) + p.String_() } - p.SetState(59) + p.SetState(62) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -1050,7 +1116,7 @@ func (p *ConfigParser) LeadingComment() (localctx ILeadingCommentContext) { if _la == ConfigParserWHITESPACE { { - p.SetState(58) + p.SetState(61) p.Match(ConfigParserWHITESPACE) if p.HasError() { // Recognition error - abort rule @@ -1060,7 +1126,7 @@ func (p *ConfigParser) LeadingComment() (localctx ILeadingCommentContext) { } - p.SetState(63) + p.SetState(66) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -1080,3 +1146,109 @@ errorExit: return localctx goto errorExit // Trick to prevent compiler error if the label is not used } + +// IStringContext is an interface to support dynamic dispatch. +type IStringContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + + // Getter signatures + QUOTED_STRING() antlr.TerminalNode + STRING() antlr.TerminalNode + + // IsStringContext differentiates from other interfaces. + IsStringContext() +} + +type StringContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptyStringContext() *StringContext { + var p = new(StringContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_string + return p +} + +func InitEmptyStringContext(p *StringContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_string +} + +func (*StringContext) IsStringContext() {} + +func NewStringContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *StringContext { + var p = new(StringContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = ConfigParserRULE_string + + return p +} + +func (s *StringContext) GetParser() antlr.Parser { return s.parser } + +func (s *StringContext) QUOTED_STRING() antlr.TerminalNode { + return s.GetToken(ConfigParserQUOTED_STRING, 0) +} + +func (s *StringContext) STRING() antlr.TerminalNode { + return s.GetToken(ConfigParserSTRING, 0) +} + +func (s *StringContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *StringContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +func (s *StringContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.EnterString(s) + } +} + +func (s *StringContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.ExitString(s) + } +} + +func (p *ConfigParser) String_() (localctx IStringContext) { + localctx = NewStringContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 12, ConfigParserRULE_string) + var _la int + + p.EnterOuterAlt(localctx, 1) + { + p.SetState(68) + _la = p.GetTokenStream().LA(1) + + if !(_la == ConfigParserSTRING || _la == ConfigParserQUOTED_STRING) { + p.GetErrorHandler().RecoverInline(p) + } else { + p.GetErrorHandler().ReportMatch(p) + p.Consume() + } + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} diff --git a/handlers/ssh_config/ast/parser_test.go b/handlers/ssh_config/ast/parser_test.go new file mode 100644 index 0000000..dba0dc3 --- /dev/null +++ b/handlers/ssh_config/ast/parser_test.go @@ -0,0 +1,129 @@ +package ast + +import ( + "config-lsp/utils" + "testing" +) + +func TestSSHConfigParserExample( + t *testing.T, +) { + input := utils.Dedent(` +HostName 1.2.3.4 +User root +`) + p := NewSSHConfig() + errors := p.Parse(input) + + if len(errors) != 0 { + t.Fatalf("Expected no errors, got %v", errors) + } + + if !(p.Options.Size() == 2 && + len(utils.KeysOfMap(p.CommentLines)) == 0) { + t.Errorf("Expected 2 options and no comment lines, but got: %v, %v", p.Options, p.CommentLines) + } + + rawFirstEntry, _ := p.Options.Get(uint32(0)) + firstEntry := rawFirstEntry.(*SSHOption) + + if !(firstEntry.Value.Value == "HostName 1.2.3.4" && + firstEntry.LocationRange.Start.Line == 0 && + firstEntry.LocationRange.End.Line == 0 && + firstEntry.LocationRange.Start.Character == 0 && + firstEntry.LocationRange.End.Character == 16 && + firstEntry.Key.Value.Value == "HostName" && + firstEntry.Key.LocationRange.Start.Character == 0 && + firstEntry.Key.LocationRange.End.Character == 8 && + firstEntry.OptionValue.Value.Value == "1.2.3.4" && + firstEntry.OptionValue.LocationRange.Start.Character == 9 && + firstEntry.OptionValue.LocationRange.End.Character == 16) { + t.Errorf("Expected first entry to be HostName 1.2.3.4, but got: %v", firstEntry) + } + + rawSecondEntry, _ := p.Options.Get(uint32(1)) + secondEntry := rawSecondEntry.(*SSHOption) + + if !(secondEntry.Value.Value == "User root" && + secondEntry.LocationRange.Start.Line == 1 && + secondEntry.LocationRange.End.Line == 1 && + secondEntry.LocationRange.Start.Character == 0 && + secondEntry.LocationRange.End.Character == 9 && + secondEntry.Key.Value.Value == "User" && + secondEntry.Key.LocationRange.Start.Character == 0 && + secondEntry.Key.LocationRange.End.Character == 4 && + secondEntry.OptionValue.Value.Value == "root" && + secondEntry.OptionValue.LocationRange.Start.Character == 5 && + secondEntry.OptionValue.LocationRange.End.Character == 9) { + t.Errorf("Expected second entry to be User root, but got: %v", secondEntry) + } +} + +func TestMatchSimpleBlock( + t *testing.T, +) { + input := utils.Dedent(` +Hostname 1.2.3.4 + +Match originalhost "192.168.0.1" + User root +`) + p := NewSSHConfig() + errors := p.Parse(input) + + if len(errors) != 0 { + t.Fatalf("Expected no errors, got %v", errors) + } + + if !(p.Options.Size() == 2 && + len(utils.KeysOfMap(p.CommentLines)) == 0) { + t.Errorf("Expected 2 option and no comment lines, but got: %v entries, %v comment lines", p.Options.Size(), len(p.CommentLines)) + } + + rawFirstEntry, _ := p.Options.Get(uint32(0)) + firstEntry := rawFirstEntry.(*SSHOption) + + if !(firstEntry.Value.Value == "Hostname 1.2.3.4" && + firstEntry.LocationRange.Start.Line == 0 && + firstEntry.LocationRange.End.Line == 0 && + firstEntry.LocationRange.Start.Character == 0 && + firstEntry.LocationRange.End.Character == 16 && + firstEntry.Key.Value.Value == "Hostname" && + firstEntry.Key.LocationRange.Start.Character == 0 && + firstEntry.Key.LocationRange.End.Character == 8 && + firstEntry.OptionValue.Value.Value == "1.2.3.4" && + firstEntry.OptionValue.LocationRange.Start.Character == 9 && + firstEntry.OptionValue.LocationRange.End.Character == 16) { + t.Errorf("Expected first entry to be Hostname 1.2.3.4, but got: %v", firstEntry) + } + + rawSecondEntry, _ := p.Options.Get(uint32(2)) + secondEntry := rawSecondEntry.(*SSHMatchBlock) + + if !(secondEntry.Options.Size() == 1 && + secondEntry.LocationRange.Start.Line == 2 && + secondEntry.LocationRange.End.Line == 3 && + secondEntry.LocationRange.Start.Character == 0 && + secondEntry.LocationRange.End.Character == 10 && + secondEntry.MatchOption.OptionValue.Value.Raw == "originalhost \"192.168.0.1\"" && + secondEntry.MatchOption.OptionValue.LocationRange.Start.Character == 6 && + secondEntry.MatchOption.OptionValue.LocationRange.End.Character == 32) { + t.Errorf("Expected second entry to be Match originalhost \"192.168.0.1\", but got: %v; options amount: %d", secondEntry, secondEntry.Options.Size()) + } + + rawThirdEntry, _ := secondEntry.Options.Get(uint32(3)) + thirdEntry := rawThirdEntry.(*SSHOption) + if !(thirdEntry.Value.Raw == "\tUser root" && + thirdEntry.LocationRange.Start.Line == 3 && + thirdEntry.LocationRange.End.Line == 3 && + thirdEntry.LocationRange.Start.Character == 0 && + thirdEntry.LocationRange.End.Character == 10 && + thirdEntry.Key.Value.Value == "User" && + thirdEntry.Key.LocationRange.Start.Character == 1 && + thirdEntry.Key.LocationRange.End.Character == 5 && + thirdEntry.OptionValue.Value.Value == "root" && + thirdEntry.OptionValue.LocationRange.Start.Character == 6 && + thirdEntry.OptionValue.LocationRange.End.Character == 10) { + t.Errorf("Expected third entry to be User root, but got: %v", thirdEntry) + } +} diff --git a/handlers/ssh_config/ast/ssh_config.go b/handlers/ssh_config/ast/ssh_config.go index b3b5b6a..5757282 100644 --- a/handlers/ssh_config/ast/ssh_config.go +++ b/handlers/ssh_config/ast/ssh_config.go @@ -3,7 +3,7 @@ package ast import ( "config-lsp/common" commonparser "config-lsp/common/parser" - "config-lsp/common/parsers/openssh-match-parser" + "config-lsp/handlers/ssh_config/match-parser" "github.com/emirpasic/gods/maps/treemap" ) @@ -52,10 +52,7 @@ type SSHHostBlock struct { type SSHConfig struct { // [uint32]SSHOption -> line number -> *SSHEntry - RootOptions *treemap.Map - - MatchBlosks []*SSHMatchBlock - HostBlocks []*SSHHostBlock + Options *treemap.Map // [uint32]{} -> line number -> {} CommentLines map[uint32]struct{} diff --git a/handlers/ssh_config/ast/ssh_config_fields.go b/handlers/ssh_config/ast/ssh_config_fields.go index bd41296..30cf8d5 100644 --- a/handlers/ssh_config/ast/ssh_config_fields.go +++ b/handlers/ssh_config/ast/ssh_config_fields.go @@ -1 +1,77 @@ package ast + +import "config-lsp/common" + +type SSHBlockType uint8 + +const ( + SSHBlockTypeMatch SSHBlockType = iota + SSHBlockTypeHost +) + +type SSHBlock interface { + GetBlockType() SSHBlockType + AddOption(option *SSHOption) + SetEnd(common.Location) +} + +func (b *SSHMatchBlock) GetBlockType() SSHBlockType { + return SSHBlockTypeMatch +} + +func (b *SSHMatchBlock) AddOption(option *SSHOption) { + b.Options.Put(option.LocationRange.Start.Line, option) +} + +func (b *SSHMatchBlock) SetEnd(end common.Location) { + b.LocationRange.End = end +} + +func (b *SSHHostBlock) GetBlockType() SSHBlockType { + return SSHBlockTypeHost +} + +func (b *SSHHostBlock) AddOption(option *SSHOption) { + b.Others.Put(option.LocationRange.Start.Line, option) +} + +func (b *SSHHostBlock) SetEnd(end common.Location) { + b.LocationRange.End = end +} + +type SSHType uint8 + +const ( + SSHTypeOption SSHType = iota + SSHTypeMatch + SSHTypeHost +) + +type SSHEntry interface { + GetType() SSHType + GetOption() *SSHOption +} + +func (o *SSHOption) GetType() SSHType { + return SSHTypeOption +} + +func (o *SSHOption) GetOption() *SSHOption { + return o +} + +func (b *SSHMatchBlock) GetType() SSHType { + return SSHTypeMatch +} + +func (b *SSHMatchBlock) GetOption() *SSHOption { + return b.MatchOption +} + +func (b *SSHHostBlock) GetType() SSHType { + return SSHTypeHost +} + +func (b *SSHHostBlock) GetOption() *SSHOption { + return b.HostOption +} diff --git a/handlers/ssh_config/match-parser/Match.g4 b/handlers/ssh_config/match-parser/Match.g4 new file mode 100644 index 0000000..5b1744d --- /dev/null +++ b/handlers/ssh_config/match-parser/Match.g4 @@ -0,0 +1,45 @@ +grammar Match; + +root + : matchEntry? (WHITESPACE matchEntry?)* EOF + ; + +matchEntry + : criteria separator? values? + ; + +separator + : WHITESPACE + ; + +criteria + : string + ; + +values + : value? (COMMA value?)* + ; + +value + : string + ; + +string + : (QUOTED_STRING | STRING) + ; + +COMMA + : ',' + ; + +STRING + : ~(' ' | '\t' | '\r' | '\n' | '#' | ',')+ + ; + +WHITESPACE + : [ \t]+ + ; + +QUOTED_STRING + : '"' WHITESPACE? (STRING WHITESPACE)* STRING? ('"')? + ; diff --git a/handlers/ssh_config/match-parser/error-listener.go b/handlers/ssh_config/match-parser/error-listener.go new file mode 100644 index 0000000..e7264b0 --- /dev/null +++ b/handlers/ssh_config/match-parser/error-listener.go @@ -0,0 +1,45 @@ +package matchparser + +import ( + "config-lsp/common" + + "github.com/antlr4-go/antlr/v4" +) + +type errorListenerContext struct { + line uint32 +} + +func createErrorListener( + line uint32, +) errorListener { + return errorListener{ + Errors: make([]common.LSPError, 0), + context: errorListenerContext{ + line: line, + }, + } +} + +type errorListener struct { + *antlr.DefaultErrorListener + Errors []common.LSPError + context errorListenerContext +} + +func (d *errorListener) SyntaxError( + recognizer antlr.Recognizer, + offendingSymbol interface{}, + _ int, + character int, + message string, + error antlr.RecognitionException, +) { + line := d.context.line + d.Errors = append(d.Errors, common.LSPError{ + Range: common.CreateSingleCharRange(uint32(line), uint32(character)), + Err: common.SyntaxError{ + Message: message, + }, + }) +} diff --git a/handlers/ssh_config/match-parser/listener.go b/handlers/ssh_config/match-parser/listener.go new file mode 100644 index 0000000..ddf7640 --- /dev/null +++ b/handlers/ssh_config/match-parser/listener.go @@ -0,0 +1,132 @@ +package matchparser + +import ( + "config-lsp/common" + commonparser "config-lsp/common/parser" + parser "config-lsp/handlers/ssh_config/match-parser/parser" + "config-lsp/utils" + "errors" + "fmt" + "strings" +) + +func createMatchListenerContext( + line uint32, + startCharacter uint32, +) *matchListenerContext { + return &matchListenerContext{ + currentEntry: nil, + line: line, + startCharacter: startCharacter, + } +} + +type matchListenerContext struct { + currentEntry *MatchEntry + line uint32 + startCharacter uint32 +} + +func createListener( + match *Match, + context *matchListenerContext, +) matchParserListener { + return matchParserListener{ + match: match, + Errors: make([]common.LSPError, 0), + matchContext: context, + } +} + +type matchParserListener struct { + *parser.BaseMatchListener + match *Match + Errors []common.LSPError + matchContext *matchListenerContext +} + +func (s *matchParserListener) EnterMatchEntry(ctx *parser.MatchEntryContext) { + location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext).ShiftHorizontal(s.matchContext.startCharacter) + location.ChangeBothLines(s.matchContext.line) + + entry := &MatchEntry{ + LocationRange: location, + Value: commonparser.ParseRawString(ctx.GetText(), commonparser.FullFeatures), + } + + s.match.Entries = append(s.match.Entries, entry) + s.matchContext.currentEntry = entry +} + +func (s *matchParserListener) ExitMatchEntry(ctx *parser.MatchEntryContext) { + s.matchContext.currentEntry = nil +} + +var availableCriteria = map[string]MatchCriteriaType{ + string(MatchCriteriaTypeCanonical): MatchCriteriaTypeCanonical, + string(MatchCriteriaTypeFinal): MatchCriteriaTypeFinal, + string(MatchCriteriaTypeExec): MatchCriteriaTypeExec, + string(MatchCriteriaTypeLocalNetwork): MatchCriteriaTypeLocalNetwork, + string(MatchCriteriaTypeHost): MatchCriteriaTypeHost, + string(MatchCriteriaTypeOriginalHost): MatchCriteriaTypeOriginalHost, + string(MatchCriteriaTypeTagged): MatchCriteriaTypeTagged, + string(MatchCriteriaTypeUser): MatchCriteriaTypeUser, + string(MatchCriteriaTypeLocalUser): MatchCriteriaTypeLocalUser, +} + +func (s *matchParserListener) EnterCriteria(ctx *parser.CriteriaContext) { + location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext).ShiftHorizontal(s.matchContext.startCharacter) + location.ChangeBothLines(s.matchContext.line) + + value := commonparser.ParseRawString(ctx.GetText(), commonparser.FullFeatures) + + criteria, found := availableCriteria[value.Value] + + if !found { + s.Errors = append(s.Errors, common.LSPError{ + Range: location, + Err: errors.New(fmt.Sprintf("Unknown criteria: %s; It must be one of: %s", ctx.GetText(), strings.Join(utils.KeysOfMap(availableCriteria), ", "))), + }) + return + } + + s.matchContext.currentEntry.Criteria = MatchCriteria{ + LocationRange: location, + Type: criteria, + Value: value, + } +} + +func (s *matchParserListener) EnterSeparator(ctx *parser.SeparatorContext) { + location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext).ShiftHorizontal(s.matchContext.startCharacter) + location.ChangeBothLines(s.matchContext.line) + + value := commonparser.ParseRawString(ctx.GetText(), commonparser.FullFeatures) + + s.matchContext.currentEntry.Separator = &MatchSeparator{ + LocationRange: location, + Value: value, + } +} + +func (s *matchParserListener) EnterValues(ctx *parser.ValuesContext) { + location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext).ShiftHorizontal(s.matchContext.startCharacter) + location.ChangeBothLines(s.matchContext.line) + + s.matchContext.currentEntry.Values = &MatchValues{ + LocationRange: location, + Values: make([]*MatchValue, 0), + } +} + +func (s *matchParserListener) EnterValue(ctx *parser.ValueContext) { + location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext).ShiftHorizontal(s.matchContext.startCharacter) + location.ChangeBothLines(s.matchContext.line) + + value := &MatchValue{ + LocationRange: location, + Value: commonparser.ParseRawString(ctx.GetText(), commonparser.FullFeatures), + } + + s.matchContext.currentEntry.Values.Values = append(s.matchContext.currentEntry.Values.Values, value) +} diff --git a/handlers/ssh_config/match-parser/match_ast.go b/handlers/ssh_config/match-parser/match_ast.go new file mode 100644 index 0000000..a15c242 --- /dev/null +++ b/handlers/ssh_config/match-parser/match_ast.go @@ -0,0 +1,56 @@ +package matchparser + +import ( + "config-lsp/common" + commonparser "config-lsp/common/parser" +) + +type Match struct { + Entries []*MatchEntry +} + +type MatchCriteriaType string + +const ( + MatchCriteriaTypeCanonical MatchCriteriaType = "canonical" + MatchCriteriaTypeFinal MatchCriteriaType = "final" + MatchCriteriaTypeExec MatchCriteriaType = "exec" + MatchCriteriaTypeLocalNetwork MatchCriteriaType = "localnetwork" + MatchCriteriaTypeHost MatchCriteriaType = "host" + MatchCriteriaTypeOriginalHost MatchCriteriaType = "originalhost" + MatchCriteriaTypeTagged MatchCriteriaType = "tagged" + MatchCriteriaTypeUser MatchCriteriaType = "user" + MatchCriteriaTypeLocalUser MatchCriteriaType = "localuser" +) + +type MatchCriteria struct { + common.LocationRange + + Type MatchCriteriaType + Value commonparser.ParsedString +} + +type MatchSeparator struct { + common.LocationRange + Value commonparser.ParsedString +} + +type MatchValues struct { + common.LocationRange + + Values []*MatchValue +} + +type MatchEntry struct { + common.LocationRange + Value commonparser.ParsedString + + Criteria MatchCriteria + Separator *MatchSeparator + Values *MatchValues +} + +type MatchValue struct { + common.LocationRange + Value commonparser.ParsedString +} diff --git a/handlers/ssh_config/match-parser/match_fields.go b/handlers/ssh_config/match-parser/match_fields.go new file mode 100644 index 0000000..ab30390 --- /dev/null +++ b/handlers/ssh_config/match-parser/match_fields.go @@ -0,0 +1,62 @@ +package matchparser + +import ( + "config-lsp/common" + "slices" +) + +func (m Match) GetEntryAtPosition(position common.Position) *MatchEntry { + index, found := slices.BinarySearchFunc( + m.Entries, + position, + func(current *MatchEntry, target common.Position) int { + if current.IsPositionAfterEnd(target) { + return -1 + } + + if current.IsPositionBeforeStart(target) { + return 1 + } + + return 0 + }, + ) + + if !found { + return nil + } + + entry := m.Entries[index] + + return entry +} + +func (e MatchEntry) GetValueAtPosition(position common.Position) *MatchValue { + if e.Values == nil { + return nil + } + + index, found := slices.BinarySearchFunc( + e.Values.Values, + position, + func(current *MatchValue, target common.Position) int { + if current.IsPositionAfterEnd(target) { + return -1 + } + + if current.IsPositionBeforeStart(target) { + return 1 + } + + return 0 + }, + ) + + if !found { + return nil + } + + value := e.Values.Values[index] + + return value +} diff --git a/handlers/ssh_config/match-parser/parser.go b/handlers/ssh_config/match-parser/parser.go new file mode 100644 index 0000000..8007a99 --- /dev/null +++ b/handlers/ssh_config/match-parser/parser.go @@ -0,0 +1,54 @@ +package matchparser + +import ( + "config-lsp/common" + "config-lsp/handlers/ssh_config/match-parser/parser" + + "github.com/antlr4-go/antlr/v4" +) + +func NewMatch() *Match { + match := new(Match) + match.Clear() + + return match +} + +func (m *Match) Clear() { + m.Entries = make([]*MatchEntry, 0) +} + +func (m *Match) Parse( + input string, + line uint32, + startCharacter uint32, +) []common.LSPError { + context := createMatchListenerContext(line, startCharacter) + + stream := antlr.NewInputStream(input) + + lexerErrorListener := createErrorListener(context.line) + lexer := parser.NewMatchLexer(stream) + lexer.RemoveErrorListeners() + lexer.AddErrorListener(&lexerErrorListener) + + tokenStream := antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel) + + parserErrorListener := createErrorListener(context.line) + antlrParser := parser.NewMatchParser(tokenStream) + antlrParser.RemoveErrorListeners() + antlrParser.AddErrorListener(&parserErrorListener) + + listener := createListener(m, context) + antlr.ParseTreeWalkerDefault.Walk( + &listener, + antlrParser.Root(), + ) + + errors := lexerErrorListener.Errors + errors = append(errors, parserErrorListener.Errors...) + errors = append(errors, listener.Errors...) + + return errors + +} diff --git a/handlers/ssh_config/match-parser/parser/Match.interp b/handlers/ssh_config/match-parser/parser/Match.interp new file mode 100644 index 0000000..2843738 --- /dev/null +++ b/handlers/ssh_config/match-parser/parser/Match.interp @@ -0,0 +1,26 @@ +token literal names: +null +',' +null +null +null + +token symbolic names: +null +COMMA +STRING +WHITESPACE +QUOTED_STRING + +rule names: +root +matchEntry +separator +criteria +values +value +string + + +atn: +[4, 1, 4, 56, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 2, 5, 7, 5, 2, 6, 7, 6, 1, 0, 3, 0, 16, 8, 0, 1, 0, 1, 0, 3, 0, 20, 8, 0, 5, 0, 22, 8, 0, 10, 0, 12, 0, 25, 9, 0, 1, 0, 1, 0, 1, 1, 1, 1, 3, 1, 31, 8, 1, 1, 1, 3, 1, 34, 8, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, 3, 4, 41, 8, 4, 1, 4, 1, 4, 3, 4, 45, 8, 4, 5, 4, 47, 8, 4, 10, 4, 12, 4, 50, 9, 4, 1, 5, 1, 5, 1, 6, 1, 6, 1, 6, 0, 0, 7, 0, 2, 4, 6, 8, 10, 12, 0, 1, 2, 0, 2, 2, 4, 4, 56, 0, 15, 1, 0, 0, 0, 2, 28, 1, 0, 0, 0, 4, 35, 1, 0, 0, 0, 6, 37, 1, 0, 0, 0, 8, 40, 1, 0, 0, 0, 10, 51, 1, 0, 0, 0, 12, 53, 1, 0, 0, 0, 14, 16, 3, 2, 1, 0, 15, 14, 1, 0, 0, 0, 15, 16, 1, 0, 0, 0, 16, 23, 1, 0, 0, 0, 17, 19, 5, 3, 0, 0, 18, 20, 3, 2, 1, 0, 19, 18, 1, 0, 0, 0, 19, 20, 1, 0, 0, 0, 20, 22, 1, 0, 0, 0, 21, 17, 1, 0, 0, 0, 22, 25, 1, 0, 0, 0, 23, 21, 1, 0, 0, 0, 23, 24, 1, 0, 0, 0, 24, 26, 1, 0, 0, 0, 25, 23, 1, 0, 0, 0, 26, 27, 5, 0, 0, 1, 27, 1, 1, 0, 0, 0, 28, 30, 3, 6, 3, 0, 29, 31, 3, 4, 2, 0, 30, 29, 1, 0, 0, 0, 30, 31, 1, 0, 0, 0, 31, 33, 1, 0, 0, 0, 32, 34, 3, 8, 4, 0, 33, 32, 1, 0, 0, 0, 33, 34, 1, 0, 0, 0, 34, 3, 1, 0, 0, 0, 35, 36, 5, 3, 0, 0, 36, 5, 1, 0, 0, 0, 37, 38, 3, 12, 6, 0, 38, 7, 1, 0, 0, 0, 39, 41, 3, 10, 5, 0, 40, 39, 1, 0, 0, 0, 40, 41, 1, 0, 0, 0, 41, 48, 1, 0, 0, 0, 42, 44, 5, 1, 0, 0, 43, 45, 3, 10, 5, 0, 44, 43, 1, 0, 0, 0, 44, 45, 1, 0, 0, 0, 45, 47, 1, 0, 0, 0, 46, 42, 1, 0, 0, 0, 47, 50, 1, 0, 0, 0, 48, 46, 1, 0, 0, 0, 48, 49, 1, 0, 0, 0, 49, 9, 1, 0, 0, 0, 50, 48, 1, 0, 0, 0, 51, 52, 3, 12, 6, 0, 52, 11, 1, 0, 0, 0, 53, 54, 7, 0, 0, 0, 54, 13, 1, 0, 0, 0, 8, 15, 19, 23, 30, 33, 40, 44, 48] \ No newline at end of file diff --git a/handlers/ssh_config/match-parser/parser/Match.tokens b/handlers/ssh_config/match-parser/parser/Match.tokens new file mode 100644 index 0000000..c1682a1 --- /dev/null +++ b/handlers/ssh_config/match-parser/parser/Match.tokens @@ -0,0 +1,5 @@ +COMMA=1 +STRING=2 +WHITESPACE=3 +QUOTED_STRING=4 +','=1 diff --git a/handlers/ssh_config/match-parser/parser/MatchLexer.interp b/handlers/ssh_config/match-parser/parser/MatchLexer.interp new file mode 100644 index 0000000..c2bc7b6 --- /dev/null +++ b/handlers/ssh_config/match-parser/parser/MatchLexer.interp @@ -0,0 +1,29 @@ +token literal names: +null +',' +null +null +null + +token symbolic names: +null +COMMA +STRING +WHITESPACE +QUOTED_STRING + +rule names: +COMMA +STRING +WHITESPACE +QUOTED_STRING + +channel names: +DEFAULT_TOKEN_CHANNEL +HIDDEN + +mode names: +DEFAULT_MODE + +atn: +[4, 0, 4, 39, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 1, 0, 1, 0, 1, 1, 4, 1, 13, 8, 1, 11, 1, 12, 1, 14, 1, 2, 4, 2, 18, 8, 2, 11, 2, 12, 2, 19, 1, 3, 1, 3, 3, 3, 24, 8, 3, 1, 3, 1, 3, 1, 3, 5, 3, 29, 8, 3, 10, 3, 12, 3, 32, 9, 3, 1, 3, 3, 3, 35, 8, 3, 1, 3, 3, 3, 38, 8, 3, 0, 0, 4, 1, 1, 3, 2, 5, 3, 7, 4, 1, 0, 2, 5, 0, 9, 10, 13, 13, 32, 32, 35, 35, 44, 44, 2, 0, 9, 9, 32, 32, 44, 0, 1, 1, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, 5, 1, 0, 0, 0, 0, 7, 1, 0, 0, 0, 1, 9, 1, 0, 0, 0, 3, 12, 1, 0, 0, 0, 5, 17, 1, 0, 0, 0, 7, 21, 1, 0, 0, 0, 9, 10, 5, 44, 0, 0, 10, 2, 1, 0, 0, 0, 11, 13, 8, 0, 0, 0, 12, 11, 1, 0, 0, 0, 13, 14, 1, 0, 0, 0, 14, 12, 1, 0, 0, 0, 14, 15, 1, 0, 0, 0, 15, 4, 1, 0, 0, 0, 16, 18, 7, 1, 0, 0, 17, 16, 1, 0, 0, 0, 18, 19, 1, 0, 0, 0, 19, 17, 1, 0, 0, 0, 19, 20, 1, 0, 0, 0, 20, 6, 1, 0, 0, 0, 21, 23, 5, 34, 0, 0, 22, 24, 3, 5, 2, 0, 23, 22, 1, 0, 0, 0, 23, 24, 1, 0, 0, 0, 24, 30, 1, 0, 0, 0, 25, 26, 3, 3, 1, 0, 26, 27, 3, 5, 2, 0, 27, 29, 1, 0, 0, 0, 28, 25, 1, 0, 0, 0, 29, 32, 1, 0, 0, 0, 30, 28, 1, 0, 0, 0, 30, 31, 1, 0, 0, 0, 31, 34, 1, 0, 0, 0, 32, 30, 1, 0, 0, 0, 33, 35, 3, 3, 1, 0, 34, 33, 1, 0, 0, 0, 34, 35, 1, 0, 0, 0, 35, 37, 1, 0, 0, 0, 36, 38, 5, 34, 0, 0, 37, 36, 1, 0, 0, 0, 37, 38, 1, 0, 0, 0, 38, 8, 1, 0, 0, 0, 7, 0, 14, 19, 23, 30, 34, 37, 0] \ No newline at end of file diff --git a/handlers/ssh_config/match-parser/parser/MatchLexer.tokens b/handlers/ssh_config/match-parser/parser/MatchLexer.tokens new file mode 100644 index 0000000..c1682a1 --- /dev/null +++ b/handlers/ssh_config/match-parser/parser/MatchLexer.tokens @@ -0,0 +1,5 @@ +COMMA=1 +STRING=2 +WHITESPACE=3 +QUOTED_STRING=4 +','=1 diff --git a/handlers/ssh_config/match-parser/parser/match_base_listener.go b/handlers/ssh_config/match-parser/parser/match_base_listener.go new file mode 100644 index 0000000..4e4375d --- /dev/null +++ b/handlers/ssh_config/match-parser/parser/match_base_listener.go @@ -0,0 +1,64 @@ +// Code generated from Match.g4 by ANTLR 4.13.0. DO NOT EDIT. + +package parser // Match + +import "github.com/antlr4-go/antlr/v4" + +// BaseMatchListener is a complete listener for a parse tree produced by MatchParser. +type BaseMatchListener struct{} + +var _ MatchListener = &BaseMatchListener{} + +// VisitTerminal is called when a terminal node is visited. +func (s *BaseMatchListener) VisitTerminal(node antlr.TerminalNode) {} + +// VisitErrorNode is called when an error node is visited. +func (s *BaseMatchListener) VisitErrorNode(node antlr.ErrorNode) {} + +// EnterEveryRule is called when any rule is entered. +func (s *BaseMatchListener) EnterEveryRule(ctx antlr.ParserRuleContext) {} + +// ExitEveryRule is called when any rule is exited. +func (s *BaseMatchListener) ExitEveryRule(ctx antlr.ParserRuleContext) {} + +// EnterRoot is called when production root is entered. +func (s *BaseMatchListener) EnterRoot(ctx *RootContext) {} + +// ExitRoot is called when production root is exited. +func (s *BaseMatchListener) ExitRoot(ctx *RootContext) {} + +// EnterMatchEntry is called when production matchEntry is entered. +func (s *BaseMatchListener) EnterMatchEntry(ctx *MatchEntryContext) {} + +// ExitMatchEntry is called when production matchEntry is exited. +func (s *BaseMatchListener) ExitMatchEntry(ctx *MatchEntryContext) {} + +// EnterSeparator is called when production separator is entered. +func (s *BaseMatchListener) EnterSeparator(ctx *SeparatorContext) {} + +// ExitSeparator is called when production separator is exited. +func (s *BaseMatchListener) ExitSeparator(ctx *SeparatorContext) {} + +// EnterCriteria is called when production criteria is entered. +func (s *BaseMatchListener) EnterCriteria(ctx *CriteriaContext) {} + +// ExitCriteria is called when production criteria is exited. +func (s *BaseMatchListener) ExitCriteria(ctx *CriteriaContext) {} + +// EnterValues is called when production values is entered. +func (s *BaseMatchListener) EnterValues(ctx *ValuesContext) {} + +// ExitValues is called when production values is exited. +func (s *BaseMatchListener) ExitValues(ctx *ValuesContext) {} + +// EnterValue is called when production value is entered. +func (s *BaseMatchListener) EnterValue(ctx *ValueContext) {} + +// ExitValue is called when production value is exited. +func (s *BaseMatchListener) ExitValue(ctx *ValueContext) {} + +// EnterString is called when production string is entered. +func (s *BaseMatchListener) EnterString(ctx *StringContext) {} + +// ExitString is called when production string is exited. +func (s *BaseMatchListener) ExitString(ctx *StringContext) {} diff --git a/handlers/ssh_config/match-parser/parser/match_lexer.go b/handlers/ssh_config/match-parser/parser/match_lexer.go new file mode 100644 index 0000000..e4ab2ba --- /dev/null +++ b/handlers/ssh_config/match-parser/parser/match_lexer.go @@ -0,0 +1,118 @@ +// Code generated from Match.g4 by ANTLR 4.13.0. DO NOT EDIT. + +package parser + +import ( + "fmt" + "github.com/antlr4-go/antlr/v4" + "sync" + "unicode" +) + +// Suppress unused import error +var _ = fmt.Printf +var _ = sync.Once{} +var _ = unicode.IsLetter + +type MatchLexer struct { + *antlr.BaseLexer + channelNames []string + modeNames []string + // TODO: EOF string +} + +var MatchLexerLexerStaticData struct { + once sync.Once + serializedATN []int32 + ChannelNames []string + ModeNames []string + LiteralNames []string + SymbolicNames []string + RuleNames []string + PredictionContextCache *antlr.PredictionContextCache + atn *antlr.ATN + decisionToDFA []*antlr.DFA +} + +func matchlexerLexerInit() { + staticData := &MatchLexerLexerStaticData + staticData.ChannelNames = []string{ + "DEFAULT_TOKEN_CHANNEL", "HIDDEN", + } + staticData.ModeNames = []string{ + "DEFAULT_MODE", + } + staticData.LiteralNames = []string{ + "", "','", + } + staticData.SymbolicNames = []string{ + "", "COMMA", "STRING", "WHITESPACE", "QUOTED_STRING", + } + staticData.RuleNames = []string{ + "COMMA", "STRING", "WHITESPACE", "QUOTED_STRING", + } + staticData.PredictionContextCache = antlr.NewPredictionContextCache() + staticData.serializedATN = []int32{ + 4, 0, 4, 39, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 1, + 0, 1, 0, 1, 1, 4, 1, 13, 8, 1, 11, 1, 12, 1, 14, 1, 2, 4, 2, 18, 8, 2, + 11, 2, 12, 2, 19, 1, 3, 1, 3, 3, 3, 24, 8, 3, 1, 3, 1, 3, 1, 3, 5, 3, 29, + 8, 3, 10, 3, 12, 3, 32, 9, 3, 1, 3, 3, 3, 35, 8, 3, 1, 3, 3, 3, 38, 8, + 3, 0, 0, 4, 1, 1, 3, 2, 5, 3, 7, 4, 1, 0, 2, 5, 0, 9, 10, 13, 13, 32, 32, + 35, 35, 44, 44, 2, 0, 9, 9, 32, 32, 44, 0, 1, 1, 0, 0, 0, 0, 3, 1, 0, 0, + 0, 0, 5, 1, 0, 0, 0, 0, 7, 1, 0, 0, 0, 1, 9, 1, 0, 0, 0, 3, 12, 1, 0, 0, + 0, 5, 17, 1, 0, 0, 0, 7, 21, 1, 0, 0, 0, 9, 10, 5, 44, 0, 0, 10, 2, 1, + 0, 0, 0, 11, 13, 8, 0, 0, 0, 12, 11, 1, 0, 0, 0, 13, 14, 1, 0, 0, 0, 14, + 12, 1, 0, 0, 0, 14, 15, 1, 0, 0, 0, 15, 4, 1, 0, 0, 0, 16, 18, 7, 1, 0, + 0, 17, 16, 1, 0, 0, 0, 18, 19, 1, 0, 0, 0, 19, 17, 1, 0, 0, 0, 19, 20, + 1, 0, 0, 0, 20, 6, 1, 0, 0, 0, 21, 23, 5, 34, 0, 0, 22, 24, 3, 5, 2, 0, + 23, 22, 1, 0, 0, 0, 23, 24, 1, 0, 0, 0, 24, 30, 1, 0, 0, 0, 25, 26, 3, + 3, 1, 0, 26, 27, 3, 5, 2, 0, 27, 29, 1, 0, 0, 0, 28, 25, 1, 0, 0, 0, 29, + 32, 1, 0, 0, 0, 30, 28, 1, 0, 0, 0, 30, 31, 1, 0, 0, 0, 31, 34, 1, 0, 0, + 0, 32, 30, 1, 0, 0, 0, 33, 35, 3, 3, 1, 0, 34, 33, 1, 0, 0, 0, 34, 35, + 1, 0, 0, 0, 35, 37, 1, 0, 0, 0, 36, 38, 5, 34, 0, 0, 37, 36, 1, 0, 0, 0, + 37, 38, 1, 0, 0, 0, 38, 8, 1, 0, 0, 0, 7, 0, 14, 19, 23, 30, 34, 37, 0, + } + deserializer := antlr.NewATNDeserializer(nil) + staticData.atn = deserializer.Deserialize(staticData.serializedATN) + atn := staticData.atn + staticData.decisionToDFA = make([]*antlr.DFA, len(atn.DecisionToState)) + decisionToDFA := staticData.decisionToDFA + for index, state := range atn.DecisionToState { + decisionToDFA[index] = antlr.NewDFA(state, index) + } +} + +// MatchLexerInit initializes any static state used to implement MatchLexer. By default the +// static state used to implement the lexer is lazily initialized during the first call to +// NewMatchLexer(). You can call this function if you wish to initialize the static state ahead +// of time. +func MatchLexerInit() { + staticData := &MatchLexerLexerStaticData + staticData.once.Do(matchlexerLexerInit) +} + +// NewMatchLexer produces a new lexer instance for the optional input antlr.CharStream. +func NewMatchLexer(input antlr.CharStream) *MatchLexer { + MatchLexerInit() + l := new(MatchLexer) + l.BaseLexer = antlr.NewBaseLexer(input) + staticData := &MatchLexerLexerStaticData + l.Interpreter = antlr.NewLexerATNSimulator(l, staticData.atn, staticData.decisionToDFA, staticData.PredictionContextCache) + l.channelNames = staticData.ChannelNames + l.modeNames = staticData.ModeNames + l.RuleNames = staticData.RuleNames + l.LiteralNames = staticData.LiteralNames + l.SymbolicNames = staticData.SymbolicNames + l.GrammarFileName = "Match.g4" + // TODO: l.EOF = antlr.TokenEOF + + return l +} + +// MatchLexer tokens. +const ( + MatchLexerCOMMA = 1 + MatchLexerSTRING = 2 + MatchLexerWHITESPACE = 3 + MatchLexerQUOTED_STRING = 4 +) diff --git a/handlers/ssh_config/match-parser/parser/match_listener.go b/handlers/ssh_config/match-parser/parser/match_listener.go new file mode 100644 index 0000000..496f3a7 --- /dev/null +++ b/handlers/ssh_config/match-parser/parser/match_listener.go @@ -0,0 +1,52 @@ +// Code generated from Match.g4 by ANTLR 4.13.0. DO NOT EDIT. + +package parser // Match + +import "github.com/antlr4-go/antlr/v4" + +// MatchListener is a complete listener for a parse tree produced by MatchParser. +type MatchListener interface { + antlr.ParseTreeListener + + // EnterRoot is called when entering the root production. + EnterRoot(c *RootContext) + + // EnterMatchEntry is called when entering the matchEntry production. + EnterMatchEntry(c *MatchEntryContext) + + // EnterSeparator is called when entering the separator production. + EnterSeparator(c *SeparatorContext) + + // EnterCriteria is called when entering the criteria production. + EnterCriteria(c *CriteriaContext) + + // EnterValues is called when entering the values production. + EnterValues(c *ValuesContext) + + // EnterValue is called when entering the value production. + EnterValue(c *ValueContext) + + // EnterString is called when entering the string production. + EnterString(c *StringContext) + + // ExitRoot is called when exiting the root production. + ExitRoot(c *RootContext) + + // ExitMatchEntry is called when exiting the matchEntry production. + ExitMatchEntry(c *MatchEntryContext) + + // ExitSeparator is called when exiting the separator production. + ExitSeparator(c *SeparatorContext) + + // ExitCriteria is called when exiting the criteria production. + ExitCriteria(c *CriteriaContext) + + // ExitValues is called when exiting the values production. + ExitValues(c *ValuesContext) + + // ExitValue is called when exiting the value production. + ExitValue(c *ValueContext) + + // ExitString is called when exiting the string production. + ExitString(c *StringContext) +} diff --git a/handlers/ssh_config/match-parser/parser/match_parser.go b/handlers/ssh_config/match-parser/parser/match_parser.go new file mode 100644 index 0000000..1ba0752 --- /dev/null +++ b/handlers/ssh_config/match-parser/parser/match_parser.go @@ -0,0 +1,1087 @@ +// Code generated from Match.g4 by ANTLR 4.13.0. DO NOT EDIT. + +package parser // Match + +import ( + "fmt" + "strconv" + "sync" + + "github.com/antlr4-go/antlr/v4" +) + +// Suppress unused import errors +var _ = fmt.Printf +var _ = strconv.Itoa +var _ = sync.Once{} + +type MatchParser struct { + *antlr.BaseParser +} + +var MatchParserStaticData struct { + once sync.Once + serializedATN []int32 + LiteralNames []string + SymbolicNames []string + RuleNames []string + PredictionContextCache *antlr.PredictionContextCache + atn *antlr.ATN + decisionToDFA []*antlr.DFA +} + +func matchParserInit() { + staticData := &MatchParserStaticData + staticData.LiteralNames = []string{ + "", "','", + } + staticData.SymbolicNames = []string{ + "", "COMMA", "STRING", "WHITESPACE", "QUOTED_STRING", + } + staticData.RuleNames = []string{ + "root", "matchEntry", "separator", "criteria", "values", "value", "string", + } + staticData.PredictionContextCache = antlr.NewPredictionContextCache() + staticData.serializedATN = []int32{ + 4, 1, 4, 56, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, + 2, 5, 7, 5, 2, 6, 7, 6, 1, 0, 3, 0, 16, 8, 0, 1, 0, 1, 0, 3, 0, 20, 8, + 0, 5, 0, 22, 8, 0, 10, 0, 12, 0, 25, 9, 0, 1, 0, 1, 0, 1, 1, 1, 1, 3, 1, + 31, 8, 1, 1, 1, 3, 1, 34, 8, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, 3, 4, 41, + 8, 4, 1, 4, 1, 4, 3, 4, 45, 8, 4, 5, 4, 47, 8, 4, 10, 4, 12, 4, 50, 9, + 4, 1, 5, 1, 5, 1, 6, 1, 6, 1, 6, 0, 0, 7, 0, 2, 4, 6, 8, 10, 12, 0, 1, + 2, 0, 2, 2, 4, 4, 56, 0, 15, 1, 0, 0, 0, 2, 28, 1, 0, 0, 0, 4, 35, 1, 0, + 0, 0, 6, 37, 1, 0, 0, 0, 8, 40, 1, 0, 0, 0, 10, 51, 1, 0, 0, 0, 12, 53, + 1, 0, 0, 0, 14, 16, 3, 2, 1, 0, 15, 14, 1, 0, 0, 0, 15, 16, 1, 0, 0, 0, + 16, 23, 1, 0, 0, 0, 17, 19, 5, 3, 0, 0, 18, 20, 3, 2, 1, 0, 19, 18, 1, + 0, 0, 0, 19, 20, 1, 0, 0, 0, 20, 22, 1, 0, 0, 0, 21, 17, 1, 0, 0, 0, 22, + 25, 1, 0, 0, 0, 23, 21, 1, 0, 0, 0, 23, 24, 1, 0, 0, 0, 24, 26, 1, 0, 0, + 0, 25, 23, 1, 0, 0, 0, 26, 27, 5, 0, 0, 1, 27, 1, 1, 0, 0, 0, 28, 30, 3, + 6, 3, 0, 29, 31, 3, 4, 2, 0, 30, 29, 1, 0, 0, 0, 30, 31, 1, 0, 0, 0, 31, + 33, 1, 0, 0, 0, 32, 34, 3, 8, 4, 0, 33, 32, 1, 0, 0, 0, 33, 34, 1, 0, 0, + 0, 34, 3, 1, 0, 0, 0, 35, 36, 5, 3, 0, 0, 36, 5, 1, 0, 0, 0, 37, 38, 3, + 12, 6, 0, 38, 7, 1, 0, 0, 0, 39, 41, 3, 10, 5, 0, 40, 39, 1, 0, 0, 0, 40, + 41, 1, 0, 0, 0, 41, 48, 1, 0, 0, 0, 42, 44, 5, 1, 0, 0, 43, 45, 3, 10, + 5, 0, 44, 43, 1, 0, 0, 0, 44, 45, 1, 0, 0, 0, 45, 47, 1, 0, 0, 0, 46, 42, + 1, 0, 0, 0, 47, 50, 1, 0, 0, 0, 48, 46, 1, 0, 0, 0, 48, 49, 1, 0, 0, 0, + 49, 9, 1, 0, 0, 0, 50, 48, 1, 0, 0, 0, 51, 52, 3, 12, 6, 0, 52, 11, 1, + 0, 0, 0, 53, 54, 7, 0, 0, 0, 54, 13, 1, 0, 0, 0, 8, 15, 19, 23, 30, 33, + 40, 44, 48, + } + deserializer := antlr.NewATNDeserializer(nil) + staticData.atn = deserializer.Deserialize(staticData.serializedATN) + atn := staticData.atn + staticData.decisionToDFA = make([]*antlr.DFA, len(atn.DecisionToState)) + decisionToDFA := staticData.decisionToDFA + for index, state := range atn.DecisionToState { + decisionToDFA[index] = antlr.NewDFA(state, index) + } +} + +// MatchParserInit initializes any static state used to implement MatchParser. By default the +// static state used to implement the parser is lazily initialized during the first call to +// NewMatchParser(). You can call this function if you wish to initialize the static state ahead +// of time. +func MatchParserInit() { + staticData := &MatchParserStaticData + staticData.once.Do(matchParserInit) +} + +// NewMatchParser produces a new parser instance for the optional input antlr.TokenStream. +func NewMatchParser(input antlr.TokenStream) *MatchParser { + MatchParserInit() + this := new(MatchParser) + this.BaseParser = antlr.NewBaseParser(input) + staticData := &MatchParserStaticData + this.Interpreter = antlr.NewParserATNSimulator(this, staticData.atn, staticData.decisionToDFA, staticData.PredictionContextCache) + this.RuleNames = staticData.RuleNames + this.LiteralNames = staticData.LiteralNames + this.SymbolicNames = staticData.SymbolicNames + this.GrammarFileName = "Match.g4" + + return this +} + +// MatchParser tokens. +const ( + MatchParserEOF = antlr.TokenEOF + MatchParserCOMMA = 1 + MatchParserSTRING = 2 + MatchParserWHITESPACE = 3 + MatchParserQUOTED_STRING = 4 +) + +// MatchParser rules. +const ( + MatchParserRULE_root = 0 + MatchParserRULE_matchEntry = 1 + MatchParserRULE_separator = 2 + MatchParserRULE_criteria = 3 + MatchParserRULE_values = 4 + MatchParserRULE_value = 5 + MatchParserRULE_string = 6 +) + +// IRootContext is an interface to support dynamic dispatch. +type IRootContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + + // Getter signatures + EOF() antlr.TerminalNode + AllMatchEntry() []IMatchEntryContext + MatchEntry(i int) IMatchEntryContext + AllWHITESPACE() []antlr.TerminalNode + WHITESPACE(i int) antlr.TerminalNode + + // IsRootContext differentiates from other interfaces. + IsRootContext() +} + +type RootContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptyRootContext() *RootContext { + var p = new(RootContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = MatchParserRULE_root + return p +} + +func InitEmptyRootContext(p *RootContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = MatchParserRULE_root +} + +func (*RootContext) IsRootContext() {} + +func NewRootContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *RootContext { + var p = new(RootContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = MatchParserRULE_root + + return p +} + +func (s *RootContext) GetParser() antlr.Parser { return s.parser } + +func (s *RootContext) EOF() antlr.TerminalNode { + return s.GetToken(MatchParserEOF, 0) +} + +func (s *RootContext) AllMatchEntry() []IMatchEntryContext { + children := s.GetChildren() + len := 0 + for _, ctx := range children { + if _, ok := ctx.(IMatchEntryContext); ok { + len++ + } + } + + tst := make([]IMatchEntryContext, len) + i := 0 + for _, ctx := range children { + if t, ok := ctx.(IMatchEntryContext); ok { + tst[i] = t.(IMatchEntryContext) + i++ + } + } + + return tst +} + +func (s *RootContext) MatchEntry(i int) IMatchEntryContext { + var t antlr.RuleContext + j := 0 + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(IMatchEntryContext); ok { + if j == i { + t = ctx.(antlr.RuleContext) + break + } + j++ + } + } + + if t == nil { + return nil + } + + return t.(IMatchEntryContext) +} + +func (s *RootContext) AllWHITESPACE() []antlr.TerminalNode { + return s.GetTokens(MatchParserWHITESPACE) +} + +func (s *RootContext) WHITESPACE(i int) antlr.TerminalNode { + return s.GetToken(MatchParserWHITESPACE, i) +} + +func (s *RootContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *RootContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +func (s *RootContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(MatchListener); ok { + listenerT.EnterRoot(s) + } +} + +func (s *RootContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(MatchListener); ok { + listenerT.ExitRoot(s) + } +} + +func (p *MatchParser) Root() (localctx IRootContext) { + localctx = NewRootContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 0, MatchParserRULE_root) + var _la int + + p.EnterOuterAlt(localctx, 1) + p.SetState(15) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + if _la == MatchParserSTRING || _la == MatchParserQUOTED_STRING { + { + p.SetState(14) + p.MatchEntry() + } + + } + p.SetState(23) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + for _la == MatchParserWHITESPACE { + { + p.SetState(17) + p.Match(MatchParserWHITESPACE) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + p.SetState(19) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + if _la == MatchParserSTRING || _la == MatchParserQUOTED_STRING { + { + p.SetState(18) + p.MatchEntry() + } + + } + + p.SetState(25) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + } + { + p.SetState(26) + p.Match(MatchParserEOF) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} + +// IMatchEntryContext is an interface to support dynamic dispatch. +type IMatchEntryContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + + // Getter signatures + Criteria() ICriteriaContext + Separator() ISeparatorContext + Values() IValuesContext + + // IsMatchEntryContext differentiates from other interfaces. + IsMatchEntryContext() +} + +type MatchEntryContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptyMatchEntryContext() *MatchEntryContext { + var p = new(MatchEntryContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = MatchParserRULE_matchEntry + return p +} + +func InitEmptyMatchEntryContext(p *MatchEntryContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = MatchParserRULE_matchEntry +} + +func (*MatchEntryContext) IsMatchEntryContext() {} + +func NewMatchEntryContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *MatchEntryContext { + var p = new(MatchEntryContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = MatchParserRULE_matchEntry + + return p +} + +func (s *MatchEntryContext) GetParser() antlr.Parser { return s.parser } + +func (s *MatchEntryContext) Criteria() ICriteriaContext { + var t antlr.RuleContext + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(ICriteriaContext); ok { + t = ctx.(antlr.RuleContext) + break + } + } + + if t == nil { + return nil + } + + return t.(ICriteriaContext) +} + +func (s *MatchEntryContext) Separator() ISeparatorContext { + var t antlr.RuleContext + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(ISeparatorContext); ok { + t = ctx.(antlr.RuleContext) + break + } + } + + if t == nil { + return nil + } + + return t.(ISeparatorContext) +} + +func (s *MatchEntryContext) Values() IValuesContext { + var t antlr.RuleContext + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(IValuesContext); ok { + t = ctx.(antlr.RuleContext) + break + } + } + + if t == nil { + return nil + } + + return t.(IValuesContext) +} + +func (s *MatchEntryContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *MatchEntryContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +func (s *MatchEntryContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(MatchListener); ok { + listenerT.EnterMatchEntry(s) + } +} + +func (s *MatchEntryContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(MatchListener); ok { + listenerT.ExitMatchEntry(s) + } +} + +func (p *MatchParser) MatchEntry() (localctx IMatchEntryContext) { + localctx = NewMatchEntryContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 2, MatchParserRULE_matchEntry) + p.EnterOuterAlt(localctx, 1) + { + p.SetState(28) + p.Criteria() + } + p.SetState(30) + p.GetErrorHandler().Sync(p) + + if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 3, p.GetParserRuleContext()) == 1 { + { + p.SetState(29) + p.Separator() + } + + } else if p.HasError() { // JIM + goto errorExit + } + p.SetState(33) + p.GetErrorHandler().Sync(p) + + if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 4, p.GetParserRuleContext()) == 1 { + { + p.SetState(32) + p.Values() + } + + } else if p.HasError() { // JIM + goto errorExit + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} + +// ISeparatorContext is an interface to support dynamic dispatch. +type ISeparatorContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + + // Getter signatures + WHITESPACE() antlr.TerminalNode + + // IsSeparatorContext differentiates from other interfaces. + IsSeparatorContext() +} + +type SeparatorContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptySeparatorContext() *SeparatorContext { + var p = new(SeparatorContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = MatchParserRULE_separator + return p +} + +func InitEmptySeparatorContext(p *SeparatorContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = MatchParserRULE_separator +} + +func (*SeparatorContext) IsSeparatorContext() {} + +func NewSeparatorContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *SeparatorContext { + var p = new(SeparatorContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = MatchParserRULE_separator + + return p +} + +func (s *SeparatorContext) GetParser() antlr.Parser { return s.parser } + +func (s *SeparatorContext) WHITESPACE() antlr.TerminalNode { + return s.GetToken(MatchParserWHITESPACE, 0) +} + +func (s *SeparatorContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *SeparatorContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +func (s *SeparatorContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(MatchListener); ok { + listenerT.EnterSeparator(s) + } +} + +func (s *SeparatorContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(MatchListener); ok { + listenerT.ExitSeparator(s) + } +} + +func (p *MatchParser) Separator() (localctx ISeparatorContext) { + localctx = NewSeparatorContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 4, MatchParserRULE_separator) + p.EnterOuterAlt(localctx, 1) + { + p.SetState(35) + p.Match(MatchParserWHITESPACE) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} + +// ICriteriaContext is an interface to support dynamic dispatch. +type ICriteriaContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + + // Getter signatures + String_() IStringContext + + // IsCriteriaContext differentiates from other interfaces. + IsCriteriaContext() +} + +type CriteriaContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptyCriteriaContext() *CriteriaContext { + var p = new(CriteriaContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = MatchParserRULE_criteria + return p +} + +func InitEmptyCriteriaContext(p *CriteriaContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = MatchParserRULE_criteria +} + +func (*CriteriaContext) IsCriteriaContext() {} + +func NewCriteriaContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *CriteriaContext { + var p = new(CriteriaContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = MatchParserRULE_criteria + + return p +} + +func (s *CriteriaContext) GetParser() antlr.Parser { return s.parser } + +func (s *CriteriaContext) String_() IStringContext { + var t antlr.RuleContext + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(IStringContext); ok { + t = ctx.(antlr.RuleContext) + break + } + } + + if t == nil { + return nil + } + + return t.(IStringContext) +} + +func (s *CriteriaContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *CriteriaContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +func (s *CriteriaContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(MatchListener); ok { + listenerT.EnterCriteria(s) + } +} + +func (s *CriteriaContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(MatchListener); ok { + listenerT.ExitCriteria(s) + } +} + +func (p *MatchParser) Criteria() (localctx ICriteriaContext) { + localctx = NewCriteriaContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 6, MatchParserRULE_criteria) + p.EnterOuterAlt(localctx, 1) + { + p.SetState(37) + p.String_() + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} + +// IValuesContext is an interface to support dynamic dispatch. +type IValuesContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + + // Getter signatures + AllValue() []IValueContext + Value(i int) IValueContext + AllCOMMA() []antlr.TerminalNode + COMMA(i int) antlr.TerminalNode + + // IsValuesContext differentiates from other interfaces. + IsValuesContext() +} + +type ValuesContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptyValuesContext() *ValuesContext { + var p = new(ValuesContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = MatchParserRULE_values + return p +} + +func InitEmptyValuesContext(p *ValuesContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = MatchParserRULE_values +} + +func (*ValuesContext) IsValuesContext() {} + +func NewValuesContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *ValuesContext { + var p = new(ValuesContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = MatchParserRULE_values + + return p +} + +func (s *ValuesContext) GetParser() antlr.Parser { return s.parser } + +func (s *ValuesContext) AllValue() []IValueContext { + children := s.GetChildren() + len := 0 + for _, ctx := range children { + if _, ok := ctx.(IValueContext); ok { + len++ + } + } + + tst := make([]IValueContext, len) + i := 0 + for _, ctx := range children { + if t, ok := ctx.(IValueContext); ok { + tst[i] = t.(IValueContext) + i++ + } + } + + return tst +} + +func (s *ValuesContext) Value(i int) IValueContext { + var t antlr.RuleContext + j := 0 + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(IValueContext); ok { + if j == i { + t = ctx.(antlr.RuleContext) + break + } + j++ + } + } + + if t == nil { + return nil + } + + return t.(IValueContext) +} + +func (s *ValuesContext) AllCOMMA() []antlr.TerminalNode { + return s.GetTokens(MatchParserCOMMA) +} + +func (s *ValuesContext) COMMA(i int) antlr.TerminalNode { + return s.GetToken(MatchParserCOMMA, i) +} + +func (s *ValuesContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *ValuesContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +func (s *ValuesContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(MatchListener); ok { + listenerT.EnterValues(s) + } +} + +func (s *ValuesContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(MatchListener); ok { + listenerT.ExitValues(s) + } +} + +func (p *MatchParser) Values() (localctx IValuesContext) { + localctx = NewValuesContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 8, MatchParserRULE_values) + var _la int + + p.EnterOuterAlt(localctx, 1) + p.SetState(40) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + if _la == MatchParserSTRING || _la == MatchParserQUOTED_STRING { + { + p.SetState(39) + p.Value() + } + + } + p.SetState(48) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + for _la == MatchParserCOMMA { + { + p.SetState(42) + p.Match(MatchParserCOMMA) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + p.SetState(44) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + if _la == MatchParserSTRING || _la == MatchParserQUOTED_STRING { + { + p.SetState(43) + p.Value() + } + + } + + p.SetState(50) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} + +// IValueContext is an interface to support dynamic dispatch. +type IValueContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + + // Getter signatures + String_() IStringContext + + // IsValueContext differentiates from other interfaces. + IsValueContext() +} + +type ValueContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptyValueContext() *ValueContext { + var p = new(ValueContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = MatchParserRULE_value + return p +} + +func InitEmptyValueContext(p *ValueContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = MatchParserRULE_value +} + +func (*ValueContext) IsValueContext() {} + +func NewValueContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *ValueContext { + var p = new(ValueContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = MatchParserRULE_value + + return p +} + +func (s *ValueContext) GetParser() antlr.Parser { return s.parser } + +func (s *ValueContext) String_() IStringContext { + var t antlr.RuleContext + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(IStringContext); ok { + t = ctx.(antlr.RuleContext) + break + } + } + + if t == nil { + return nil + } + + return t.(IStringContext) +} + +func (s *ValueContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *ValueContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +func (s *ValueContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(MatchListener); ok { + listenerT.EnterValue(s) + } +} + +func (s *ValueContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(MatchListener); ok { + listenerT.ExitValue(s) + } +} + +func (p *MatchParser) Value() (localctx IValueContext) { + localctx = NewValueContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 10, MatchParserRULE_value) + p.EnterOuterAlt(localctx, 1) + { + p.SetState(51) + p.String_() + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} + +// IStringContext is an interface to support dynamic dispatch. +type IStringContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + + // Getter signatures + QUOTED_STRING() antlr.TerminalNode + STRING() antlr.TerminalNode + + // IsStringContext differentiates from other interfaces. + IsStringContext() +} + +type StringContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptyStringContext() *StringContext { + var p = new(StringContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = MatchParserRULE_string + return p +} + +func InitEmptyStringContext(p *StringContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = MatchParserRULE_string +} + +func (*StringContext) IsStringContext() {} + +func NewStringContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *StringContext { + var p = new(StringContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = MatchParserRULE_string + + return p +} + +func (s *StringContext) GetParser() antlr.Parser { return s.parser } + +func (s *StringContext) QUOTED_STRING() antlr.TerminalNode { + return s.GetToken(MatchParserQUOTED_STRING, 0) +} + +func (s *StringContext) STRING() antlr.TerminalNode { + return s.GetToken(MatchParserSTRING, 0) +} + +func (s *StringContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *StringContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +func (s *StringContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(MatchListener); ok { + listenerT.EnterString(s) + } +} + +func (s *StringContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(MatchListener); ok { + listenerT.ExitString(s) + } +} + +func (p *MatchParser) String_() (localctx IStringContext) { + localctx = NewStringContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 12, MatchParserRULE_string) + var _la int + + p.EnterOuterAlt(localctx, 1) + { + p.SetState(53) + _la = p.GetTokenStream().LA(1) + + if !(_la == MatchParserSTRING || _la == MatchParserQUOTED_STRING) { + p.GetErrorHandler().RecoverInline(p) + } else { + p.GetErrorHandler().ReportMatch(p) + p.Consume() + } + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} diff --git a/handlers/ssh_config/match-parser/parser_test.go b/handlers/ssh_config/match-parser/parser_test.go new file mode 100644 index 0000000..d308bc8 --- /dev/null +++ b/handlers/ssh_config/match-parser/parser_test.go @@ -0,0 +1,143 @@ +package matchparser + +import ( + "testing" +) + +func TestSimpleExample( + t *testing.T, +) { + offset := uint32(5) + input := "originalhost example.com user root" + + match := NewMatch() + errors := match.Parse(input, 32, offset) + + if len(errors) > 0 { + t.Fatalf("Expected no errors, but got %v", errors) + } + + if !(len(match.Entries) == 2) { + t.Errorf("Expected 2 entries, but got %v", len(match.Entries)) + } + + if !(match.Entries[0].Criteria.Type == MatchCriteriaTypeOriginalHost) { + t.Errorf("Expected OriginalHost, but got %v", match.Entries[0]) + } + + if !(match.Entries[0].Values.Values[0].Value.Value == "example.com" && match.Entries[0].Values.Values[0].Start.Character == 13+offset && match.Entries[0].Values.Values[0].End.Character == 23+offset+1) { + t.Errorf("Expected example.com, but got %v", match.Entries[0].Values.Values[0]) + } + + if !(match.Entries[1].Criteria.Type == MatchCriteriaTypeUser) { + t.Errorf("Expected User, but got %v", match.Entries[1]) + } + + if !(match.Entries[1].Values.Values[0].Value.Value == "root" && match.Entries[1].Values.Values[0].Start.Character == 30+offset && match.Entries[1].Values.Values[0].End.Character == 33+offset+1) { + t.Errorf("Expected root, but got %v", match.Entries[1].Values.Values[0]) + } +} + +func TestListExample( + t *testing.T, +) { + offset := uint32(20) + input := "originalhost example.com,example.org,example.net" + + match := NewMatch() + errors := match.Parse(input, 0, offset) + + if len(errors) > 0 { + t.Fatalf("Expected no errors, but got %v", errors) + } + + if !(len(match.Entries) == 1) { + t.Errorf("Expected 1 entries, but got %v", len(match.Entries)) + } + + if !(match.Entries[0].Criteria.Type == MatchCriteriaTypeOriginalHost) { + t.Errorf("Expected Address, but got %v", match.Entries[0]) + } + + if !(len(match.Entries[0].Values.Values) == 3) { + t.Errorf("Expected 3 values, but got %v", len(match.Entries[0].Values.Values)) + } + + if !(match.Entries[0].Values.Values[0].Value.Value == "example.com" && match.Entries[0].Values.Values[0].Start.Character == 13+offset && match.Entries[0].Values.Values[0].End.Character == 23+offset+1) { + t.Errorf("Expected example.com, but got %v", match.Entries[0].Values.Values[0]) + } +} + +func TestComplexExample( + t *testing.T, +) { + input := `originalhost laptop exec "[[ $(/usr/bin/dig +short laptop.lan) == '' ]]"` + + match := NewMatch() + errors := match.Parse(input, 0, 0) + + // TODO: Fix match so that it allows quotes + if len(errors) > 0 { + t.Fatalf("Expected no errors, but got %v", errors) + } + + if !(len(match.Entries) == 2) { + t.Errorf("Expected 2 entries, but got %v", len(match.Entries)) + } +} + +func TestIncompleteBetweenEntriesExample( + t *testing.T, +) { + input := "user root,admin,alice " + + match := NewMatch() + errors := match.Parse(input, 0, 0) + + if len(errors) > 0 { + t.Fatalf("Expected no errors, but got %v", errors) + } + + if !(len(match.Entries) == 1) { + t.Errorf("Expected 1 entries, but got %v", len(match.Entries)) + } + + if !(match.Entries[0].Criteria.Type == MatchCriteriaTypeUser) { + t.Errorf("Expected User, but got %v", match.Entries[0]) + } + + if !(len(match.Entries[0].Values.Values) == 3) { + t.Errorf("Expected 3 values, but got %v", len(match.Entries[0].Values.Values)) + } + + if !(match.Entries[0].Start.Character == 0 && match.Entries[0].End.Character == 21) { + t.Errorf("Expected 0-20, but got %v", match.Entries[0]) + } +} + +func TestIncompleteBetweenValuesExample( + t *testing.T, +) { + input := "user " + + match := NewMatch() + errors := match.Parse(input, 0, 0) + + if len(errors) > 0 { + t.Fatalf("Expected no errors, but got %v", errors) + } + + if !(len(match.Entries) == 1) { + t.Errorf("Expected 1 entries, but got %v", len(match.Entries)) + } + + if !(match.Entries[0].Criteria.Type == MatchCriteriaTypeUser) { + t.Errorf("Expected User, but got %v", match.Entries[0]) + } + + if !(len(match.Entries[0].Values.Values) == 0) { + t.Errorf("Expected 0 values, but got %v", match.Entries[0].Values) + } +} + + diff --git a/handlers/ssh_config/shared.go b/handlers/ssh_config/shared.go new file mode 100644 index 0000000..f701d68 --- /dev/null +++ b/handlers/ssh_config/shared.go @@ -0,0 +1,14 @@ +package sshconfig + +import ( + "config-lsp/handlers/ssh_config/ast" + + protocol "github.com/tliron/glsp/protocol_3_16" +) + +type SSHDocument struct { + Config *ast.SSHConfig + Indexes *ast.SSHIndexes +} + +var DocumentParserMap = map[protocol.DocumentUri]*SSHDocument{} From e6900d986148bf05a824b364668f975ad30ec12e Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Sun, 22 Sep 2024 13:06:06 +0200 Subject: [PATCH 074/133] fix: Fix update_antlr_parser --- update_antlr_parser.sh | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100755 update_antlr_parser.sh diff --git a/update_antlr_parser.sh b/update_antlr_parser.sh new file mode 100755 index 0000000..c6f8295 --- /dev/null +++ b/update_antlr_parser.sh @@ -0,0 +1,18 @@ +#!/bin/sh + +GIT_ROOT=$(git rev-parse --show-toplevel) + +# aliases +cd $GIT_ROOT/handlers/aliases && antlr4 -Dlanguage=Go -o ast/parser Aliases.g4 + +# sshd_config +cd $GIT_ROOT/handlers/sshd_config && antlr4 -Dlanguage=Go -o ast/parser Config.g4 +cd $GIT_ROOT/handlers/sshd_config/match-parser && antlr4 -Dlanguage=Go -o parser Match.g4 + +# ssh_config +cd $GIT_ROOT/handlers/ssh_config && antlr4 -Dlanguage=Go -o ast/parser Config.g4 +cd $GIT_ROOT/handlers/ssh_config/match-parser && antlr4 -Dlanguage=Go -o parser Match.g4 + +# hosts +cd $GIT_ROOT/handlers/hosts && antlr4 -Dlanguage=Go -o ast/parser Hosts.g4 + From 8067c821e81f4a6d46912f898b3e01712262e30c Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Sun, 22 Sep 2024 14:49:42 +0200 Subject: [PATCH 075/133] feat(ssh_config): Add hosts parsing; Add some tests --- handlers/ssh_config/ast/listener.go | 38 +++++- handlers/ssh_config/ast/parser_test.go | 129 ++++++++++++++++++ handlers/ssh_config/ast/ssh_config.go | 6 +- handlers/ssh_config/ast/ssh_config_fields.go | 2 +- handlers/ssh_config/host-parser/host_ast.go | 16 +++ handlers/ssh_config/host-parser/parser.go | 54 ++++++++ .../ssh_config/host-parser/parser_test.go | 73 ++++++++++ handlers/sshd_config/ast/listener.go | 2 +- 8 files changed, 315 insertions(+), 5 deletions(-) create mode 100644 handlers/ssh_config/host-parser/host_ast.go create mode 100644 handlers/ssh_config/host-parser/parser.go create mode 100644 handlers/ssh_config/host-parser/parser_test.go diff --git a/handlers/ssh_config/ast/listener.go b/handlers/ssh_config/ast/listener.go index 3adfe6e..a9cc359 100644 --- a/handlers/ssh_config/ast/listener.go +++ b/handlers/ssh_config/ast/listener.go @@ -4,6 +4,7 @@ import ( "config-lsp/common" commonparser "config-lsp/common/parser" "config-lsp/handlers/ssh_config/ast/parser" + hostparser "config-lsp/handlers/ssh_config/host-parser" "config-lsp/handlers/ssh_config/match-parser" "strings" @@ -131,7 +132,7 @@ func (s *sshParserListener) ExitEntry(ctx *parser.EntryContext) { if len(errors) > 0 { for _, err := range errors { s.Errors = append(s.Errors, common.LSPError{ - Range: err.Range.ShiftHorizontal(s.sshContext.currentOption.Start.Character), + Range: err.Range, Err: err.Err, }) } @@ -153,6 +154,41 @@ func (s *sshParserListener) ExitEntry(ctx *parser.EntryContext) { s.sshContext.currentKeyIsBlockOf = nil s.sshContext.currentBlock = matchBlock + case SSHBlockTypeHost: + var host *hostparser.Host + + hostParser := hostparser.NewHost() + errors := hostParser.Parse( + s.sshContext.currentOption.OptionValue.Value.Raw, + location.Start.Line, + s.sshContext.currentOption.OptionValue.Start.Character, + ) + + if len(errors) > 0 { + for _, err := range errors { + s.Errors = append(s.Errors, common.LSPError{ + Range: err.Range, + Err: err.Err, + }) + } + } else { + host = hostParser + } + + hostBlock := &SSHHostBlock{ + LocationRange: location, + HostOption: s.sshContext.currentOption, + HostValue: host, + Options: treemap.NewWith(gods.UInt32Comparator), + } + + s.Config.Options.Put( + location.Start.Line, + hostBlock, + ) + + s.sshContext.currentKeyIsBlockOf = nil + s.sshContext.currentBlock = hostBlock } return diff --git a/handlers/ssh_config/ast/parser_test.go b/handlers/ssh_config/ast/parser_test.go index dba0dc3..791d25f 100644 --- a/handlers/ssh_config/ast/parser_test.go +++ b/handlers/ssh_config/ast/parser_test.go @@ -127,3 +127,132 @@ Match originalhost "192.168.0.1" t.Errorf("Expected third entry to be User root, but got: %v", thirdEntry) } } + +func TestSimpleHostBlock( + t *testing.T, +) { + input := utils.Dedent(` +Ciphers 3des-cbc + +Host example.com + Port 22 +`) + p := NewSSHConfig() + errors := p.Parse(input) + + if len(errors) != 0 { + t.Fatalf("Expected no errors, got %v", errors) + } + + if !(p.Options.Size() == 2 && + len(utils.KeysOfMap(p.CommentLines)) == 0) { + t.Errorf("Expected 2 option and no comment lines, but got: %v entries, %v comment lines", p.Options.Size(), len(p.CommentLines)) + } + + rawFirstEntry, _ := p.Options.Get(uint32(0)) + firstEntry := rawFirstEntry.(*SSHOption) + if !(firstEntry.Value.Value == "Ciphers 3des-cbc") { + t.Errorf("Expected first entry to be Ciphers 3des-cbc, but got: %v", firstEntry) + } + + rawSecondEntry, _ := p.Options.Get(uint32(2)) + secondEntry := rawSecondEntry.(*SSHHostBlock) + if !(secondEntry.Options.Size() == 1 && + secondEntry.LocationRange.Start.Line == 2 && + secondEntry.LocationRange.Start.Character == 0 && + secondEntry.LocationRange.End.Line == 3 && + secondEntry.LocationRange.End.Character == 8) { + t.Errorf("Expected second entry to be Host example.com, but got: %v", secondEntry) + } + + rawThirdEntry, _ := secondEntry.Options.Get(uint32(3)) + thirdEntry := rawThirdEntry.(*SSHOption) + if !(thirdEntry.Value.Raw == "\tPort 22" && + thirdEntry.Key.Value.Raw == "Port" && + thirdEntry.OptionValue.Value.Raw == "22" && + thirdEntry.LocationRange.Start.Line == 3 && + thirdEntry.LocationRange.Start.Character == 0 && + thirdEntry.LocationRange.End.Line == 3 && + thirdEntry.LocationRange.End.Character == 8) { + t.Errorf("Expected third entry to be Port 22, but got: %v", thirdEntry) + } + + rawFourthEntry, _ := p.Options.Get(uint32(3)) + + if !(rawFourthEntry == nil) { + t.Errorf("Expected fourth entry to be nil, but got: %v", rawFourthEntry) + } +} + +func TestComplexExample( + t *testing.T, +) { + input := utils.Dedent(` +Host laptop + HostName laptop.lan + +Match originalhost laptop exec "[[ $(/usr/bin/dig +short laptop.lan) == '' ]]" + HostName laptop.sdn +`) + p := NewSSHConfig() + errors := p.Parse(input) + + if len(errors) != 0 { + t.Fatalf("Expected no errors, got %v", errors) + } + + if !(p.Options.Size() == 2 && + len(utils.KeysOfMap(p.CommentLines)) == 0) { + t.Errorf("Expected 2 option and no comment lines, but got: %v entries, %v comment lines", p.Options.Size(), len(p.CommentLines)) + } + + rawFirstEntry, _ := p.Options.Get(uint32(0)) + firstBlock := rawFirstEntry.(*SSHHostBlock) + if !(firstBlock.Options.Size() == 1 && + firstBlock.LocationRange.Start.Line == 0 && + firstBlock.LocationRange.Start.Character == 0 && + firstBlock.LocationRange.End.Line == 1 && + firstBlock.LocationRange.End.Character == 23) { + t.Errorf("Expected first entry to be Host laptop, but got: %v", firstBlock) + } + + rawSecondEntry, _ := firstBlock.Options.Get(uint32(1)) + secondOption := rawSecondEntry.(*SSHOption) + if !(secondOption.Value.Raw == " HostName laptop.lan" && + secondOption.Key.Value.Raw == "HostName" && + secondOption.OptionValue.Value.Raw == "laptop.lan" && + secondOption.LocationRange.Start.Line == 1 && + secondOption.LocationRange.Start.Character == 0 && + secondOption.Key.LocationRange.Start.Character == 4 && + secondOption.LocationRange.End.Line == 1 && + secondOption.LocationRange.End.Character == 23) { + t.Errorf("Expected second entry to be HostName laptop.lan, but got: %v", secondOption) + } + + rawThirdEntry, _ := p.Options.Get(uint32(3)) + secondBlock := rawThirdEntry.(*SSHMatchBlock) + if !(secondBlock.Options.Size() == 1 && + secondBlock.LocationRange.Start.Line == 3 && + secondBlock.LocationRange.Start.Character == 0 && + secondBlock.LocationRange.End.Line == 4 && + secondBlock.LocationRange.End.Character == 23) { + t.Errorf("Expected second entry to be Match originalhost laptop exec \"[[ $(/usr/bin/dig +short laptop.lan) == '' ]]\", but got: %v", secondBlock) + } + + if !(secondBlock.MatchOption.LocationRange.End.Character == 78) { + t.Errorf("Expected second entry to be Match originalhost laptop exec \"[[ $(/usr/bin/dig +short laptop.lan) == '' ]]\", but got: %v", secondBlock) + } + + rawFourthEntry, _ := secondBlock.Options.Get(uint32(4)) + thirdOption := rawFourthEntry.(*SSHOption) + if !(thirdOption.Value.Raw == " HostName laptop.sdn" && + thirdOption.Key.Value.Raw == "HostName" && + thirdOption.OptionValue.Value.Raw == "laptop.sdn" && + thirdOption.LocationRange.Start.Line == 4 && + thirdOption.LocationRange.Start.Character == 0 && + thirdOption.Key.LocationRange.Start.Character == 4 && + thirdOption.LocationRange.End.Line == 4 && + thirdOption.LocationRange.End.Character == 23) { + t.Errorf("Expected third entry to be HostName laptop.sdn, but got: %v", thirdOption) + } +} diff --git a/handlers/ssh_config/ast/ssh_config.go b/handlers/ssh_config/ast/ssh_config.go index 5757282..c9f6120 100644 --- a/handlers/ssh_config/ast/ssh_config.go +++ b/handlers/ssh_config/ast/ssh_config.go @@ -3,7 +3,9 @@ package ast import ( "config-lsp/common" commonparser "config-lsp/common/parser" + hostparser "config-lsp/handlers/ssh_config/host-parser" "config-lsp/handlers/ssh_config/match-parser" + "github.com/emirpasic/gods/maps/treemap" ) @@ -44,10 +46,10 @@ type SSHMatchBlock struct { type SSHHostBlock struct { common.LocationRange HostOption *SSHOption - HostValue string + HostValue *hostparser.Host // [uint32]*SSHOption -> line number -> *SSHOption - Others *treemap.Map + Options *treemap.Map } type SSHConfig struct { diff --git a/handlers/ssh_config/ast/ssh_config_fields.go b/handlers/ssh_config/ast/ssh_config_fields.go index 30cf8d5..55e0960 100644 --- a/handlers/ssh_config/ast/ssh_config_fields.go +++ b/handlers/ssh_config/ast/ssh_config_fields.go @@ -32,7 +32,7 @@ func (b *SSHHostBlock) GetBlockType() SSHBlockType { } func (b *SSHHostBlock) AddOption(option *SSHOption) { - b.Others.Put(option.LocationRange.Start.Line, option) + b.Options.Put(option.LocationRange.Start.Line, option) } func (b *SSHHostBlock) SetEnd(end common.Location) { diff --git a/handlers/ssh_config/host-parser/host_ast.go b/handlers/ssh_config/host-parser/host_ast.go new file mode 100644 index 0000000..28da9ce --- /dev/null +++ b/handlers/ssh_config/host-parser/host_ast.go @@ -0,0 +1,16 @@ +package hostparser + +import ( + "config-lsp/common" + commonparser "config-lsp/common/parser" +) + +type Host struct { + Hosts []*HostValue +} + +type HostValue struct { + common.LocationRange + Value commonparser.ParsedString +} + diff --git a/handlers/ssh_config/host-parser/parser.go b/handlers/ssh_config/host-parser/parser.go new file mode 100644 index 0000000..d2d6a94 --- /dev/null +++ b/handlers/ssh_config/host-parser/parser.go @@ -0,0 +1,54 @@ +package hostparser + +import ( + "config-lsp/common" + "regexp" + commonparser "config-lsp/common/parser" +) + +func NewHost() *Host { + match := new(Host) + match.Clear() + + return match +} + +func (h *Host) Clear() { + h.Hosts = make([]*HostValue, 0) +} + +var textPattern = regexp.MustCompile(`\S+`) + +func (h *Host) Parse( + input string, + line uint32, + startCharacter uint32, +) []common.LSPError { + hostsIndexes := textPattern.FindAllStringIndex(input, -1) + + for _, hostIndex := range hostsIndexes { + startIndex := hostIndex[0] + endIndex := hostIndex[1] + + rawHost := input[startIndex:endIndex] + + value := commonparser.ParseRawString(rawHost, commonparser.FullFeatures) + host := HostValue{ + LocationRange: common.LocationRange{ + Start: common.Location{ + Line: line, + Character: startCharacter + uint32(startIndex), + }, + End: common.Location{ + Line: line, + Character: startCharacter + uint32(endIndex), + }, + }, + Value: value, + } + + h.Hosts = append(h.Hosts, &host) + } + + return nil +} diff --git a/handlers/ssh_config/host-parser/parser_test.go b/handlers/ssh_config/host-parser/parser_test.go new file mode 100644 index 0000000..d751e7b --- /dev/null +++ b/handlers/ssh_config/host-parser/parser_test.go @@ -0,0 +1,73 @@ +package hostparser + +import "testing" + +func TestSimpleExample( + t *testing.T, +) { + input := `example.com` + + host := NewHost() + offset := uint32(8) + errs := host.Parse(input, 4, offset) + + if len(errs) > 0 { + t.Fatalf("Expected no errors, got %v", errs) + } + + if !(len(host.Hosts) == 1) { + t.Errorf("Expected 1 host, got %v", len(host.Hosts)) + } + + if !(host.Hosts[0].Value.Raw == "example.com") { + t.Errorf("Expected host to be 'example.com', got %v", host.Hosts[0].Value.Raw) + } + + if !(host.Hosts[0].Start.Line == 4 && host.Hosts[0].Start.Character == 0+offset && host.Hosts[0].End.Character == 11+offset) { + t.Errorf("Expected host to be at line 4, characters 0-11, got %v", host.Hosts[0]) + } + + if !(host.Hosts[0].Value.Value == "example.com") { + t.Errorf("Expected host value to be 'example.com', got %v", host.Hosts[0].Value.Value) + } +} + +func TestMultipleExample( + t *testing.T, +) { + input := `example.com example.org example.net` + + host := NewHost() + offset := uint32(8) + errs := host.Parse(input, 4, offset) + + if len(errs) > 0 { + t.Fatalf("Expected no errors, got %v", errs) + } + + if !(len(host.Hosts) == 3) { + t.Errorf("Expected 3 hosts, got %v", len(host.Hosts)) + } +} + +func TestIncompleteExample( + t *testing.T, +) { + input := `example.com ` + + host := NewHost() + offset := uint32(8) + errs := host.Parse(input, 4, offset) + + if len(errs) > 0 { + t.Fatalf("Expected no errors, got %v", errs) + } + + if !(len(host.Hosts) == 1) { + t.Errorf("Expected 1 hosts, got %v", len(host.Hosts)) + } + + if !(host.Hosts[0].Value.Raw == "example.com") { + t.Errorf("Expected host to be 'example.com', got %v", host.Hosts[0].Value.Raw) + } +} diff --git a/handlers/sshd_config/ast/listener.go b/handlers/sshd_config/ast/listener.go index 2ffcdec..cc5a414 100644 --- a/handlers/sshd_config/ast/listener.go +++ b/handlers/sshd_config/ast/listener.go @@ -126,7 +126,7 @@ func (s *sshdParserListener) ExitEntry(ctx *parser.EntryContext) { if len(errors) > 0 { for _, err := range errors { s.Errors = append(s.Errors, common.LSPError{ - Range: err.Range.ShiftHorizontal(s.sshdContext.currentOption.Start.Character), + Range: err.Range, Err: err.Err, }) } From 6601526fc2a5faba32ea8c0345b1411860d4cc19 Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Sun, 22 Sep 2024 14:55:19 +0200 Subject: [PATCH 076/133] test(ssh_config): Add more tests --- handlers/ssh_config/ast/parser_test.go | 101 +++++++++++++++++++++++++ 1 file changed, 101 insertions(+) diff --git a/handlers/ssh_config/ast/parser_test.go b/handlers/ssh_config/ast/parser_test.go index 791d25f..1462fa7 100644 --- a/handlers/ssh_config/ast/parser_test.go +++ b/handlers/ssh_config/ast/parser_test.go @@ -256,3 +256,104 @@ Match originalhost laptop exec "[[ $(/usr/bin/dig +short laptop.lan) == '' ]]" t.Errorf("Expected third entry to be HostName laptop.sdn, but got: %v", thirdOption) } } + +func TestComplexBigExample( + t *testing.T, +) { + // From https://gist.github.com/zeloc/b9455b793b07898025db + input := utils.Dedent(` +### default for all ## +Host * + ForwardAgent no + ForwardX11 no + ForwardX11Trusted yes + User nixcraft + Port 22 + Protocol 2 + ServerAliveInterval 60 + ServerAliveCountMax 30 + +## override as per host ## +Host server1 + HostName server1.cyberciti.biz + User nixcraft + Port 4242 + IdentityFile /nfs/shared/users/nixcraft/keys/server1/id_rsa + +## Home nas server ## +Host nas01 + HostName 192.168.1.100 + User root + IdentityFile ~/.ssh/nas01.key + +## Login AWS Cloud ## +Host aws.apache + HostName 1.2.3.4 + User wwwdata + IdentityFile ~/.ssh/aws.apache.key + +## Login to internal lan server at 192.168.0.251 via our public uk office ssh based gateway using ## +## $ ssh uk.gw.lan ## +Host uk.gw.lan uk.lan + HostName 192.168.0.251 + User nixcraft + ProxyCommand ssh nixcraft@gateway.uk.cyberciti.biz nc %h %p 2> /dev/null + +## Our Us Proxy Server ## +## Forward all local port 3128 traffic to port 3128 on the remote vps1.cyberciti.biz server ## +## $ ssh -f -N proxyus ## +Host proxyus + HostName vps1.cyberciti.biz + User breakfree + IdentityFile ~/.ssh/vps1.cyberciti.biz.key + LocalForward 3128 127.0.0.1:3128 +`) + p := NewSSHConfig() + + errors := p.Parse(input) + + if len(errors) != 0 { + t.Fatalf("Expected no errors, got %v", errors) + } + + if !(p.Options.Size() == 6 && len(utils.KeysOfMap(p.CommentLines)) == 9) { + t.Errorf("Expected 6 options and no comment lines, but got: %v options, %v comment lines", p.Options.Size(), len(p.CommentLines)) + } + + // Validate each Host block and its options + rawFirstEntry, _ := p.Options.Get(uint32(1)) + firstBlock := rawFirstEntry.(*SSHHostBlock) + if !(firstBlock.Options.Size() == 8) { + t.Errorf("Expected 8 options for Host *, but got: %v", firstBlock.Options.Size()) + } + + rawSecondEntry, _ := p.Options.Get(uint32(12)) + secondBlock := rawSecondEntry.(*SSHHostBlock) + if !(secondBlock.Options.Size() == 4) { + t.Errorf("Expected 4 options for Host server1, but got: %v", secondBlock.Options.Size()) + } + + rawThirdEntry, _ := p.Options.Get(uint32(19)) + thirdBlock := rawThirdEntry.(*SSHHostBlock) + if !(thirdBlock.Options.Size() == 3) { + t.Errorf("Expected 2 options for Host nas01, but got: %v", thirdBlock.Options.Size()) + } + + rawFourthEntry, _ := p.Options.Get(uint32(25)) + fourthBlock := rawFourthEntry.(*SSHHostBlock) + if !(fourthBlock.Options.Size() == 3) { + t.Errorf("Expected 2 options for Host aws.apache, but got: %v", fourthBlock.Options.Size()) + } + + rawFifthEntry, _ := p.Options.Get(uint32(32)) + fifthBlock := rawFifthEntry.(*SSHHostBlock) + if !(fifthBlock.Options.Size() == 3) { + t.Errorf("Expected 3 options for Host uk.gw.lan uk.lan, but got: %v", fifthBlock.Options.Size()) + } + + rawSixthEntry, _ := p.Options.Get(uint32(40)) + sixthBlock := rawSixthEntry.(*SSHHostBlock) + if !(sixthBlock.Options.Size() == 4) { + t.Errorf("Expected 4 options for Host proxyus, but got: %v", sixthBlock.Options.Size()) + } +} From 78661e3c2e3c0d60c3c05f9622badc5be470606c Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Sun, 22 Sep 2024 17:56:48 +0200 Subject: [PATCH 077/133] feat(ssh_config): Update fields --- common/ssh/query.go | 44 ++ .../value-data-amount-value.go | 9 +- .../value-time-format.go | 10 +- handlers/ssh_config/ast/listener.go | 2 - handlers/ssh_config/ast/ssh_config_fields.go | 15 +- handlers/ssh_config/fields/fields.go | 591 ++++++++++++++---- handlers/ssh_config/fields/utils.go | 39 ++ handlers/ssh_config/indexes/handlers.go | 129 ++++ .../ssh_config/{ast => indexes}/indexes.go | 19 +- handlers/ssh_config/indexes/indexes_test.go | 53 ++ handlers/ssh_config/shared.go | 3 +- handlers/sshd_config/fields/fields.go | 19 +- handlers/sshd_config/fields/utils.go | 57 -- 13 files changed, 787 insertions(+), 203 deletions(-) create mode 100644 common/ssh/query.go rename {handlers/sshd_config/fields => doc-values}/value-data-amount-value.go (90%) rename {handlers/sshd_config/fields => doc-values}/value-time-format.go (91%) create mode 100644 handlers/ssh_config/fields/utils.go create mode 100644 handlers/ssh_config/indexes/handlers.go rename handlers/ssh_config/{ast => indexes}/indexes.go (65%) create mode 100644 handlers/ssh_config/indexes/indexes_test.go diff --git a/common/ssh/query.go b/common/ssh/query.go new file mode 100644 index 0000000..8e4cf61 --- /dev/null +++ b/common/ssh/query.go @@ -0,0 +1,44 @@ +package ssh + +import ( + "config-lsp/doc-values" + "config-lsp/utils" + "os/exec" + "strings" +) + +var _cachedQueries map[string][]docvalues.EnumString = make(map[string][]docvalues.EnumString) + +func queryValues(query string) ([]string, error) { + cmd := exec.Command("ssh", "-Q", query) + + output, err := cmd.Output() + + if err != nil { + return []string{}, err + } + + return strings.Split(string(output), "\n"), nil +} + +func QueryOpenSSHOptions( + query string, +) ([]docvalues.EnumString, error) { + var availableQueries []docvalues.EnumString + key := query + + if _cachedQueries[key] != nil && len(_cachedQueries[key]) > 0 { + return _cachedQueries[key], nil + } else { + availableRawQueries, err := queryValues(query) + availableQueries = utils.Map(availableRawQueries, docvalues.CreateEnumString) + + if err != nil { + return []docvalues.EnumString{}, err + } + + _cachedQueries[key] = availableQueries + } + + return availableQueries, nil +} diff --git a/handlers/sshd_config/fields/value-data-amount-value.go b/doc-values/value-data-amount-value.go similarity index 90% rename from handlers/sshd_config/fields/value-data-amount-value.go rename to doc-values/value-data-amount-value.go index 01a6b68..0616b54 100644 --- a/handlers/sshd_config/fields/value-data-amount-value.go +++ b/doc-values/value-data-amount-value.go @@ -1,7 +1,6 @@ -package fields +package docvalues import ( - docvalues "config-lsp/doc-values" "fmt" "regexp" "strconv" @@ -23,9 +22,9 @@ func (v DataAmountValue) GetTypeDescription() []string { return []string{"Data amount"} } -func (v DataAmountValue) CheckIsValid(value string) []*docvalues.InvalidValue { +func (v DataAmountValue) CheckIsValid(value string) []*InvalidValue { if !dataAmountCheckPattern.MatchString(value) { - return []*docvalues.InvalidValue{ + return []*InvalidValue{ { Err: InvalidDataAmountError{}, Start: 0, @@ -85,7 +84,7 @@ func (v DataAmountValue) FetchCompletions(line string, cursor uint32) []protocol if line == "" || isJustDigitsPattern.MatchString(line) { completions = append( completions, - docvalues.GenerateBase10Completions(line)..., + GenerateBase10Completions(line)..., ) } diff --git a/handlers/sshd_config/fields/value-time-format.go b/doc-values/value-time-format.go similarity index 91% rename from handlers/sshd_config/fields/value-time-format.go rename to doc-values/value-time-format.go index 607ac3d..b1a3261 100644 --- a/handlers/sshd_config/fields/value-time-format.go +++ b/doc-values/value-time-format.go @@ -1,7 +1,6 @@ -package fields +package docvalues import ( - docvalues "config-lsp/doc-values" "config-lsp/utils" "fmt" "regexp" @@ -12,6 +11,7 @@ import ( var timeFormatCompletionsPattern = regexp.MustCompile(`(?i)^(\d+)([smhdw])$`) var timeFormatCheckPattern = regexp.MustCompile(`(?i)^(\d+)([smhdw]?)$`) +var isJustDigitsPattern = regexp.MustCompile(`^\d+$`) type InvalidTimeFormatError struct{} @@ -25,9 +25,9 @@ func (v TimeFormatValue) GetTypeDescription() []string { return []string{"Time value"} } -func (v TimeFormatValue) CheckIsValid(value string) []*docvalues.InvalidValue { +func (v TimeFormatValue) CheckIsValid(value string) []*InvalidValue { if !timeFormatCheckPattern.MatchString(value) { - return []*docvalues.InvalidValue{ + return []*InvalidValue{ { Err: InvalidTimeFormatError{}, Start: 0, @@ -99,7 +99,7 @@ func (v TimeFormatValue) FetchCompletions(line string, cursor uint32) []protocol if line == "" || isJustDigitsPattern.MatchString(line) { completions = append( completions, - docvalues.GenerateBase10Completions(line)..., + GenerateBase10Completions(line)..., ) } diff --git a/handlers/ssh_config/ast/listener.go b/handlers/ssh_config/ast/listener.go index a9cc359..f9dff36 100644 --- a/handlers/ssh_config/ast/listener.go +++ b/handlers/ssh_config/ast/listener.go @@ -17,12 +17,10 @@ type sshListenerContext struct { currentOption *SSHOption currentBlock SSHBlock currentKeyIsBlockOf *SSHBlockType - currentIndexes *SSHIndexes } func createListenerContext() *sshListenerContext { context := new(sshListenerContext) - context.currentIndexes = NewSSHIndexes() return context } diff --git a/handlers/ssh_config/ast/ssh_config_fields.go b/handlers/ssh_config/ast/ssh_config_fields.go index 55e0960..ec5ccd0 100644 --- a/handlers/ssh_config/ast/ssh_config_fields.go +++ b/handlers/ssh_config/ast/ssh_config_fields.go @@ -1,6 +1,10 @@ package ast -import "config-lsp/common" +import ( + "config-lsp/common" + + "github.com/emirpasic/gods/maps/treemap" +) type SSHBlockType uint8 @@ -13,6 +17,7 @@ type SSHBlock interface { GetBlockType() SSHBlockType AddOption(option *SSHOption) SetEnd(common.Location) + GetOptions() *treemap.Map } func (b *SSHMatchBlock) GetBlockType() SSHBlockType { @@ -27,6 +32,10 @@ func (b *SSHMatchBlock) SetEnd(end common.Location) { b.LocationRange.End = end } +func (b *SSHMatchBlock) GetOptions() *treemap.Map { + return b.Options +} + func (b *SSHHostBlock) GetBlockType() SSHBlockType { return SSHBlockTypeHost } @@ -39,6 +48,10 @@ func (b *SSHHostBlock) SetEnd(end common.Location) { b.LocationRange.End = end } +func (b *SSHHostBlock) GetOptions() *treemap.Map { + return b.Options +} + type SSHType uint8 const ( diff --git a/handlers/ssh_config/fields/fields.go b/handlers/ssh_config/fields/fields.go index 83237d3..d90b649 100644 --- a/handlers/ssh_config/fields/fields.go +++ b/handlers/ssh_config/fields/fields.go @@ -1,6 +1,17 @@ package fields -import docvalues "config-lsp/doc-values" +import ( + "config-lsp/common/ssh" + docvalues "config-lsp/doc-values" + "regexp" +) + +var ZERO = 0 +var MAX_PORT = 65535 + +var AllowedDuplicateOptions = map[string]struct{}{ + "CertificateFile": {}, +} var Options = map[string]docvalues.DocumentationValue{ "Host": { @@ -20,24 +31,51 @@ var Options = map[string]docvalues.DocumentationValue{ }, "AddKeysToAgent": { Documentation: `Specifies whether keys should be automatically added to a running ssh-agent(1). If this option is set to yes and a key is loaded from a file, the key and its passphrase are added to the agent with the default lifetime, as if by ssh-add(1). If this option is set to ask, ssh(1) will require confirmation using the SSH_ASKPASS program before adding a key (see ssh-add(1) for details). If this option is set to confirm, each use of the key must be confirmed, as if the -c option was specified to ssh-add(1). If this option is set to no, no keys are added to the agent. Alternately, this option may be specified as a time interval using the format described in the TIME FORMATS section of sshd_config(5) to specify the key's lifetime in ssh-agent(1), after which it will automatically be removed. The argument must be no (the default), yes, confirm (optionally followed by a time interval), ask or a time interval.`, - Value: docvalues.StringValue{}, + Value: docvalues.OrValue{ + Values: []docvalues.Value{ + docvalues.EnumValue{ + EnforceValues: true, + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("no"), + docvalues.CreateEnumString("yes"), + docvalues.CreateEnumString("confirm"), + docvalues.CreateEnumString("ask"), + }, + }, + docvalues.TimeFormatValue{}, + }, + }, }, "AddressFamily": { - Documentation: `Specifies which address family to use when connecting. Valid arguments are any (the default), inet - (use IPv4 only), or inet6 (use IPv6 only).`, - Value: docvalues.StringValue{}, + Documentation: `Specifies which address family to use when connecting. Valid arguments are any (the default), inet (use IPv4 only), or inet6 (use IPv6 only).`, + Value: docvalues.EnumValue{ + EnforceValues: true, + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("any"), + docvalues.CreateEnumString("inet"), + docvalues.CreateEnumString("inet6"), + }, + }, }, "BatchMode": { Documentation: `If set to yes, user interaction such as password prompts and host key confirmation requests will be disabled. This option is useful in scripts and other batch jobs where no user is present to interact with ssh(1). The argument must be yes or no (the default).`, - Value: docvalues.StringValue{}, + Value: booleanEnumValue, }, "BindAddress": { Documentation: `Use the specified address on the local machine as the source address of the connection. Only useful on systems with more than one address.`, - Value: docvalues.StringValue{}, + Value: docvalues.IPAddressValue{ + AllowIPv4: true, + AllowIPv6: true, + AllowRange: false, + }, }, "BindInterface": { Documentation: `Use the address of the specified interface on the local machine as the source address of the connection.`, - Value: docvalues.StringValue{}, + Value: docvalues.IPAddressValue{ + AllowIPv4: false, + AllowIPv6: false, + AllowRange: false, + }, }, "CanonicalDomains": { Documentation: `When CanonicalizeHostname is enabled, this option specifies the list of domain suffixes in which to search for the specified destination host.`, @@ -45,23 +83,27 @@ var Options = map[string]docvalues.DocumentationValue{ }, "CanonicalizeFallbackLocal": { Documentation: `Specifies whether to fail with an error when hostname canonicalization fails. The default, yes, will attempt to look up the unqualified hostname using the system resolver's search rules. A value of no will cause ssh(1) to fail instantly if CanonicalizeHostname is enabled and the target hostname cannot be found in any of the domains specified by CanonicalDomains.`, - Value: docvalues.StringValue{}, + Value: booleanEnumValue, }, "CanonicalizeHostname": { Documentation: `Controls whether explicit hostname canonicalization is performed. The default, no, is not to perform any name rewriting and let the system resolver handle all hostname lookups. If set to yes then, for connections that do not use a ProxyCommand or ProxyJump, ssh(1) will attempt to canonicalize the hostname specified on the command line using the CanonicalDomains suffixes and CanonicalizePermittedCNAMEs rules. If CanonicalizeHostname is set to always, then canonicalization is applied to proxied connections too. If this option is enabled, then the configuration files are processed again using the new target name to pick up any new configuration in matching Host and Match stanzas. A value of none disables the use of a ProxyJump host.`, - Value: docvalues.StringValue{}, + Value: booleanEnumValue, }, "CanonicalizeMaxDots": { Documentation: `Specifies the maximum number of dot characters in a hostname before canonicalization is disabled. The default, 1, allows a single dot (i.e. hostname.subdomain).`, - Value: docvalues.StringValue{}, + Value: docvalues.PositiveNumberValue(), }, "CanonicalizePermittedCNAMEs": { Documentation: `Specifies rules to determine whether CNAMEs should be followed when canonicalizing hostnames. The rules consist of one or more arguments of source_domain_list:target_domain_list, where source_domain_list is a pattern-list of domains that may follow CNAMEs in canonicalization, and target_domain_list is a pattern-list of domains that they may resolve to. For example, '*.a.example.com:*.b.example.com,*.c.example.com' will allow hostnames matching '*.a.example.com' to be canonicalized to names in the '*.b.example.com' or '*.c.example.com' domains. A single argument of 'none' causes no CNAMEs to be considered for canonicalization. This is the default behaviour.`, - Value: docvalues.StringValue{}, + Value: docvalues.ArrayValue{ + Separator: ",", + DuplicatesExtractor: &docvalues.SimpleDuplicatesExtractor, + SubValue: docvalues.StringValue{}, + }, }, "CASignatureAlgorithms": { Documentation: `Specifies which algorithms are allowed for signing of certificates by certificate authorities (CAs). The default is: @@ -75,22 +117,86 @@ rsa-sha2-512,rsa-sha2-256 If the specified list begins with a ‘+’ character, then the specified algorithms will be appended to the default set instead of replacing them. If the specified list begins with a ‘-’ character, then the specified algorithms (including wildcards) will be removed from the default set instead of replacing them. ssh(1) will not accept host certificates signed using algorithms other than those specified.`, - Value: docvalues.StringValue{}, + Value: docvalues.PrefixWithMeaningValue{ + Prefixes: []docvalues.Prefix{ + { + Prefix: "+", + Meaning: "Appende to the default set", + }, + { + Prefix: "-", + Meaning: "Remove from the default set", + }, + }, + SubValue: docvalues.ArrayValue{ + Separator: ",", + DuplicatesExtractor: &docvalues.DuplicatesAllowedExtractor, + // TODO: Add + SubValue: docvalues.StringValue{}, + }, + }, }, "CertificateFile": { Documentation: `Specifies a file from which the user's certificate is read. A corresponding private key must be provided separately in order to use this certificate either from an IdentityFile directive or -i flag to ssh(1), via ssh-agent(1), or via a PKCS11Provider or SecurityKeyProvider. Arguments to CertificateFile may use the tilde syntax to refer to a user's home directory, the tokens described in the TOKENS section and environment variables as described in the ENVIRONMENT VARIABLES section. It is possible to have multiple certificate files specified in configuration files; these certificates will be tried in sequence. Multiple CertificateFile directives will add to the list of certificates used for authentication.`, - Value: docvalues.StringValue{}, + Value: docvalues.PathValue{ + RequiredType: docvalues.PathTypeFile, + }, }, "ChannelTimeout": { - Documentation: `Open X11 forwarding sessions.`, - Value: docvalues.StringValue{}, + Documentation: `Specifies whether and how quickly ssh(1) should close inactive channels. Timeouts are specified as one or more “type=interval” pairs separated by whitespace, where the “type” must be the special keyword “global” or a channel type name from the list below, optionally containing wildcard characters. + +The timeout value “interval” is specified in seconds or may use any of the units documented in the TIME FORMATS section. For example, “session=5m” would cause interactive sessions to terminate after five minutes of inactivity. Specifying a zero value disables the inactivity timeout. + +The special timeout “global” applies to all active channels, taken together. Traffic on any active channel will reset the timeout, but when the timeout expires then all open channels will be closed. Note that this global timeout is not matched by wildcards and must be specified explicitly. + +The available channel type names include: + +agent-connection + Open connections to ssh-agent(1). +direct-tcpip, direct-streamlocal@openssh.com + Open TCP or Unix socket (respectively) connections that have been established from a ssh(1) local forwarding, i.e. LocalForward or DynamicForward. +forwarded-tcpip, forwarded-streamlocal@openssh.com + Open TCP or Unix socket (respectively) connections that have been established to a sshd(8) listening on behalf of a ssh(1) remote forwarding, i.e. RemoteForward. +session + The interactive main session, including shell session, command execution, scp(1), sftp(1), etc. +tun-connection + Open TunnelForward connections. +x11-connection + Open X11 forwarding sessions. + +Note that in all the above cases, terminating an inactive session does not guarantee to remove all resources associated with the session, e.g. shell processes or X11 clients relating to the session may continue to execute. + +Moreover, terminating an inactive channel or session does not necessarily close the SSH connection, nor does it prevent a client from requesting another channel of the same type. In particular, expiring an inactive forwarding session does not prevent another identical forwarding from being subsequently created. + +The default is not to expire channels of any type for inactivity.`, + Value: docvalues.ArrayValue{ + Separator: " ", + DuplicatesExtractor: &channelTimeoutExtractor, + SubValue: docvalues.KeyValueAssignmentValue{ + ValueIsOptional: false, + Separator: "=", + Key: docvalues.EnumValue{ + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("global"), + docvalues.CreateEnumString("agent-connection"), + docvalues.CreateEnumString("direct-tcpip"), + docvalues.CreateEnumString("direct-streamlocal@openssh.com"), + docvalues.CreateEnumString("forwarded-tcpip"), + docvalues.CreateEnumString("forwarded-streamlocal@openssh.com"), + docvalues.CreateEnumString("session"), + docvalues.CreateEnumString("tun-connection"), + docvalues.CreateEnumString("x11-connection"), + }, + }, + Value: docvalues.TimeFormatValue{}, + }, + }, }, "CheckHostIP": { - Documentation: `If set to yes, ssh(1) will additionally check the host IP address in the known_hosts file. This allows it to detect if a host key changed due to DNS spoofing and will add addresses of destination hosts to ~/.ssh/known_hosts in the process, regardless of the setting of StrictHostKeyChecking. If the option is set to no (the default), the check will not be - executed.`, - Value: docvalues.StringValue{}, + Documentation: `If set to yes, ssh(1) will additionally check the host IP address in the known_hosts file. This allows it to detect if a host key changed due to DNS spoofing and will add addresses of destination hosts to ~/.ssh/known_hosts in the process, regardless of the setting of StrictHostKeyChecking. If the option is set to no (the default), the check will not be executed.`, + Value: booleanEnumValue, }, "Ciphers": { Documentation: `Specifies the ciphers allowed and their order of preference. Multiple ciphers must be comma-separated. If the specified list begins with a @@ -116,124 +222,168 @@ aes128-gcm@openssh.com,aes256-gcm@openssh.com The list of available ciphers may also be obtained using 'ssh -Q cipher'.`, - Value: docvalues.StringValue{}, + Value: prefixPlusMinusCaret([]docvalues.EnumString{ + docvalues.CreateEnumString("3des-cbc"), + docvalues.CreateEnumString("aes128-cbc"), + docvalues.CreateEnumString("aes192-cbc"), + docvalues.CreateEnumString("aes256-cbc"), + docvalues.CreateEnumString("aes128-ctr"), + docvalues.CreateEnumString("aes192-ctr"), + docvalues.CreateEnumString("aes256-ctr"), + docvalues.CreateEnumString("aes128-gcm@openssh.com"), + docvalues.CreateEnumString("aes256-gcm@openssh.com"), + docvalues.CreateEnumString("chacha20-poly1305@openssh.com"), + }), }, "ClearAllForwardings": { Documentation: `Specifies that all local, remote, and dynamic port forwardings specified in the configuration files or on the command line be cleared. This option is primarily useful when used from the ssh(1) command line to clear port forwardings set in configuration files, and is automatically set by scp(1) and sftp(1). The argument must be yes or no (the default).`, - Value: docvalues.StringValue{}, + Value: booleanEnumValue, }, "Compression": { - Documentation: `Specifies whether to use compression. The argument must be yes or no (the - default).`, - Value: docvalues.StringValue{}, + Documentation: `Specifies whether to use compression. The argument must be yes or no (the default).`, + Value: booleanEnumValue, }, "ConnectionAttempts": { Documentation: `Specifies the number of tries (one per second) to make before exiting. The argument must be an integer. This may be useful in scripts if the connection sometimes fails. The default is 1.`, - Value: docvalues.StringValue{}, + Value: docvalues.NumberValue{}, }, "ConnectTimeout": { Documentation: `Specifies the timeout (in seconds) used when connecting to the SSH server, instead of using the default system TCP timeout. This timeout is applied both to establishing the connection and to performing the initial SSH protocol handshake and key exchange.`, - Value: docvalues.StringValue{}, + Value: docvalues.NumberValue{}, }, "ControlMaster": { Documentation: `Enables the sharing of multiple sessions over a single network connection. When set to yes, ssh(1) will listen for connections on a control socket specified using the ControlPath argument. Additional sessions can connect to this socket using the same ControlPath with ControlMaster set to no (the default). These sessions will try to reuse the master instance's network connection rather than initiating new ones, but will fall back to connecting normally if the control socket does not exist, or is not listening. Setting this to ask will cause ssh(1) to listen for control connections, but require confirmation using ssh-askpass(1). If the ControlPath cannot be opened, ssh(1) will continue without connecting to a master instance. X11 and ssh-agent(1) forwarding is supported over these multiplexed connections, however the display and agent forwarded will be the one belonging to the master connection i.e. it is not possible to forward multiple displays or agents. Two additional options allow for opportunistic multiplexing: try to use a master connection but fall back to creating a new one if one does not already exist. These options are: auto and autoask. The latter requires confirmation like the ask option.`, - Value: docvalues.StringValue{}, + Value: docvalues.EnumValue{ + EnforceValues: true, + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("yes"), + docvalues.CreateEnumString("no"), + docvalues.CreateEnumString("ask"), + docvalues.CreateEnumString("auto"), + docvalues.CreateEnumString("autoask"), + }, + }, }, "ControlPath": { - Documentation: `Specify the path to the control socket used for connection sharing as described in the ControlMaster section above or the string none to disable connection sharing. Arguments to ControlPath may use the tilde syntax to refer to a user's home directory, the tokens described in the TOKENS section and environment variables as described in the ENVIRONMENT VARIABLES section. It is recommended that any ControlPath used for opportunistic connection sharing include at least %h, %p, and %r - (or alternatively %C) and be placed in a directory that is not writable by other users. This ensures that shared connections are uniquely - identified.`, + Documentation: `Specify the path to the control socket used for connection sharing as described in the ControlMaster section above or the string none to disable connection sharing. Arguments to ControlPath may use the tilde syntax to refer to a user's home directory, the tokens described in the TOKENS section and environment variables as described in the ENVIRONMENT VARIABLES section. It is recommended that any ControlPath used for opportunistic connection sharing include at least %h, %p, and %r (or alternatively %C) and be placed in a directory that is not writable by other users. This ensures that shared connections are uniquely identified.`, Value: docvalues.StringValue{}, }, "ControlPersist": { - Documentation: `When used in conjunction with ControlMaster, specifies that the master connection should remain open in the background - (waiting for future client connections) after the initial client connection has been closed. If set to no (the default), then the master connection will not be placed into the background, and will close as soon as the initial client connection is closed. If set to yes or 0, then the master connection will remain in the background indefinitely (until killed or closed via a mechanism such as the 'ssh -O exit'). If set to a time in seconds, or a time in any of the formats documented in sshd_config(5), then the backgrounded master connection will automatically terminate after it has remained idle (with no client connections) for the specified time.`, - Value: docvalues.StringValue{}, + Documentation: `When used in conjunction with ControlMaster, specifies that the master connection should remain open in the background (waiting for future client connections) after the initial client connection has been closed. If set to no (the default), then the master connection will not be placed into the background, and will close as soon as the initial client connection is closed. If set to yes or 0, then the master connection will remain in the background indefinitely (until killed or closed via a mechanism such as the 'ssh -O exit'). If set to a time in seconds, or a time in any of the formats documented in sshd_config(5), then the backgrounded master connection will automatically terminate after it has remained idle (with no client connections) for the specified time.`, + Value: docvalues.OrValue{ + Values: []docvalues.Value{ + booleanEnumValue, + docvalues.TimeFormatValue{}, + docvalues.PositiveNumberValue(), + }, + }, }, "DynamicForward": { - Documentation: `Specifies that a TCP port on the local machine be forwarded over the secure channel, and the application protocol is then used to determine where to connect to from the remote machine. - The argument must be + Documentation: `Specifies that a TCP port on the local machine be forwarded over the secure channel, and the application protocol is then used to determine where to connect to from the remote machine. The argument must be [bind_address:]port. IPv6 addresses can be specified by enclosing addresses in square brackets. By default, the local port is bound in accordance with the GatewayPorts setting. However, an explicit bind_address may be used to bind the connection to a specific address. The bind_address of localhost indicates that the listening port be bound for local use only, while an empty address or ‘*’ indicates that the port should be available from all interfaces. Currently the SOCKS4 and SOCKS5 protocols are supported, and ssh(1) will act as a SOCKS server. Multiple forwardings may be specified, and additional forwardings can be given on the command line. Only the superuser can forward privileged ports.`, - Value: docvalues.StringValue{}, + Value: docvalues.OrValue{ + Values: []docvalues.Value{ + docvalues.NumberValue{Min: &ZERO, Max: &MAX_PORT}, + docvalues.KeyValueAssignmentValue{ + Key: docvalues.IPAddressValue{ + AllowIPv4: true, + AllowIPv6: true, + AllowRange: false, + }, + Value: docvalues.NumberValue{Min: &ZERO, Max: &MAX_PORT}, + }, + }, + }, }, "EnableEscapeCommandline": { - Documentation: `Enables the command line option in the EscapeChar menu for interactive sessions (default - ‘~C’). By default, the command line is disabled.`, + Documentation: `Enables the command line option in the EscapeChar menu for interactive sessions (default ‘~C’). By default, the command line is disabled.`, Value: docvalues.StringValue{}, }, "EnableSSHKeysign": { Documentation: `Setting this option to yes in the global client configuration file /etc/ssh/ssh_config enables the use of the helper program ssh-keysign(8) during HostbasedAuthentication. The argument must be yes or no (the default). This option should be placed in the non-hostspecific section. See ssh-keysign(8) for more information.`, - Value: docvalues.StringValue{}, + Value: booleanEnumValue, }, "EscapeChar": { - Documentation: `Sets the escape character (default: - ‘~’). The escape character can also be set on the command line. The argument should be a single character, - ‘^’ followed by a letter, or none to disable the escape character entirely - (making the connection transparent for binary data).`, + Documentation: `Sets the escape character (default: ‘~’). The escape character can also be set on the command line. The argument should be a single character, ‘^’ followed by a letter, or none to disable the escape character entirely (making the connection transparent for binary data).`, Value: docvalues.StringValue{}, }, "ExitOnForwardFailure": { Documentation: `Specifies whether ssh(1) should terminate the connection if it cannot set up all requested dynamic, tunnel, local, and remote port forwardings, (e.g. if either end is unable to bind and listen on a specified port). Note that ExitOnForwardFailure does not apply to connections made over port forwardings and will not, for example, cause ssh(1) to exit if TCP connections to the ultimate forwarding destination fail. The argument must be yes or no (the default).`, - Value: docvalues.StringValue{}, + Value: booleanEnumValue, }, "FingerprintHash": { Documentation: `Specifies the hash algorithm used when displaying key fingerprints. Valid options are: md5 and sha256 (the default).`, - Value: docvalues.StringValue{}, + Value: docvalues.EnumValue{ + EnforceValues: true, + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("md5"), + docvalues.CreateEnumString("sha256"), + }, + }, }, "ForkAfterAuthentication": { Documentation: `Requests ssh to go to background just before command execution. This is useful if ssh is going to ask for passwords or passphrases, but the user wants it in the background. This implies the StdinNull configuration option being set to “yes”. The recommended way to start X11 programs at a remote site is with something like ssh -f host xterm, which is the same as ssh host xterm if the ForkAfterAuthentication configuration option is set to “yes”. If the ExitOnForwardFailure configuration option is set to “yes”, then a client started with the ForkAfterAuthentication configuration option being set to “yes” will wait for all remote port forwards to be successfully established before placing itself in the background. The argument to this keyword must be yes (same as the -f option) or no (the default).`, - Value: docvalues.StringValue{}, + Value: booleanEnumValue, }, "ForwardAgent": { - Documentation: `Specifies whether the connection to the authentication agent (if any) will be forwarded to the remote machine. The argument may be yes, no (the default), an explicit path to an agent socket or the name of an environment variable - (beginning with ‘$’) in which to find the path. + Documentation: `Specifies whether the connection to the authentication agent (if any) will be forwarded to the remote machine. The argument may be yes, no (the default), an explicit path to an agent socket or the name of an environment variable (beginning with ‘$’) in which to find the path. Agent forwarding should be enabled with caution. Users with the ability to bypass file permissions on the remote host (for the agent's Unix-domain socket) can access the local agent through the forwarded connection. An attacker cannot obtain key material from the agent, however they can perform operations on the keys that enable them to authenticate using the identities loaded into the agent.`, - Value: docvalues.StringValue{}, + Value: docvalues.OrValue{ + Values: []docvalues.Value{ + booleanEnumValue, + docvalues.StringValue{}, + }, + }, }, "ForwardX11": { Documentation: `Specifies whether X11 connections will be automatically redirected over the secure channel and DISPLAY set. The argument must be yes or no (the default). X11 forwarding should be enabled with caution. Users with the ability to bypass file permissions on the remote host (for the user's X11 authorization database) can access the local X11 display through the forwarded connection. An attacker may then be able to perform activities such as keystroke monitoring if the ForwardX11Trusted option is also enabled.`, - Value: docvalues.StringValue{}, + Value: booleanEnumValue, }, "ForwardX11Timeout": { Documentation: `Specify a timeout for untrusted X11 forwarding using the format described in the TIME FORMATS section of sshd_config(5). X11 connections received by ssh(1) after this time will be refused. Setting ForwardX11Timeout to zero will disable the timeout and permit X11 forwarding for the life of the connection. The default is to disable untrusted X11 forwarding after twenty minutes has elapsed.`, - Value: docvalues.StringValue{}, + Value: docvalues.TimeFormatValue{}, }, "ForwardX11Trusted": { Documentation: `If this option is set to yes, remote X11 clients will have full access to the original X11 display. If this option is set to no (the default), remote X11 clients will be considered untrusted and prevented from stealing or tampering with data belonging to trusted X11 clients. Furthermore, the xauth(1) token used for the session will be set to expire after 20 minutes. Remote clients will be refused access after this time. See the X11 SECURITY extension specification for full details on the restrictions imposed on untrusted clients.`, - Value: docvalues.StringValue{}, + Value: booleanEnumValue, }, "GatewayPorts": { - Documentation: `Specifies whether remote hosts are allowed to connect to local forwarded ports. By default, ssh(1) binds local port forwardings to the loopback address. This prevents other remote hosts from connecting to forwarded ports. GatewayPorts can be used to specify that ssh should bind local port forwardings to the wildcard address, thus allowing remote hosts to connect to forwarded ports. The argument must be yes or no (the - default).`, - Value: docvalues.StringValue{}, + Documentation: `Specifies whether remote hosts are allowed to connect to local forwarded ports. By default, ssh(1) binds local port forwardings to the loopback address. This prevents other remote hosts from connecting to forwarded ports. GatewayPorts can be used to specify that ssh should bind local port forwardings to the wildcard address, thus allowing remote hosts to connect to forwarded ports. The argument must be yes or no (the default).`, + Value: booleanEnumValue, }, "GlobalKnownHostsFile": { Documentation: `Specifies one or more files to use for the global host key database, separated by whitespace. The default is /etc/ssh/ssh_known_hosts, /etc/ssh/ssh_known_hosts2.`, - Value: docvalues.StringValue{}, + Value: docvalues.ArrayValue{ + Separator: " ", + DuplicatesExtractor: &docvalues.SimpleDuplicatesExtractor, + SubValue: docvalues.PathValue{ + RequiredType: docvalues.PathTypeFile, + }, + }, }, "GSSAPIAuthentication": { Documentation: `Specifies whether user authentication based on GSSAPI is allowed. The default is no.`, - Value: docvalues.StringValue{}, + Value: booleanEnumValue, }, "GSSAPIDelegateCredentials": { Documentation: `Forward (delegate) credentials to the server. The default is no.`, - Value: docvalues.StringValue{}, + Value: booleanEnumValue, }, "HashKnownHosts": { Documentation: `Indicates that ssh(1) should hash host names and addresses when they are added to ~/.ssh/known_hosts. These hashed names may be used normally by ssh(1) and sshd(8), but they do not visually reveal identifying information if the file's contents are disclosed. The default is no. Note that existing names and addresses in known hosts files will not be converted automatically, but may be manually hashed using ssh-keygen(1).`, - Value: docvalues.StringValue{}, + Value: booleanEnumValue, }, "HostbasedAcceptedAlgorithms": { Documentation: `Specifies the signature algorithms that will be used for hostbased authentication as a comma-separated list of patterns. Alternately if the specified list begins with a ‘+’ character, then the specified signature algorithms will be appended to the default set instead of replacing them. If the specified list begins with a ‘-’ character, then the specified signature algorithms (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a ‘^’ character, then the specified signature algorithms will be placed at the head of the default set. The default for this option is: @@ -253,11 +403,22 @@ sk-ecdsa-sha2-nistp256@openssh.com, rsa-sha2-512,rsa-sha2-256 The -Q option of ssh(1) may be used to list supported signature algorithms. This was formerly named HostbasedKeyTypes.`, - Value: docvalues.StringValue{}, + Value: docvalues.CustomValue{ + FetchValue: func(_ docvalues.CustomValueContext) docvalues.Value { + options, err := ssh.QueryOpenSSHOptions("HostbasedAcceptedAlgorithms") + + if err != nil { + // Fallback + options, _ = ssh.QueryOpenSSHOptions("HostbasedAcceptedKeyTypes") + } + + return prefixPlusMinusCaret(options) + }, + }, }, "HostbasedAuthentication": { Documentation: `Specifies whether to try rhosts based authentication with public key authentication. The argument must be yes or no (the default).`, - Value: docvalues.StringValue{}, + Value: booleanEnumValue, }, "HostKeyAlgorithms": { Documentation: `Specifies the host key signature algorithms that the client wants to use in order of preference. Alternately if the specified list begins with a @@ -280,7 +441,13 @@ rsa-sha2-512,rsa-sha2-256 If hostkeys are known for the destination host then this default is modified to prefer their algorithms. The list of available signature algorithms may also be obtained using 'ssh -Q HostKeyAlgorithms'.`, - Value: docvalues.StringValue{}, + Value: docvalues.CustomValue{ + FetchValue: func(_ docvalues.CustomValueContext) docvalues.Value { + options, _ := ssh.QueryOpenSSHOptions("HostKeyAlgorithms") + + return prefixPlusMinusCaret(options) + }, + }, }, "HostKeyAlias": { Documentation: `Specifies an alias that should be used instead of the real host name when looking up or saving the host key in the host key database files and when validating host certificates. This option is useful for tunneling SSH connections or for multiple servers running on a single host.`, @@ -292,11 +459,10 @@ rsa-sha2-512,rsa-sha2-256 }, "IdentitiesOnly": { Documentation: `Specifies that ssh(1) should only use the configured authentication identity and certificate files (either the default files, or those explicitly configured in the ssh_config files or passed on the ssh(1) command-line), even if ssh-agent(1) or a PKCS11Provider or SecurityKeyProvider offers more identities. The argument to this keyword must be yes or no (the default). This option is intended for situations where ssh-agent offers many different identities.`, - Value: docvalues.StringValue{}, + Value: booleanEnumValue, }, "IdentityAgent": { - Documentation: `Specifies the UNIX-domain socket used to communicate with the authentication agent. - This option overrides the SSH_AUTH_SOCK environment variable and can be used to select a specific agent. Setting the socket name to none disables the use of an authentication agent. If the string 'SSH_AUTH_SOCK' is specified, the location of the socket will be read from the SSH_AUTH_SOCK environment variable. Otherwise if the specified value begins with a ‘$’ character, then it will be treated as an environment variable containing the location of the socket. + Documentation: `Specifies the UNIX-domain socket used to communicate with the authentication agent. This option overrides the SSH_AUTH_SOCK environment variable and can be used to select a specific agent. Setting the socket name to none disables the use of an authentication agent. If the string 'SSH_AUTH_SOCK' is specified, the location of the socket will be read from the SSH_AUTH_SOCK environment variable. Otherwise if the specified value begins with a '$' character, then it will be treated as an environment variable containing the location of the socket. Arguments to IdentityAgent may use the tilde syntax to refer to a user's home directory, the tokens described in the TOKENS section and environment variables as described in the ENVIRONMENT VARIABLES section.`, Value: docvalues.StringValue{}, }, @@ -319,19 +485,77 @@ rsa-sha2-512,rsa-sha2-256 "Include": { Documentation: `Include the specified configuration file(s). Multiple pathnames may be specified and each pathname may contain glob(7) wildcards, tokens as described in the TOKENS section, environment variables as described in the ENVIRONMENT VARIABLES section and, for user configurations, shell-like ‘~’ references to user home directories. Wildcards will be expanded and processed in lexical order. Files without absolute paths are assumed to be in ~/.ssh if included in a user configuration file or /etc/ssh if included from the system configuration file. Include directive may appear inside a Match or Host block to perform conditional inclusion.`, - Value: docvalues.StringValue{}, + Value: docvalues.ArrayValue{ + Separator: " ", + DuplicatesExtractor: &docvalues.SimpleDuplicatesExtractor, + SubValue: docvalues.StringValue{}, + }, }, "IPQoS": { Documentation: `Specifies the IPv4 type-of-service or DSCP class for connections. Accepted values are af11, af12, af13, af21, af22, af23, af31, af32, af33, af41, af42, af43, cs0, cs1, cs2, cs3, cs4, cs5, cs6, cs7, ef, le, lowdelay, throughput, reliability, a numeric value, or none to use the operating system default. This option may take one or two arguments, separated by whitespace. If one argument is specified, it is used as the packet class unconditionally. If two values are specified, the first is automatically selected for interactive sessions and the second for non-interactive sessions. The default is af21 (Low-Latency Data) for interactive sessions and cs1 (Lower Effort) for non-interactive sessions.`, - Value: docvalues.StringValue{}, + Value: docvalues.OrValue{ + Values: []docvalues.Value{ + docvalues.NumberValue{}, + docvalues.EnumValue{ + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("none"), + }, + }, + docvalues.ArrayValue{ + Separator: " ", + SubValue: docvalues.EnumValue{ + EnforceValues: true, + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("af11"), + docvalues.CreateEnumString("af12"), + docvalues.CreateEnumString("af13"), + docvalues.CreateEnumString("af21"), + docvalues.CreateEnumString("af22"), + docvalues.CreateEnumString("af23"), + docvalues.CreateEnumString("af31"), + docvalues.CreateEnumString("af32"), + docvalues.CreateEnumString("af33"), + docvalues.CreateEnumString("af41"), + docvalues.CreateEnumString("af42"), + docvalues.CreateEnumString("af43"), + docvalues.CreateEnumString("cs0"), + docvalues.CreateEnumString("cs1"), + docvalues.CreateEnumString("cs2"), + docvalues.CreateEnumString("cs3"), + docvalues.CreateEnumString("cs4"), + docvalues.CreateEnumString("cs5"), + docvalues.CreateEnumString("cs6"), + docvalues.CreateEnumString("cs7"), + docvalues.CreateEnumString("ef"), + docvalues.CreateEnumString("le"), + docvalues.CreateEnumString("lowdelay"), + docvalues.CreateEnumString("throughput"), + docvalues.CreateEnumString("reliability"), + docvalues.CreateEnumString("none"), + }, + }, + }, + }, + }, }, "KbdInteractiveAuthentication": { Documentation: `Specifies whether to use keyboard-interactive authentication. The argument to this keyword must be yes (the default) or no. ChallengeResponseAuthentication is a deprecated alias for this.`, - Value: docvalues.StringValue{}, + Value: booleanEnumValue, }, "KbdInteractiveDevices": { Documentation: `Specifies the list of methods to use in keyboard-interactive authentication. Multiple method names must be comma-separated. The default is to use the server specified list. The methods available vary depending on what the server supports. For an OpenSSH server, it may be zero or more of: bsdauth, pam, and skey.`, - Value: docvalues.StringValue{}, + Value: docvalues.ArrayValue{ + Separator: ",", + DuplicatesExtractor: &docvalues.SimpleDuplicatesExtractor, + SubValue: docvalues.EnumValue{ + EnforceValues: true, + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("bsdauth"), + docvalues.CreateEnumString("pam"), + docvalues.CreateEnumString("skey"), + }, + }, + }, }, "KexAlgorithms": { Documentation: `Specifies the permitted KEX (Key Exchange) algorithms that will be used and their preference order. The selected algorithm will be the first algorithm in this list that the server also supports. Multiple algorithms must be comma-separated. @@ -349,7 +573,21 @@ diffie-hellman-group18-sha512, diffie-hellman-group14-sha256 The list of supported key exchange algorithms may also be obtained using 'ssh -Q kex'.`, - Value: docvalues.StringValue{}, + Value: prefixPlusMinusCaret([]docvalues.EnumString{ + docvalues.CreateEnumString("curve25519-sha256"), + docvalues.CreateEnumString("curve25519-sha256@libssh.org"), + docvalues.CreateEnumString("diffie-hellman-group1-sha1"), + docvalues.CreateEnumString("diffie-hellman-group14-sha1"), + docvalues.CreateEnumString("diffie-hellman-group14-sha256"), + docvalues.CreateEnumString("diffie-hellman-group16-sha512"), + docvalues.CreateEnumString("diffie-hellman-group18-sha512"), + docvalues.CreateEnumString("diffie-hellman-group-exchange-sha1"), + docvalues.CreateEnumString("diffie-hellman-group-exchange-sha256"), + docvalues.CreateEnumString("ecdh-sha2-nistp256"), + docvalues.CreateEnumString("ecdh-sha2-nistp384"), + docvalues.CreateEnumString("ecdh-sha2-nistp521"), + docvalues.CreateEnumString("sntrup761x25519-sha512@openssh.com"), + }), }, "KnownHostsCommand": { Documentation: `Specifies a command to use to obtain a list of host keys, in addition to those listed in UserKnownHostsFile and GlobalKnownHostsFile. This command is executed after the files have been read. It may write host key lines to standard output in identical format to the usual files (described in the VERIFYING HOST KEYS section in ssh(1)). Arguments to KnownHostsCommand accept the tokens described in the TOKENS section. The command may be invoked multiple times per connection: once when preparing the preference list of host key algorithms to use, again to obtain the host key for the requested host name and, if CheckHostIP is enabled, one more time to obtain the host key matching the server's address. If the command exits abnormally or returns a non-zero exit status then the connection is terminated.`, @@ -365,11 +603,35 @@ diffie-hellman-group14-sha256 Documentation: `Specifies that a TCP port on the local machine be forwarded over the secure channel to the specified host and port from the remote machine. The first argument specifies the listener and may be [bind_address:]port or a Unix domain socket path. The second argument is the destination and may be host:hostport or a Unix domain socket path if the remote host supports it. IPv6 addresses can be specified by enclosing addresses in square brackets. Multiple forwardings may be specified, and additional forwardings can be given on the command line. Only the superuser can forward privileged ports. By default, the local port is bound in accordance with the GatewayPorts setting. However, an explicit bind_address may be used to bind the connection to a specific address. The bind_address of localhost indicates that the listening port be bound for local use only, while an empty address or ‘*’ indicates that the port should be available from all interfaces. Unix domain socket paths may use the tokens described in the TOKENS section and environment variables as described in the ENVIRONMENT VARIABLES section.`, - Value: docvalues.StringValue{}, + Value: docvalues.OrValue{ + Values: []docvalues.Value{ + docvalues.NumberValue{Min: &ZERO, Max: &MAX_PORT}, + docvalues.KeyValueAssignmentValue{ + Key: docvalues.IPAddressValue{ + AllowIPv4: true, + AllowIPv6: true, + AllowRange: false, + }, + }, + }, + }, }, "LogLevel": { Documentation: `Gives the verbosity level that is used when logging messages from ssh(1). The possible values are: QUIET, FATAL, ERROR, INFO, VERBOSE, DEBUG, DEBUG1, DEBUG2, and DEBUG3. The default is INFO. DEBUG and DEBUG1 are equivalent. DEBUG2 and DEBUG3 each specify higher levels of verbose output.`, - Value: docvalues.StringValue{}, + Value: docvalues.EnumValue{ + EnforceValues: true, + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("QUIET"), + docvalues.CreateEnumString("FATAL"), + docvalues.CreateEnumString("ERROR"), + docvalues.CreateEnumString("INFO"), + docvalues.CreateEnumString("VERBOSE"), + docvalues.CreateEnumString("DEBUG"), + docvalues.CreateEnumString("DEBUG1"), + docvalues.CreateEnumString("DEBUG2"), + docvalues.CreateEnumString("DEBUG3"), + }, + }, }, "LogVerbose": { Documentation: `Specify one or more overrides to LogLevel. An override consists of one or more pattern lists that matches the source file, function and line number to force detailed logging for. For example, an override pattern of: @@ -392,51 +654,84 @@ umac-64@openssh.com,umac-128@openssh.com, hmac-sha2-256,hmac-sha2-512,hmac-sha1 The list of available MAC algorithms may also be obtained using 'ssh -Q mac'.`, - Value: docvalues.StringValue{}, + Value: prefixPlusMinusCaret([]docvalues.EnumString{ + docvalues.CreateEnumString("hmac-md5"), + docvalues.CreateEnumString("hmac-md5-96"), + docvalues.CreateEnumString("hmac-sha1"), + docvalues.CreateEnumString("hmac-sha1-96"), + docvalues.CreateEnumString("hmac-sha2-256"), + docvalues.CreateEnumString("hmac-sha2-256"), + docvalues.CreateEnumString("hmac-sha2-512"), + docvalues.CreateEnumString("umac-64@openssh.com"), + docvalues.CreateEnumString("umac-128@openssh.com"), + docvalues.CreateEnumString("hmac-md5-etm@openssh.com"), + docvalues.CreateEnumString("hmac-md5-96-etm@openssh.com"), + docvalues.CreateEnumString("hmac-sha1-etm@openssh.com"), + docvalues.CreateEnumString("hmac-sha1-96-etm@openssh.com"), + docvalues.CreateEnumString("hmac-sha2-256-etm@openssh.com"), + docvalues.CreateEnumString("hmac-sha2-512-etm@openssh.com"), + docvalues.CreateEnumString("umac-64-etm@openssh.com"), + docvalues.CreateEnumString("umac-128-etm@openssh.com"), + }), }, "NoHostAuthenticationForLocalhost": { Documentation: `Disable host authentication for localhost (loopback addresses). The argument to this keyword must be yes or no (the default).`, - Value: docvalues.StringValue{}, + Value: booleanEnumValue, }, "NumberOfPasswordPrompts": { Documentation: `Specifies the number of password prompts before giving up. The argument to this keyword must be an integer. The default is 3.`, - Value: docvalues.StringValue{}, + Value: docvalues.PositiveNumberValue(), }, "ObscureKeystrokeTiming": { Documentation: `Specifies whether ssh(1) should try to obscure inter-keystroke timings from passive observers of network traffic. If enabled, then for interactive sessions, ssh(1) will send keystrokes at fixed intervals of a few tens of milliseconds and will send fake keystroke packets for some time after typing ceases. The argument to this keyword must be yes, no or an interval specifier of the form interval:milliseconds (e.g. interval:80 for 80 milliseconds). The default is to obscure keystrokes using a 20ms packet interval. Note that smaller intervals will result in higher fake keystroke packet rates.`, - Value: docvalues.StringValue{}, + Value: docvalues.OrValue{ + Values: []docvalues.Value{ + booleanEnumValue, + docvalues.RegexValue{ + Regex: *regexp.MustCompile(`^interval:[0-9]+$`), + }, + }, + }, }, "PasswordAuthentication": { Documentation: `Specifies whether to use password authentication. The argument to this keyword must be yes (the default) or no.`, - Value: docvalues.StringValue{}, + Value: booleanEnumValue, }, "PermitLocalCommand": { Documentation: `Allow local command execution via the LocalCommand option or using the !command escape sequence in ssh(1). The argument must be yes or no (the default).`, - Value: docvalues.StringValue{}, + Value: booleanEnumValue, }, "PermitRemoteOpen": { Documentation: `Specifies the destinations to which remote TCP port forwarding is permitted when RemoteForward is used as a SOCKS proxy. The forwarding specification must be one of the following forms: - PermitRemoteOpen host:port PermitRemoteOpen IPv4_addr:port PermitRemoteOpen - [IPv6_addr]:port + PermitRemoteOpen host:port PermitRemoteOpen IPv4_addr:port PermitRemoteOpen [IPv6_addr]:port Multiple forwards may be specified by separating them with whitespace. An argument of any can be used to remove all restrictions and permit any forwarding requests. An argument of none can be used to prohibit all forwarding requests. The wildcard ‘*’ can be used for host or port to allow all hosts or ports respectively. Otherwise, no pattern matching or address lookups are performed on supplied names.`, + // TODO: Improve Value: docvalues.StringValue{}, }, "PKCS11Provider": { Documentation: `Specifies which PKCS#11 provider to use or none to indicate that no provider should be used (the default). The argument to this keyword is a path to the PKCS#11 shared library ssh(1) should use to communicate with a PKCS#11 token providing keys for user authentication.`, - Value: docvalues.StringValue{}, + Value: booleanEnumValue, }, "Port": { Documentation: `Specifies the port number to connect on the remote host. The default is 22.`, - Value: docvalues.StringValue{}, + Value: docvalues.NumberValue{Min: &ZERO, Max: &MAX_PORT}, }, "PreferredAuthentications": { Documentation: `Specifies the order in which the client should try authentication methods. This allows a client to prefer one method (e.g. keyboard-interactive) over another method (e.g. password). The default is: - gssapi-with-mic,hostbased,publickey, -keyboard-interactive,password`, - Value: docvalues.StringValue{}, + gssapi-with-mic,hostbased,publickey,keyboard-interactive,password`, + Value: docvalues.EnumValue{ + EnforceValues: true, + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("gssapi-with-mic"), + docvalues.CreateEnumString("hostbased"), + docvalues.CreateEnumString("publickey"), + docvalues.CreateEnumString("keyboard-interactive"), + docvalues.CreateEnumString("password"), + }, + }, }, "ProxyCommand": { Documentation: `Specifies the command to use to connect to the server. The command string extends to the end of the line, and is executed using the user's shell @@ -458,7 +753,7 @@ keyboard-interactive,password`, }, "ProxyUseFdpass": { Documentation: `Specifies that ProxyCommand will pass a connected file descriptor back to ssh(1) instead of continuing to execute and pass data. The default is no.`, - Value: docvalues.StringValue{}, + Value: booleanEnumValue, }, "PubkeyAcceptedAlgorithms": { Documentation: `Specifies the signature algorithms that will be used for public key authentication as a comma-separated list of patterns. If the specified list begins with a ‘+’ character, then the algorithms after it will be appended to the default instead of replacing it. If the specified list begins with a ‘-’ character, then the specified algorithms (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a @@ -479,17 +774,28 @@ sk-ecdsa-sha2-nistp256@openssh.com, rsa-sha2-512,rsa-sha2-256 The list of available signature algorithms may also be obtained using 'ssh -Q PubkeyAcceptedAlgorithms'.`, - Value: docvalues.StringValue{}, + Value: docvalues.CustomValue{ + FetchValue: func(_ docvalues.CustomValueContext) docvalues.Value { + options, _ := ssh.QueryOpenSSHOptions("PubkeyAcceptedAlgorithms") + + return prefixPlusMinusCaret(options) + }, + }, }, "PubkeyAuthentication": { Documentation: `Specifies whether to try public key authentication. The argument to this keyword must be yes (the default), no, unbound or host-bound. The final two options enable public key authentication while respectively disabling or enabling the OpenSSH host-bound authentication protocol extension required for restricted ssh-agent(1) forwarding.`, - Value: docvalues.StringValue{}, + Value: booleanEnumValue, }, "RekeyLimit": { Documentation: `Specifies the maximum amount of data that may be transmitted or received before the session key is renegotiated, optionally followed by a maximum amount of time that may pass before the session key is renegotiated. The first argument is specified in bytes and may have a suffix of ‘K’, ‘M’, or ‘G’ to indicate Kilobytes, Megabytes, or Gigabytes, respectively. The default is between ‘1G’ and ‘4G’, depending on the cipher. The optional second value is specified in seconds and may use any of the units documented in the TIME FORMATS section of sshd_config(5). The default value for RekeyLimit is default none, which means that rekeying is performed after the cipher's default amount of data has been sent or received and no time based rekeying is done.`, - Value: docvalues.StringValue{}, + Value: docvalues.KeyValueAssignmentValue{ + Separator: " ", + ValueIsOptional: true, + Key: docvalues.DataAmountValue{}, + Value: docvalues.TimeFormatValue{}, + }, }, "RemoteCommand": { Documentation: `Specifies a command to execute on the remote machine after successfully connecting to the server. The command string extends to the end of the line, and is executed with the user's shell. Arguments to RemoteCommand accept the tokens described in the TOKENS section.`, @@ -507,11 +813,19 @@ rsa-sha2-512,rsa-sha2-256 "RequestTTY": { Documentation: `Specifies whether to request a pseudo-tty for the session. The argument may be one of: no (never request a TTY), yes (always request a TTY when standard input is a TTY), force (always request a TTY) or auto (request a TTY when opening a login session). This option mirrors the -t and -T flags for ssh(1).`, - Value: docvalues.StringValue{}, + Value: docvalues.EnumValue{ + EnforceValues: true, + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("no"), + docvalues.CreateEnumString("yes"), + docvalues.CreateEnumString("force"), + docvalues.CreateEnumString("auto"), + }, + }, }, "RequiredRSASize": { Documentation: `Specifies the minimum RSA key size (in bits) that ssh(1) will accept. User authentication keys smaller than this limit will be ignored. Servers that present host keys smaller than this limit will cause the connection to be terminated. The default is 1024 bits. Note that this limit may only be raised from the default.`, - Value: docvalues.StringValue{}, + Value: docvalues.PositiveNumberValue(), }, "RevokedHostKeys": { Documentation: `Specifies revoked host public keys. Keys listed in this file will be refused for host authentication. Note that if this file does not exist or is not readable, then host authentication will be refused for all hosts. Keys may be specified as a text file, listing one public key per line, or as an OpenSSH Key Revocation List (KRL) as generated by ssh-keygen(1). For more information on KRLs, see the KEY REVOCATION LISTS section in ssh-keygen(1). Arguments to RevokedHostKeys may use the tilde syntax to refer to a user's home directory, the tokens described in the TOKENS section and environment variables as described in the ENVIRONMENT VARIABLES section.`, @@ -520,7 +834,9 @@ rsa-sha2-512,rsa-sha2-256 "SecurityKeyProvider": { Documentation: `Specifies a path to a library that will be used when loading any FIDO authenticator-hosted keys, overriding the default of using the built-in USB HID support. If the specified value begins with a ‘$’ character, then it will be treated as an environment variable containing the path to the library.`, - Value: docvalues.StringValue{}, + Value: docvalues.PathValue{ + RequiredType: docvalues.PathTypeFile, + }, }, "SendEnv": { Documentation: `Specifies what variables from the local environ(7) should be sent to the server. The server must also support it, and the server must be configured to accept these environment variables. Note that the TERM environment variable is always sent whenever a pseudo-terminal is requested as it is required by the protocol. Refer to AcceptEnv in sshd_config(5) for how to configure the server. Variables are specified by name, which may contain wildcard characters. Multiple environment variables may be separated by whitespace or spread across multiple SendEnv directives. @@ -531,16 +847,14 @@ rsa-sha2-512,rsa-sha2-256 "ServerAliveCountMax": { Documentation: `Sets the number of server alive messages (see below) which may be sent without ssh(1) receiving any messages back from the server. If this threshold is reached while server alive messages are being sent, ssh will disconnect from the server, terminating the session. It is important to note that the use of server alive messages is very different from TCPKeepAlive (below). The server alive messages are sent through the encrypted channel and therefore will not be spoofable. The TCP keepalive option enabled by TCPKeepAlive is spoofable. The server alive mechanism is valuable when the client or server depend on knowing when a connection has become unresponsive. The default value is 3. If, for example, ServerAliveInterval (see below) is set to 15 and ServerAliveCountMax is left at the default, if the server becomes unresponsive, ssh will disconnect after approximately 45 seconds.`, - Value: docvalues.StringValue{}, + Value: docvalues.PositiveNumberValue(), }, "ServerAliveInterval": { Documentation: `Sets a timeout interval in seconds after which if no data has been received from the server, ssh(1) will send a message through the encrypted channel to request a response from the server. The default is 0, indicating that these messages will not be sent to the server.`, - Value: docvalues.StringValue{}, + Value: docvalues.PositiveNumberValue(), }, "SessionType": { - Documentation: `May be used to either request invocation of a subsystem on the remote system, or to prevent the execution of a remote command at all. The latter is useful for just forwarding ports. The argument to this keyword must be none (same as the -N option), subsystem (same as the - -s option) or default - (shell or command execution).`, + Documentation: `May be used to either request invocation of a subsystem on the remote system, or to prevent the execution of a remote command at all. The latter is useful for just forwarding ports. The argument to this keyword must be none (same as the -N option), subsystem (same as the -s option) or default (shell or command execution).`, Value: docvalues.StringValue{}, }, "SetEnv": { @@ -548,37 +862,59 @@ rsa-sha2-512,rsa-sha2-256 Value: docvalues.StringValue{}, }, "StdinNull": { - Documentation: `Redirects stdin from /dev/null (actually, prevents reading from stdin). Either this or the equivalent - -n option must be used when ssh is run in the background. The argument to this keyword must be yes (same as the - -n option) or no (the default).`, - Value: docvalues.StringValue{}, + Documentation: `Redirects stdin from /dev/null (actually, prevents reading from stdin). Either this or the equivalent -n option must be used when ssh is run in the background. The argument to this keyword must be yes (same as the -n option) or no (the default).`, + Value: booleanEnumValue, }, "StreamLocalBindMask": { Documentation: `Sets the octal file creation mode mask (umask) used when creating a Unix-domain socket file for local or remote port forwarding. This option is only used for port forwarding to a Unix-domain socket file. The default value is 0177, which creates a Unix-domain socket file that is readable and writable only by the owner. Note that not all operating systems honor the file mode on Unix-domain socket files.`, - Value: docvalues.StringValue{}, + Value: docvalues.MaskValue(), }, "StreamLocalBindUnlink": { Documentation: `Specifies whether to remove an existing Unix-domain socket file for local or remote port forwarding before creating a new one. If the socket file already exists and StreamLocalBindUnlink is not enabled, ssh will be unable to forward the port to the Unix-domain socket file. This option is only used for port forwarding to a Unix-domain socket file. The argument must be yes or no (the default).`, - Value: docvalues.StringValue{}, + Value: booleanEnumValue, }, "StrictHostKeyChecking": { Documentation: `If this flag is set to yes, ssh(1) will never automatically add host keys to the ~/.ssh/known_hosts file, and refuses to connect to hosts whose host key has changed. This provides maximum protection against man-in-the-middle (MITM) attacks, though it can be annoying when the /etc/ssh/ssh_known_hosts file is poorly maintained or when connections to new hosts are frequently made. This option forces the user to manually add all new hosts. If this flag is set to accept-new then ssh will automatically add new host keys to the user's known_hosts file, but will not permit connections to hosts with changed host keys. If this flag is set to no or off, ssh will automatically add new host keys to the user known hosts files and allow connections to hosts with changed hostkeys to proceed, subject to some restrictions. If this flag is set to ask (the default), new host keys will be added to the user known host files only after the user has confirmed that is what they really want to do, and ssh will refuse to connect to hosts whose host key has changed. The host keys of known hosts will be verified automatically in all cases.`, - Value: docvalues.StringValue{}, + Value: docvalues.EnumValue{ + EnforceValues: true, + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("yes"), + docvalues.CreateEnumString("accept-new"), + docvalues.CreateEnumString("no"), + docvalues.CreateEnumString("off"), + docvalues.CreateEnumString("ask"), + }, + }, }, "SyslogFacility": { Documentation: `Gives the facility code that is used when logging messages from ssh(1). The possible values are: DAEMON, USER, AUTH, LOCAL0, LOCAL1, LOCAL2, LOCAL3, LOCAL4, LOCAL5, LOCAL6, LOCAL7. The default is USER.`, - Value: docvalues.StringValue{}, + Value: docvalues.EnumValue{ + EnforceValues: true, + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("DAEMON"), + docvalues.CreateEnumString("USER"), + docvalues.CreateEnumString("AUTH"), + docvalues.CreateEnumString("LOCAL0"), + docvalues.CreateEnumString("LOCAL1"), + docvalues.CreateEnumString("LOCAL2"), + docvalues.CreateEnumString("LOCAL3"), + docvalues.CreateEnumString("LOCAL4"), + docvalues.CreateEnumString("LOCAL5"), + docvalues.CreateEnumString("LOCAL6"), + docvalues.CreateEnumString("LOCAL7"), + }, + }, }, "TCPKeepAlive": { Documentation: `Specifies whether the system should send TCP keepalive messages to the other side. If they are sent, death of the connection or crash of one of the machines will be properly noticed. However, this means that connections will die if the route is down temporarily, and some people find it annoying. The default is yes (to send TCP keepalive messages), and the client will notice if the network goes down or the remote host dies. This is important in scripts, and many users want it too. To disable TCP keepalive messages, the value should be set to no. See also ServerAliveInterval for protocol-level keepalives.`, - Value: docvalues.StringValue{}, + Value: booleanEnumValue, }, "Tag": { Documentation: `Specify a configuration tag name that may be later used by a Match directive to select a block of configuration.`, @@ -586,7 +922,15 @@ rsa-sha2-512,rsa-sha2-256 }, "Tunnel": { Documentation: `Request tun(4) device forwarding between the client and the server. The argument must be yes, point-to-point (layer 3), ethernet (layer 2), or no (the default). Specifying yes requests the default tunnel mode, which is point-to-point.`, - Value: docvalues.StringValue{}, + Value: docvalues.EnumValue{ + EnforceValues: true, + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("yes"), + docvalues.CreateEnumString("point-to-point"), + docvalues.CreateEnumString("ethernet"), + docvalues.CreateEnumString("no"), + }, + }, }, "TunnelDevice": { Documentation: `Specifies the tun(4) devices to open on the client @@ -602,29 +946,50 @@ rsa-sha2-512,rsa-sha2-256 If UpdateHostKeys is set to ask, then the user is asked to confirm the modifications to the known_hosts file. Confirmation is currently incompatible with ControlPersist, and will be disabled if it is enabled. Presently, only sshd(8) from OpenSSH 6.8 and greater support the 'hostkeys@openssh.com' protocol extension used to inform the client of all the server's hostkeys.`, - Value: docvalues.StringValue{}, + Value: docvalues.EnumValue{ + EnforceValues: true, + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("yes"), + docvalues.CreateEnumString("no"), + docvalues.CreateEnumString("ask"), + }, + }, }, "User": { Documentation: `Specifies the user to log in as. This can be useful when a different user name is used on different machines. This saves the trouble of having to remember to give the user name on the command line.`, - Value: docvalues.StringValue{}, + Value: docvalues.UserValue("", false), }, "UserKnownHostsFile": { Documentation: `Specifies one or more files to use for the user host key database, separated by whitespace. Each filename may use tilde notation to refer to the user's home directory, the tokens described in the TOKENS section and environment variables as described in the ENVIRONMENT VARIABLES section. A value of none causes ssh(1) to ignore any user-specific known hosts files. The default is ~/.ssh/known_hosts, ~/.ssh/known_hosts2.`, - Value: docvalues.StringValue{}, + Value: docvalues.ArrayValue{ + Separator: " ", + SubValue: docvalues.PathValue{ + RequiredType: docvalues.PathTypeFile, + }, + }, }, "VerifyHostKeyDNS": { Documentation: `Specifies whether to verify the remote key using DNS and SSHFP resource records. If this option is set to yes, the client will implicitly trust keys that match a secure fingerprint from DNS. Insecure fingerprints will be handled as if this option was set to ask. If this option is set to ask, information on fingerprint match will be displayed, but the user will still need to confirm new host keys according to the StrictHostKeyChecking option. The default is no. See also VERIFYING HOST KEYS in ssh(1).`, - Value: docvalues.StringValue{}, + Value: docvalues.EnumValue{ + EnforceValues: true, + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("yes"), + docvalues.CreateEnumString("no"), + docvalues.CreateEnumString("ask"), + }, + }, }, "VisualHostKey": { Documentation: `If this flag is set to yes, an ASCII art representation of the remote host key fingerprint is printed in addition to the fingerprint string at login and for unknown host keys. If this flag is set to no (the default), no fingerprint strings are printed at login and only the fingerprint string will be printed for unknown host keys.`, - Value: docvalues.StringValue{}, + Value: booleanEnumValue, }, "XAuthLocation": { Documentation: `Specifies the full pathname of the xauth(1) program. The default is /usr/X11R6/bin/xauth.`, - Value: docvalues.StringValue{}, + Value: docvalues.PathValue{ + RequiredType: docvalues.PathTypeFile, + }, }, } diff --git a/handlers/ssh_config/fields/utils.go b/handlers/ssh_config/fields/utils.go new file mode 100644 index 0000000..d966219 --- /dev/null +++ b/handlers/ssh_config/fields/utils.go @@ -0,0 +1,39 @@ +package fields + +import docvalues "config-lsp/doc-values" + +var booleanEnumValue = docvalues.EnumValue{ + EnforceValues: true, + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("yes"), + docvalues.CreateEnumString("no"), + }, +} + +var channelTimeoutExtractor = docvalues.ExtractKeyDuplicatesExtractor("=") + +func prefixPlusMinusCaret(values []docvalues.EnumString) docvalues.PrefixWithMeaningValue { + return docvalues.PrefixWithMeaningValue{ + Prefixes: []docvalues.Prefix{ + { + Prefix: "+", + Meaning: "Append to the default set", + }, + { + Prefix: "-", + Meaning: "Remove from the default set", + }, + { + Prefix: "^", + Meaning: "Place at the head of the default set", + }, + }, + SubValue: docvalues.ArrayValue{ + Separator: ",", + DuplicatesExtractor: &docvalues.SimpleDuplicatesExtractor, + SubValue: docvalues.EnumValue{ + Values: values, + }, + }, + } +} diff --git a/handlers/ssh_config/indexes/handlers.go b/handlers/ssh_config/indexes/handlers.go new file mode 100644 index 0000000..2502870 --- /dev/null +++ b/handlers/ssh_config/indexes/handlers.go @@ -0,0 +1,129 @@ +package indexes + +import ( + "config-lsp/common" + "config-lsp/handlers/ssh_config/ast" + "config-lsp/handlers/ssh_config/fields" + "errors" + "fmt" + "regexp" +) + +var whitespacePattern = regexp.MustCompile(`\S+`) + +func NewSSHIndexes() *SSHIndexes { + return &SSHIndexes{ + AllOptionsPerName: make(map[string](map[*ast.SSHBlock]([]*ast.SSHOption)), 0), + Includes: make([]*SSHIndexIncludeLine, 0), + } +} + +func CreateIndexes(config ast.SSHConfig) (*SSHIndexes, []common.LSPError) { + errs := make([]common.LSPError, 0) + indexes := NewSSHIndexes() + + it := config.Options.Iterator() + for it.Next() { + entry := it.Value().(ast.SSHEntry) + + switch entry.GetType() { + case ast.SSHTypeOption: + errs = append(errs, addOption(indexes, entry.GetOption(), nil)...) + case ast.SSHTypeMatch: + fallthrough + case ast.SSHTypeHost: + block := entry.(ast.SSHBlock) + + errs = append(errs, addOption(indexes, entry.GetOption(), &block)...) + + it := block.GetOptions().Iterator() + for it.Next() { + option := it.Value().(*ast.SSHOption) + + errs = append(errs, addOption(indexes, option, &block)...) + } + } + } + + // Add Includes + for block, options := range indexes.AllOptionsPerName["Include"] { + includeOption := options[0] + rawValue := includeOption.OptionValue.Value.Value + pathIndexes := whitespacePattern.FindAllStringIndex(rawValue, -1) + paths := make([]*SSHIndexIncludeValue, 0) + + for _, pathIndex := range pathIndexes { + startIndex := pathIndex[0] + endIndex := pathIndex[1] + + rawPath := rawValue[startIndex:endIndex] + + offset := includeOption.OptionValue.Start.Character + path := SSHIndexIncludeValue{ + LocationRange: common.LocationRange{ + Start: common.Location{ + Line: includeOption.Start.Line, + Character: uint32(startIndex) + offset, + }, + End: common.Location{ + Line: includeOption.Start.Line, + Character: uint32(endIndex) + offset, + }, + }, + Value: rawPath, + Paths: make([]ValidPath, 0), + } + + paths = append(paths, &path) + } + + indexes.Includes[includeOption.Start.Line] = &SSHIndexIncludeLine{ + Values: paths, + Option: includeOption, + Block: block, + } + } + + return indexes, errs +} + +func addOption( + i *SSHIndexes, + option *ast.SSHOption, + block *ast.SSHBlock, +) []common.LSPError { + var errs []common.LSPError + + if optionsMap, found := i.AllOptionsPerName[option.Key.Key]; found { + if options, found := optionsMap[block]; found { + if _, duplicatesAllowed := fields.AllowedDuplicateOptions[option.Key.Key]; !duplicatesAllowed { + firstDefinedOption := options[0] + errs = append(errs, common.LSPError{ + Range: option.Key.LocationRange, + Err: errors.New(fmt.Sprintf( + "Option '%s' has already been defined on line %d", + option.Key.Key, + firstDefinedOption.Start.Line+1, + )), + }) + } else { + i.AllOptionsPerName[option.Key.Key][block] = append( + i.AllOptionsPerName[option.Key.Key][block], + option, + ) + } + } else { + i.AllOptionsPerName[option.Key.Key][block] = []*ast.SSHOption{ + option, + } + } + } else { + i.AllOptionsPerName[option.Key.Key] = map[*ast.SSHBlock]([]*ast.SSHOption){ + block: { + option, + }, + } + } + + return errs +} diff --git a/handlers/ssh_config/ast/indexes.go b/handlers/ssh_config/indexes/indexes.go similarity index 65% rename from handlers/ssh_config/ast/indexes.go rename to handlers/ssh_config/indexes/indexes.go index 109be56..35cc82d 100644 --- a/handlers/ssh_config/ast/indexes.go +++ b/handlers/ssh_config/indexes/indexes.go @@ -1,6 +1,9 @@ -package ast +package indexes -import "config-lsp/common" +import ( + "config-lsp/common" + "config-lsp/handlers/ssh_config/ast" +) type ValidPath string @@ -19,17 +22,13 @@ type SSHIndexIncludeValue struct { type SSHIndexIncludeLine struct { Values []*SSHIndexIncludeValue - Option *SSHOption - Block *SSHBlock + Option *ast.SSHOption + Block *ast.SSHBlock } type SSHIndexes struct { + AllOptionsPerName map[string](map[*ast.SSHBlock]([]*ast.SSHOption)) + Includes []*SSHIndexIncludeLine } -func NewSSHIndexes() *SSHIndexes { - return &SSHIndexes{ - Includes: make([]*SSHIndexIncludeLine, 0), - } -} - diff --git a/handlers/ssh_config/indexes/indexes_test.go b/handlers/ssh_config/indexes/indexes_test.go new file mode 100644 index 0000000..73a6abe --- /dev/null +++ b/handlers/ssh_config/indexes/indexes_test.go @@ -0,0 +1,53 @@ +package indexes + +import ( + // "config-lsp/handlers/sshd_config/ast" + // "config-lsp/utils" + // "testing" +) + +// func TestComplexExample( +// t *testing.T, +// ) { +// input := utils.Dedent(` +// IdentityFile ~/.ssh/id_rsa +// +// Host server1 +// HostName server1.cyberciti.biz +// User nixcraft +// Port 4242 +// IdentityFile /nfs/shared/users/nixcraft/keys/server1/id_rsa +// +// ## Home nas server ## +// Host nas01 +// HostName 192.168.1.100 +// User root +// IdentityFile ~/.ssh/nas01.key +// `) +// config := ast.NewSSHDConfig() +// errors := config.Parse(input) +// +// if len(errors) > 0 { +// t.Fatalf("Expected no errors, but got %v", len(errors)) +// } +// +// indexes, errors := CreateIndexes(*config) +// +// if !(len(errors) == 1) { +// t.Fatalf("Expected one errors, but got %v", len(errors)) +// } +// +// firstMatchBlock := config.FindMatchBlock(uint32(6)) +// opts := indexes.AllOptionsPerName["PermitRootLogin"] +// if !(len(opts) == 2 && +// len(opts[nil]) == 1 && +// opts[nil][0].Value.Value == "PermitRootLogin yes" && +// opts[nil][0].Start.Line == 0 && +// len(opts[firstMatchBlock]) == 1 && +// opts[firstMatchBlock][0].Value.Value == "\tPermitRootLogin no" && +// opts[firstMatchBlock][0].Start.Line == 6 && +// opts[firstMatchBlock][0].Key.Key == "PermitRootLogin") { +// t.Errorf("Expected 3 PermitRootLogin options, but got %v", opts) +// } +// } + diff --git a/handlers/ssh_config/shared.go b/handlers/ssh_config/shared.go index f701d68..5aa8e06 100644 --- a/handlers/ssh_config/shared.go +++ b/handlers/ssh_config/shared.go @@ -2,13 +2,14 @@ package sshconfig import ( "config-lsp/handlers/ssh_config/ast" + "config-lsp/handlers/ssh_config/indexes" protocol "github.com/tliron/glsp/protocol_3_16" ) type SSHDocument struct { Config *ast.SSHConfig - Indexes *ast.SSHIndexes + Indexes *indexes.SSHIndexes } var DocumentParserMap = map[protocol.DocumentUri]*SSHDocument{} diff --git a/handlers/sshd_config/fields/fields.go b/handlers/sshd_config/fields/fields.go index 09f9536..45e4ebb 100644 --- a/handlers/sshd_config/fields/fields.go +++ b/handlers/sshd_config/fields/fields.go @@ -1,6 +1,7 @@ package fields import ( + "config-lsp/common/ssh" docvalues "config-lsp/doc-values" "regexp" ) @@ -220,7 +221,7 @@ See PATTERNS in ssh_config(5) for more information on patterns. This keyword may docvalues.CreateEnumString("x11-connection"), }, }, - Value: TimeFormatValue{}, + Value: docvalues.TimeFormatValue{}, }, }, }, @@ -325,11 +326,11 @@ See PATTERNS in ssh_config(5) for more information on patterns. This keyword may The list of available signature algorithms may also be obtained using "ssh -Q HostbasedAcceptedAlgorithms". This was formerly named HostbasedAcceptedKeyTypes.`, Value: docvalues.CustomValue{ FetchValue: func(_ docvalues.CustomValueContext) docvalues.Value { - options, err := queryOpenSSHOptions("HostbasedAcceptedAlgorithms") + options, err := ssh.QueryOpenSSHOptions("HostbasedAcceptedAlgorithms") if err != nil { // Fallback - options, _ = queryOpenSSHOptions("HostbasedAcceptedKeyTypes") + options, _ = ssh.QueryOpenSSHOptions("HostbasedAcceptedKeyTypes") } return prefixPlusMinusCaret(options) @@ -374,7 +375,7 @@ See PATTERNS in ssh_config(5) for more information on patterns. This keyword may The list of available signature algorithms may also be obtained using "ssh -Q HostKeyAlgorithms".`, Value: docvalues.CustomValue{ FetchValue: func(_ docvalues.CustomValueContext) docvalues.Value { - options, _ := queryOpenSSHOptions("HostKeyAlgorithms") + options, _ := ssh.QueryOpenSSHOptions("HostKeyAlgorithms") return prefixPlusMinusCaret(options) }, @@ -513,7 +514,7 @@ See PATTERNS in ssh_config(5) for more information on patterns. This keyword may }, "LoginGraceTime": { Documentation: `The server disconnects after this time if the user has not successfully logged in. If the value is 0, there is no time limit. The default is 120 seconds.`, - Value: TimeFormatValue{}, + Value: docvalues.TimeFormatValue{}, }, "LogLevel": { Documentation: `Gives the verbosity level that is used when logging messages from sshd(8). The possible values are: QUIET, FATAL, ERROR, INFO, VERBOSE, DEBUG, DEBUG1, DEBUG2, and DEBUG3. The default is INFO. DEBUG and DEBUG1 are equivalent. DEBUG2 and DEBUG3 each specify higher levels of debugging output. Logging with a DEBUG level violates the privacy of users and is not recommended.`, @@ -790,7 +791,7 @@ Only a subset of keywords may be used on the lines following a Match keyword. Av The list of available signature algorithms may also be obtained using "ssh -Q PubkeyAcceptedAlgorithms".`, Value: docvalues.CustomValue{ FetchValue: func(_ docvalues.CustomValueContext) docvalues.Value { - options, _ := queryOpenSSHOptions("PubkeyAcceptedAlgorithms") + options, _ := ssh.QueryOpenSSHOptions("PubkeyAcceptedAlgorithms") return prefixPlusMinusCaret(options) }, @@ -822,8 +823,8 @@ Only a subset of keywords may be used on the lines following a Match keyword. Av Value: docvalues.KeyValueAssignmentValue{ Separator: " ", ValueIsOptional: true, - Key: DataAmountValue{}, - Value: TimeFormatValue{}, + Key: docvalues.DataAmountValue{}, + Value: docvalues.TimeFormatValue{}, }, }, "RequiredRSASize": { @@ -925,7 +926,7 @@ Only a subset of keywords may be used on the lines following a Match keyword. Av Documentation: `Specifies whether and how quickly sshd(8) should close client connections with no open channels. Open channels include active shell, command execution or subsystem sessions, connected network, socket, agent or X11 forwardings. Forwarding listeners, such as those from the ssh(1) -R flag, are not considered as open channels and do not prevent the timeout. The timeout value is specified in seconds or may use any of the units documented in the “TIME FORMATS” section. Note that this timeout starts when the client connection completes user authentication but before the client has an opportunity to open any channels. Caution should be used when using short timeout values, as they may not provide sufficient time for the client to request and open its channels before terminating the connection. The default none is to never expire connections for having no open channels. This option may be useful in conjunction with ChannelTimeout.`, - Value: TimeFormatValue{}, + Value: docvalues.TimeFormatValue{}, }, "UseDNS": { Documentation: `Specifies whether sshd(8) should look up the remote host name, and to check that the resolved host name for the remote IP address maps back to the very same IP address. diff --git a/handlers/sshd_config/fields/utils.go b/handlers/sshd_config/fields/utils.go index eb092d0..a9c8189 100644 --- a/handlers/sshd_config/fields/utils.go +++ b/handlers/sshd_config/fields/utils.go @@ -2,14 +2,8 @@ package fields import ( docvalues "config-lsp/doc-values" - "config-lsp/utils" - "os/exec" - "regexp" - "strings" ) -var isJustDigitsPattern = regexp.MustCompile(`^\d+$`) - var booleanEnumValue = docvalues.EnumValue{ EnforceValues: true, Values: []docvalues.EnumString{ @@ -18,21 +12,6 @@ var booleanEnumValue = docvalues.EnumValue{ }, } -var plusMinuxCaretPrefixes = []docvalues.Prefix{ - { - Prefix: "+", - Meaning: "Append to the default set", - }, - { - Prefix: "-", - Meaning: "Remove from the default set", - }, - { - Prefix: "^", - Meaning: "Place at the head of the default set", - }, -} - var channelTimeoutExtractor = docvalues.ExtractKeyDuplicatesExtractor("=") var setEnvExtractor = docvalues.ExtractKeyDuplicatesExtractor("=") @@ -61,39 +40,3 @@ func prefixPlusMinusCaret(values []docvalues.EnumString) docvalues.PrefixWithMea }, } } - -var _cachedQueries map[string][]docvalues.EnumString = make(map[string][]docvalues.EnumString) - -func queryValues(query string) ([]string, error) { - cmd := exec.Command("ssh", "-Q", query) - - output, err := cmd.Output() - - if err != nil { - return []string{}, err - } - - return strings.Split(string(output), "\n"), nil -} - -func queryOpenSSHOptions( - query string, -) ([]docvalues.EnumString, error) { - var availableQueries []docvalues.EnumString - key := query - - if _cachedQueries[key] != nil && len(_cachedQueries[key]) > 0 { - return _cachedQueries[key], nil - } else { - availableRawQueries, err := queryValues(query) - availableQueries = utils.Map(availableRawQueries, docvalues.CreateEnumString) - - if err != nil { - return []docvalues.EnumString{}, err - } - - _cachedQueries[key] = availableQueries - } - - return availableQueries, nil -} From 6608375b9ec8a75950d0c8d20ed3180115987d33 Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Sun, 22 Sep 2024 18:45:57 +0200 Subject: [PATCH 078/133] feat(ssh_config): Add LSP glue to ssh_config --- handlers/ssh_config/analyzer/analyzer.go | 12 +++++ handlers/ssh_config/lsp/README.md | 7 +++ .../lsp/text-document-completion.go | 10 ++++ .../lsp/text-document-definition.go | 10 ++++ .../lsp/text-document-did-change.go | 42 +++++++++++++++ .../ssh_config/lsp/text-document-did-close.go | 13 +++++ .../ssh_config/lsp/text-document-did-open.go | 51 +++++++++++++++++++ .../ssh_config/lsp/text-document-hover.go | 13 +++++ .../lsp/text-document-range-formatting.go | 13 +++++ .../lsp/text-document-signature-help.go | 10 ++++ root-handler/lsp-utils.go | 14 ++++- root-handler/text-document-code-action.go | 2 + root-handler/text-document-completion.go | 3 ++ root-handler/text-document-definition.go | 3 ++ root-handler/text-document-did-change.go | 5 ++ root-handler/text-document-did-close.go | 5 ++ root-handler/text-document-did-open.go | 3 ++ root-handler/text-document-hover.go | 3 ++ root-handler/text-document-prepare-rename.go | 2 + .../text-document-range-formatting.go | 4 ++ root-handler/text-document-rename.go | 2 + root-handler/text-document-signature-help.go | 2 + 22 files changed, 227 insertions(+), 2 deletions(-) create mode 100644 handlers/ssh_config/analyzer/analyzer.go create mode 100644 handlers/ssh_config/lsp/README.md create mode 100644 handlers/ssh_config/lsp/text-document-completion.go create mode 100644 handlers/ssh_config/lsp/text-document-definition.go create mode 100644 handlers/ssh_config/lsp/text-document-did-change.go create mode 100644 handlers/ssh_config/lsp/text-document-did-close.go create mode 100644 handlers/ssh_config/lsp/text-document-did-open.go create mode 100644 handlers/ssh_config/lsp/text-document-hover.go create mode 100644 handlers/ssh_config/lsp/text-document-range-formatting.go create mode 100644 handlers/ssh_config/lsp/text-document-signature-help.go diff --git a/handlers/ssh_config/analyzer/analyzer.go b/handlers/ssh_config/analyzer/analyzer.go new file mode 100644 index 0000000..dd789d0 --- /dev/null +++ b/handlers/ssh_config/analyzer/analyzer.go @@ -0,0 +1,12 @@ +package analyzer + +import ( + sshconfig "config-lsp/handlers/ssh_config" + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func Analyze( + d *sshconfig.SSHDocument, +) []protocol.Diagnostic { + return nil +} diff --git a/handlers/ssh_config/lsp/README.md b/handlers/ssh_config/lsp/README.md new file mode 100644 index 0000000..2aa9542 --- /dev/null +++ b/handlers/ssh_config/lsp/README.md @@ -0,0 +1,7 @@ +# /sshd_config/lsp + +This folder is the glue between our language server and the LSP +clients. +This folder only contains LSP commands. +It only handles very little actual logic, and instead calls +the handlers from `../handlers`. \ No newline at end of file diff --git a/handlers/ssh_config/lsp/text-document-completion.go b/handlers/ssh_config/lsp/text-document-completion.go new file mode 100644 index 0000000..5c5b64a --- /dev/null +++ b/handlers/ssh_config/lsp/text-document-completion.go @@ -0,0 +1,10 @@ +package lsp + +import ( + "github.com/tliron/glsp" + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func TextDocumentCompletion(context *glsp.Context, params *protocol.CompletionParams) (any, error) { + return nil, nil +} diff --git a/handlers/ssh_config/lsp/text-document-definition.go b/handlers/ssh_config/lsp/text-document-definition.go new file mode 100644 index 0000000..4e73e2c --- /dev/null +++ b/handlers/ssh_config/lsp/text-document-definition.go @@ -0,0 +1,10 @@ +package lsp + +import ( + "github.com/tliron/glsp" + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func TextDocumentDefinition(context *glsp.Context, params *protocol.DefinitionParams) ([]protocol.Location, error) { + return nil, nil +} diff --git a/handlers/ssh_config/lsp/text-document-did-change.go b/handlers/ssh_config/lsp/text-document-did-change.go new file mode 100644 index 0000000..7650bab --- /dev/null +++ b/handlers/ssh_config/lsp/text-document-did-change.go @@ -0,0 +1,42 @@ +package lsp + +import ( + "config-lsp/common" + sshconfig "config-lsp/handlers/ssh_config" + "config-lsp/handlers/ssh_config/analyzer" + "config-lsp/utils" + + "github.com/tliron/glsp" + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func TextDocumentDidChange( + context *glsp.Context, + params *protocol.DidChangeTextDocumentParams, +) error { + content := params.ContentChanges[0].(protocol.TextDocumentContentChangeEventWhole).Text + common.ClearDiagnostics(context, params.TextDocument.URI) + + document := sshconfig.DocumentParserMap[params.TextDocument.URI] + document.Config.Clear() + + diagnostics := make([]protocol.Diagnostic, 0) + errors := document.Config.Parse(content) + + if len(errors) > 0 { + diagnostics = append(diagnostics, utils.Map( + errors, + func(err common.LSPError) protocol.Diagnostic { + return err.ToDiagnostic() + }, + )...) + } + + diagnostics = append(diagnostics, analyzer.Analyze(document)...) + + if len(diagnostics) > 0 { + common.SendDiagnostics(context, params.TextDocument.URI, diagnostics) + } + + return nil +} diff --git a/handlers/ssh_config/lsp/text-document-did-close.go b/handlers/ssh_config/lsp/text-document-did-close.go new file mode 100644 index 0000000..49d7ba4 --- /dev/null +++ b/handlers/ssh_config/lsp/text-document-did-close.go @@ -0,0 +1,13 @@ +package lsp + +import ( + "config-lsp/handlers/ssh_config" + "github.com/tliron/glsp" + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func TextDocumentDidClose(context *glsp.Context, params *protocol.DidCloseTextDocumentParams) error { + delete(sshconfig.DocumentParserMap, params.TextDocument.URI) + + return nil +} diff --git a/handlers/ssh_config/lsp/text-document-did-open.go b/handlers/ssh_config/lsp/text-document-did-open.go new file mode 100644 index 0000000..d37a78f --- /dev/null +++ b/handlers/ssh_config/lsp/text-document-did-open.go @@ -0,0 +1,51 @@ +package lsp + +import ( + "config-lsp/common" + "config-lsp/handlers/ssh_config" + "config-lsp/handlers/ssh_config/ast" + "config-lsp/handlers/ssh_config/analyzer" + "config-lsp/utils" + + "github.com/tliron/glsp" + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func TextDocumentDidOpen( + context *glsp.Context, + params *protocol.DidOpenTextDocumentParams, +) error { + common.ClearDiagnostics(context, params.TextDocument.URI) + + var document *sshconfig.SSHDocument + + if foundDocument, ok := sshconfig.DocumentParserMap[params.TextDocument.URI]; ok { + document = foundDocument + } else { + config := ast.NewSSHConfig() + document = &sshconfig.SSHDocument{ + Config: config, + } + sshconfig.DocumentParserMap[params.TextDocument.URI] = document + } + + errors := document.Config.Parse(params.TextDocument.Text) + + diagnostics := utils.Map( + errors, + func(err common.LSPError) protocol.Diagnostic { + return err.ToDiagnostic() + }, + ) + + diagnostics = append( + diagnostics, + analyzer.Analyze(document)..., + ) + + if len(diagnostics) > 0 { + common.SendDiagnostics(context, params.TextDocument.URI, diagnostics) + } + + return nil +} diff --git a/handlers/ssh_config/lsp/text-document-hover.go b/handlers/ssh_config/lsp/text-document-hover.go new file mode 100644 index 0000000..61d19cd --- /dev/null +++ b/handlers/ssh_config/lsp/text-document-hover.go @@ -0,0 +1,13 @@ +package lsp + +import ( + "github.com/tliron/glsp" + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func TextDocumentHover( + context *glsp.Context, + params *protocol.HoverParams, +) (*protocol.Hover, error) { + return nil, nil +} diff --git a/handlers/ssh_config/lsp/text-document-range-formatting.go b/handlers/ssh_config/lsp/text-document-range-formatting.go new file mode 100644 index 0000000..8cb8549 --- /dev/null +++ b/handlers/ssh_config/lsp/text-document-range-formatting.go @@ -0,0 +1,13 @@ +package lsp + +import ( + "github.com/tliron/glsp" + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func TextDocumentRangeFormatting( + context *glsp.Context, + params *protocol.DocumentRangeFormattingParams, +) ([]protocol.TextEdit, error) { + return nil, nil +} diff --git a/handlers/ssh_config/lsp/text-document-signature-help.go b/handlers/ssh_config/lsp/text-document-signature-help.go new file mode 100644 index 0000000..eff0052 --- /dev/null +++ b/handlers/ssh_config/lsp/text-document-signature-help.go @@ -0,0 +1,10 @@ +package lsp + +import ( + "github.com/tliron/glsp" + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func TextDocumentSignatureHelp(context *glsp.Context, params *protocol.SignatureHelpParams) (*protocol.SignatureHelp, error) { + return nil, nil +} diff --git a/root-handler/lsp-utils.go b/root-handler/lsp-utils.go index 8a5b7c6..f2e22e5 100644 --- a/root-handler/lsp-utils.go +++ b/root-handler/lsp-utils.go @@ -13,6 +13,7 @@ import ( type SupportedLanguage string const ( + LanguageSSHConfig SupportedLanguage = "ssh_config" LanguageSSHDConfig SupportedLanguage = "sshd_config" LanguageFstab SupportedLanguage = "fstab" LanguageWireguard SupportedLanguage = "languagewireguard" @@ -21,6 +22,7 @@ const ( ) var AllSupportedLanguages = []string{ + string(LanguageSSHConfig), string(LanguageSSHDConfig), string(LanguageFstab), string(LanguageWireguard), @@ -54,8 +56,12 @@ func (e LanguageUndetectableError) Error() string { var valueToLanguageMap = map[string]SupportedLanguage{ "sshd_config": LanguageSSHDConfig, "sshdconfig": LanguageSSHDConfig, - "ssh_config": LanguageSSHDConfig, - "sshconfig": LanguageSSHDConfig, + + "ssh_config": LanguageSSHConfig, + "sshconfig": LanguageSSHConfig, + + ".ssh/config": LanguageSSHConfig, + "~/.ssh/config": LanguageSSHConfig, "fstab": LanguageFstab, "etc/fstab": LanguageFstab, @@ -124,5 +130,9 @@ func DetectLanguage( return LanguageWireguard, nil } + if strings.HasSuffix(uri, ".ssh/config") { + return LanguageSSHConfig, nil + } + return "", undetectableError } diff --git a/root-handler/text-document-code-action.go b/root-handler/text-document-code-action.go index f1da029..ac385ad 100644 --- a/root-handler/text-document-code-action.go +++ b/root-handler/text-document-code-action.go @@ -29,6 +29,8 @@ func TextDocumentCodeAction(context *glsp.Context, params *protocol.CodeActionPa return hosts.TextDocumentCodeAction(context, params) case LanguageSSHDConfig: return nil, nil + case LanguageSSHConfig: + return nil, nil case LanguageWireguard: return wireguard.TextDocumentCodeAction(context, params) case LanguageAliases: diff --git a/root-handler/text-document-completion.go b/root-handler/text-document-completion.go index 6b5a2f2..a82a4eb 100644 --- a/root-handler/text-document-completion.go +++ b/root-handler/text-document-completion.go @@ -4,6 +4,7 @@ import ( aliases "config-lsp/handlers/aliases/lsp" fstab "config-lsp/handlers/fstab/lsp" hosts "config-lsp/handlers/hosts/lsp" + sshconfig "config-lsp/handlers/ssh_config/lsp" sshdconfig "config-lsp/handlers/sshd_config/lsp" wireguard "config-lsp/handlers/wireguard/lsp" @@ -29,6 +30,8 @@ func TextDocumentCompletion(context *glsp.Context, params *protocol.CompletionPa return fstab.TextDocumentCompletion(context, params) case LanguageSSHDConfig: return sshdconfig.TextDocumentCompletion(context, params) + case LanguageSSHConfig: + return sshconfig.TextDocumentCompletion(context, params) case LanguageWireguard: return wireguard.TextDocumentCompletion(context, params) case LanguageHosts: diff --git a/root-handler/text-document-definition.go b/root-handler/text-document-definition.go index 70e7b6a..593cfad 100644 --- a/root-handler/text-document-definition.go +++ b/root-handler/text-document-definition.go @@ -2,6 +2,7 @@ package roothandler import ( aliases "config-lsp/handlers/aliases/lsp" + sshconfig "config-lsp/handlers/ssh_config/lsp" sshdconfig "config-lsp/handlers/sshd_config/lsp" "github.com/tliron/glsp" @@ -26,6 +27,8 @@ func TextDocumentDefinition(context *glsp.Context, params *protocol.DefinitionPa return nil, nil case LanguageSSHDConfig: return sshdconfig.TextDocumentDefinition(context, params) + case LanguageSSHConfig: + return sshconfig.TextDocumentDefinition(context, params) case LanguageFstab: return nil, nil case LanguageWireguard: diff --git a/root-handler/text-document-did-change.go b/root-handler/text-document-did-change.go index 295a091..caaab6d 100644 --- a/root-handler/text-document-did-change.go +++ b/root-handler/text-document-did-change.go @@ -5,6 +5,7 @@ import ( fstab "config-lsp/handlers/fstab/lsp" hosts "config-lsp/handlers/hosts/lsp" sshdconfig "config-lsp/handlers/sshd_config/lsp" + sshconfig "config-lsp/handlers/ssh_config/lsp" wireguard "config-lsp/handlers/wireguard/lsp" "github.com/tliron/glsp" @@ -43,6 +44,8 @@ func TextDocumentDidChange(context *glsp.Context, params *protocol.DidChangeText return fstab.TextDocumentDidOpen(context, params) case LanguageSSHDConfig: return sshdconfig.TextDocumentDidOpen(context, params) + case LanguageSSHConfig: + return sshconfig.TextDocumentDidOpen(context, params) case LanguageWireguard: return wireguard.TextDocumentDidOpen(context, params) case LanguageHosts: @@ -57,6 +60,8 @@ func TextDocumentDidChange(context *glsp.Context, params *protocol.DidChangeText return fstab.TextDocumentDidChange(context, params) case LanguageSSHDConfig: return sshdconfig.TextDocumentDidChange(context, params) + case LanguageSSHConfig: + return sshconfig.TextDocumentDidChange(context, params) case LanguageWireguard: return wireguard.TextDocumentDidChange(context, params) case LanguageHosts: diff --git a/root-handler/text-document-did-close.go b/root-handler/text-document-did-close.go index 0d56091..724d9a6 100644 --- a/root-handler/text-document-did-close.go +++ b/root-handler/text-document-did-close.go @@ -4,6 +4,8 @@ import ( aliases "config-lsp/handlers/aliases/lsp" fstab "config-lsp/handlers/fstab/lsp" hosts "config-lsp/handlers/hosts/lsp" + sshconfig "config-lsp/handlers/ssh_config/lsp" + sshdconfig "config-lsp/handlers/sshd_config/lsp" wireguard "config-lsp/handlers/wireguard/lsp" "github.com/tliron/glsp" @@ -28,6 +30,9 @@ func TextDocumentDidClose(context *glsp.Context, params *protocol.DidCloseTextDo switch *language { case LanguageSSHDConfig: + return sshdconfig.TextDocumentDidClose(context, params) + case LanguageSSHConfig: + return sshconfig.TextDocumentDidClose(context, params) case LanguageFstab: return fstab.TextDocumentDidClose(context, params) case LanguageWireguard: diff --git a/root-handler/text-document-did-open.go b/root-handler/text-document-did-open.go index 3d18585..68365f6 100644 --- a/root-handler/text-document-did-open.go +++ b/root-handler/text-document-did-open.go @@ -7,6 +7,7 @@ import ( aliases "config-lsp/handlers/aliases/lsp" fstab "config-lsp/handlers/fstab/lsp" hosts "config-lsp/handlers/hosts/lsp" + sshconfig "config-lsp/handlers/ssh_config/lsp" sshdconfig "config-lsp/handlers/sshd_config/lsp" wireguard "config-lsp/handlers/wireguard/lsp" @@ -35,6 +36,8 @@ func TextDocumentDidOpen(context *glsp.Context, params *protocol.DidOpenTextDocu return fstab.TextDocumentDidOpen(context, params) case LanguageSSHDConfig: return sshdconfig.TextDocumentDidOpen(context, params) + case LanguageSSHConfig: + return sshconfig.TextDocumentDidOpen(context, params) case LanguageWireguard: return wireguard.TextDocumentDidOpen(context, params) case LanguageHosts: diff --git a/root-handler/text-document-hover.go b/root-handler/text-document-hover.go index da9a971..72f6c65 100644 --- a/root-handler/text-document-hover.go +++ b/root-handler/text-document-hover.go @@ -4,6 +4,7 @@ import ( aliases "config-lsp/handlers/aliases/lsp" fstab "config-lsp/handlers/fstab/lsp" hosts "config-lsp/handlers/hosts/lsp" + sshconfig "config-lsp/handlers/ssh_config/lsp" sshdconfig "config-lsp/handlers/sshd_config/lsp" wireguard "config-lsp/handlers/wireguard/lsp" @@ -29,6 +30,8 @@ func TextDocumentHover(context *glsp.Context, params *protocol.HoverParams) (*pr return hosts.TextDocumentHover(context, params) case LanguageSSHDConfig: return sshdconfig.TextDocumentHover(context, params) + case LanguageSSHConfig: + return sshconfig.TextDocumentHover(context, params) case LanguageFstab: return fstab.TextDocumentHover(context, params) case LanguageWireguard: diff --git a/root-handler/text-document-prepare-rename.go b/root-handler/text-document-prepare-rename.go index 6dbc75a..710fc9b 100644 --- a/root-handler/text-document-prepare-rename.go +++ b/root-handler/text-document-prepare-rename.go @@ -25,6 +25,8 @@ func TextDocumentPrepareRename(context *glsp.Context, params *protocol.PrepareRe return nil, nil case LanguageSSHDConfig: return nil, nil + case LanguageSSHConfig: + return nil, nil case LanguageFstab: return nil, nil case LanguageWireguard: diff --git a/root-handler/text-document-range-formatting.go b/root-handler/text-document-range-formatting.go index 6b4cff6..5f917f2 100644 --- a/root-handler/text-document-range-formatting.go +++ b/root-handler/text-document-range-formatting.go @@ -1,7 +1,9 @@ package roothandler import ( + sshconfig "config-lsp/handlers/ssh_config/lsp" sshdconfig "config-lsp/handlers/sshd_config/lsp" + "github.com/tliron/glsp" protocol "github.com/tliron/glsp/protocol_3_16" ) @@ -27,6 +29,8 @@ func TextDocumentRangeFormattingFunc( return nil, nil case LanguageSSHDConfig: return sshdconfig.TextDocumentRangeFormatting(context, params) + case LanguageSSHConfig: + return sshconfig.TextDocumentRangeFormatting(context, params) case LanguageFstab: return nil, nil case LanguageWireguard: diff --git a/root-handler/text-document-rename.go b/root-handler/text-document-rename.go index 5a41135..9bdfafd 100644 --- a/root-handler/text-document-rename.go +++ b/root-handler/text-document-rename.go @@ -24,6 +24,8 @@ func TextDocumentRename(context *glsp.Context, params *protocol.RenameParams) (* return nil, nil case LanguageSSHDConfig: return nil, nil + case LanguageSSHConfig: + return nil, nil case LanguageFstab: return nil, nil case LanguageWireguard: diff --git a/root-handler/text-document-signature-help.go b/root-handler/text-document-signature-help.go index 3fb742e..0e6ca33 100644 --- a/root-handler/text-document-signature-help.go +++ b/root-handler/text-document-signature-help.go @@ -26,6 +26,8 @@ func TextDocumentSignatureHelp(context *glsp.Context, params *protocol.Signature return nil, nil case LanguageSSHDConfig: return sshdconfig.TextDocumentSignatureHelp(context, params) + case LanguageSSHConfig: + return nil, nil case LanguageFstab: return nil, nil case LanguageWireguard: From 92b2f12e3f13e39395e80a4602be1a984eeeb6e4 Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Sun, 22 Sep 2024 22:14:10 +0200 Subject: [PATCH 079/133] feat(ssh_config): Overall improvements --- handlers/ssh_config/ast/listener.go | 1 + .../ssh_config/ast/ssh_cofig_fields_test.go | 54 +++++++++ handlers/ssh_config/ast/ssh_config_fields.go | 109 ++++++++++++++++++ handlers/ssh_config/document_fields.go | 31 +++++ handlers/ssh_config/handlers/completions.go | 59 ++++++++++ handlers/ssh_config/indexes/indexes.go | 6 +- .../{handlers.go => indexes_handlers.go} | 10 +- .../lsp/text-document-completion.go | 40 +++++++ handlers/ssh_config/shared.go | 3 +- .../sshd_config/ast/sshd_config_fields.go | 1 - handlers/sshd_config/handlers/completions.go | 22 ++-- 11 files changed, 313 insertions(+), 23 deletions(-) create mode 100644 handlers/ssh_config/ast/ssh_cofig_fields_test.go create mode 100644 handlers/ssh_config/document_fields.go create mode 100644 handlers/ssh_config/handlers/completions.go rename handlers/ssh_config/indexes/{handlers.go => indexes_handlers.go} (90%) diff --git a/handlers/ssh_config/ast/listener.go b/handlers/ssh_config/ast/listener.go index f9dff36..0043422 100644 --- a/handlers/ssh_config/ast/listener.go +++ b/handlers/ssh_config/ast/listener.go @@ -152,6 +152,7 @@ func (s *sshParserListener) ExitEntry(ctx *parser.EntryContext) { s.sshContext.currentKeyIsBlockOf = nil s.sshContext.currentBlock = matchBlock + case SSHBlockTypeHost: var host *hostparser.Host diff --git a/handlers/ssh_config/ast/ssh_cofig_fields_test.go b/handlers/ssh_config/ast/ssh_cofig_fields_test.go new file mode 100644 index 0000000..eeba4a9 --- /dev/null +++ b/handlers/ssh_config/ast/ssh_cofig_fields_test.go @@ -0,0 +1,54 @@ +package ast + +import ( + "config-lsp/utils" + "testing" +) + +func TestComplexExampleRetrievesCorrectly( + t *testing.T, +) { + input := utils.Dedent(` +Port 22 + +Host laptop + HostName laptop.lan + +Match originalhost laptop exec "[[ $(/usr/bin/dig +short laptop.lan) == '' ]]" + HostName laptop.sdn + `) + + p := NewSSHConfig() + errors := p.Parse(input) + + if len(errors) != 0 { + t.Fatalf("Expected no errors, got %v", errors) + } + + firstOption, firstBlock := p.FindOption(0) + if !(firstOption.Value.Raw == "Port 22") { + t.Errorf("Expected Port 22, got %v", firstOption.Value.Raw) + } + + if !(firstBlock == nil) { + t.Errorf("Expected no block, got %v", firstBlock) + } + + secondOption, secondBlock := p.FindOption(3) + if !(secondOption.Value.Raw == " HostName laptop.lan") { + t.Errorf("Expected HostName laptop.lan, got %v", secondOption.Value.Raw) + } + + if !(secondBlock.GetLocation().Start.Line == 2) { + t.Errorf("Expected line 2, got %v", secondBlock.GetLocation().Start.Line) + } + + thirdOption, thirdBlock := p.FindOption(6) + if !(thirdOption.Value.Raw == " HostName laptop.sdn") { + t.Errorf("Expected HostName laptop.sdn, got %v", thirdOption.Value.Raw) + } + + if !(thirdBlock.GetLocation().Start.Line == 5) { + t.Errorf("Expected line 3, got %v", thirdBlock.GetLocation().Start.Line) + } +} diff --git a/handlers/ssh_config/ast/ssh_config_fields.go b/handlers/ssh_config/ast/ssh_config_fields.go index ec5ccd0..7902b21 100644 --- a/handlers/ssh_config/ast/ssh_config_fields.go +++ b/handlers/ssh_config/ast/ssh_config_fields.go @@ -18,6 +18,8 @@ type SSHBlock interface { AddOption(option *SSHOption) SetEnd(common.Location) GetOptions() *treemap.Map + GetEntryOption() *SSHOption + GetLocation() common.LocationRange } func (b *SSHMatchBlock) GetBlockType() SSHBlockType { @@ -36,6 +38,14 @@ func (b *SSHMatchBlock) GetOptions() *treemap.Map { return b.Options } +func (b *SSHMatchBlock) GetEntryOption() *SSHOption { + return b.MatchOption +} + +func (b *SSHMatchBlock) GetLocation() common.LocationRange { + return b.LocationRange +} + func (b *SSHHostBlock) GetBlockType() SSHBlockType { return SSHBlockTypeHost } @@ -52,6 +62,14 @@ func (b *SSHHostBlock) GetOptions() *treemap.Map { return b.Options } +func (b *SSHHostBlock) GetEntryOption() *SSHOption { + return b.HostOption +} + +func (b *SSHHostBlock) GetLocation() common.LocationRange { + return b.LocationRange +} + type SSHType uint8 const ( @@ -88,3 +106,94 @@ func (b *SSHHostBlock) GetType() SSHType { func (b *SSHHostBlock) GetOption() *SSHOption { return b.HostOption } + +func (c SSHConfig) FindBlock(line uint32) SSHBlock { + it := c.Options.Iterator() + for it.Next() { + entry := it.Value().(SSHEntry) + + if entry.GetType() == SSHTypeOption { + continue + } + + block := entry.(SSHBlock) + + if block.GetLocation().Start.Line <= line && block.GetLocation().End.Line >= line { + return block + } + } + + return nil +} + +func (c SSHConfig) FindOption(line uint32) (*SSHOption, SSHBlock) { + block := c.FindBlock(line) + + var option *SSHOption + + if block == nil { + if rawOption, found := c.Options.Get(line); found { + option = rawOption.(*SSHOption) + } + } else { + if rawOption, found := block.GetOptions().Get(line); found { + option = rawOption.(*SSHOption) + } + } + + return option, block +} + +type AllOptionInfo struct { + Block SSHBlock + Option *SSHOption +} + +func (c SSHConfig) GetAllOptions() []AllOptionInfo { + options := make([]AllOptionInfo, 0, 50) + + for _, rawEntry := range c.Options.Values() { + switch rawEntry.(type) { + case *SSHOption: + option := rawEntry.(*SSHOption) + options = append(options, AllOptionInfo{ + Block: nil, + Option: option, + }) + case *SSHMatchBlock: + block := rawEntry.(SSHBlock) + + options = append(options, AllOptionInfo{ + Block: block, + Option: block.GetEntryOption(), + }) + + for _, rawOption := range block.GetOptions().Values() { + option := rawOption.(*SSHOption) + options = append(options, AllOptionInfo{ + Block: nil, + Option: option, + }) + } + case *SSHHostBlock: + block := rawEntry.(SSHBlock) + + options = append(options, AllOptionInfo{ + Block: block, + Option: block.GetEntryOption(), + }) + + for _, rawOption := range block.GetOptions().Values() { + option := rawOption.(*SSHOption) + options = append(options, AllOptionInfo{ + Block: nil, + Option: option, + }) + } + } + + } + + return options +} + diff --git a/handlers/ssh_config/document_fields.go b/handlers/ssh_config/document_fields.go new file mode 100644 index 0000000..4c6795f --- /dev/null +++ b/handlers/ssh_config/document_fields.go @@ -0,0 +1,31 @@ +package sshconfig + +import "config-lsp/handlers/ssh_config/ast" + +func (d SSHDocument) FindOptionByNameAndBlock( + name string, + block ast.SSHBlock, +) *ast.AllOptionInfo { + for _, info := range d.FindOptionsByName(name) { + if info.Block == block { + return &info + } + } + + return nil +} + +func (d SSHDocument) FindOptionsByName( + name string, +) []ast.AllOptionInfo { + options := make([]ast.AllOptionInfo, 0, 5) + + for _, info := range d.Config.GetAllOptions() { + if info.Option.Key.Key == name { + options = append(options, info) + } + } + + return options +} + diff --git a/handlers/ssh_config/handlers/completions.go b/handlers/ssh_config/handlers/completions.go new file mode 100644 index 0000000..e6236c6 --- /dev/null +++ b/handlers/ssh_config/handlers/completions.go @@ -0,0 +1,59 @@ +package handlers + +import ( + docvalues "config-lsp/doc-values" + sshconfig "config-lsp/handlers/ssh_config" + "config-lsp/handlers/ssh_config/ast" + "config-lsp/handlers/ssh_config/fields" + "config-lsp/utils" + + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func GetRootCompletions( + d *sshconfig.SSHDocument, + parentBlock ast.SSHBlock, + suggestValue bool, +) ([]protocol.CompletionItem, error) { + kind := protocol.CompletionItemKindField + + availableOptions := make(map[string]docvalues.DocumentationValue, 0) + + for key, option := range fields.Options { + alreadyExists := d.FindOptionByNameAndBlock(key, parentBlock) != nil + + if !alreadyExists || utils.KeyExists(fields.AllowedDuplicateOptions, key) { + availableOptions[key] = option + } + } + + // Remove all fields that are already present and are not allowed to be duplicated + for _, info := range d.Config.GetAllOptions() { + if _, found := fields.AllowedDuplicateOptions[info.Option.Key.Key]; found { + continue + } + + delete(availableOptions, info.Option.Key.Key) + } + + return utils.MapMapToSlice( + availableOptions, + func(name string, doc docvalues.DocumentationValue) protocol.CompletionItem { + completion := &protocol.CompletionItem{ + Label: name, + Kind: &kind, + Documentation: doc.Documentation, + } + + if suggestValue { + format := protocol.InsertTextFormatSnippet + insertText := name + " " + "${1:value}" + + completion.InsertTextFormat = &format + completion.InsertText = &insertText + } + + return *completion + }, + ), nil +} diff --git a/handlers/ssh_config/indexes/indexes.go b/handlers/ssh_config/indexes/indexes.go index 35cc82d..841cbc3 100644 --- a/handlers/ssh_config/indexes/indexes.go +++ b/handlers/ssh_config/indexes/indexes.go @@ -23,12 +23,14 @@ type SSHIndexIncludeValue struct { type SSHIndexIncludeLine struct { Values []*SSHIndexIncludeValue Option *ast.SSHOption - Block *ast.SSHBlock + Block ast.SSHBlock } type SSHIndexes struct { - AllOptionsPerName map[string](map[*ast.SSHBlock]([]*ast.SSHOption)) + AllOptionsPerName map[string](map[ast.SSHBlock]([]*ast.SSHOption)) Includes []*SSHIndexIncludeLine + + BlockRanges map[uint32]ast.SSHBlock } diff --git a/handlers/ssh_config/indexes/handlers.go b/handlers/ssh_config/indexes/indexes_handlers.go similarity index 90% rename from handlers/ssh_config/indexes/handlers.go rename to handlers/ssh_config/indexes/indexes_handlers.go index 2502870..4c78283 100644 --- a/handlers/ssh_config/indexes/handlers.go +++ b/handlers/ssh_config/indexes/indexes_handlers.go @@ -13,7 +13,7 @@ var whitespacePattern = regexp.MustCompile(`\S+`) func NewSSHIndexes() *SSHIndexes { return &SSHIndexes{ - AllOptionsPerName: make(map[string](map[*ast.SSHBlock]([]*ast.SSHOption)), 0), + AllOptionsPerName: make(map[string](map[ast.SSHBlock]([]*ast.SSHOption)), 0), Includes: make([]*SSHIndexIncludeLine, 0), } } @@ -34,13 +34,13 @@ func CreateIndexes(config ast.SSHConfig) (*SSHIndexes, []common.LSPError) { case ast.SSHTypeHost: block := entry.(ast.SSHBlock) - errs = append(errs, addOption(indexes, entry.GetOption(), &block)...) + errs = append(errs, addOption(indexes, entry.GetOption(), block)...) it := block.GetOptions().Iterator() for it.Next() { option := it.Value().(*ast.SSHOption) - errs = append(errs, addOption(indexes, option, &block)...) + errs = append(errs, addOption(indexes, option, block)...) } } } @@ -90,7 +90,7 @@ func CreateIndexes(config ast.SSHConfig) (*SSHIndexes, []common.LSPError) { func addOption( i *SSHIndexes, option *ast.SSHOption, - block *ast.SSHBlock, + block ast.SSHBlock, ) []common.LSPError { var errs []common.LSPError @@ -118,7 +118,7 @@ func addOption( } } } else { - i.AllOptionsPerName[option.Key.Key] = map[*ast.SSHBlock]([]*ast.SSHOption){ + i.AllOptionsPerName[option.Key.Key] = map[ast.SSHBlock]([]*ast.SSHOption){ block: { option, }, diff --git a/handlers/ssh_config/lsp/text-document-completion.go b/handlers/ssh_config/lsp/text-document-completion.go index 5c5b64a..5813dae 100644 --- a/handlers/ssh_config/lsp/text-document-completion.go +++ b/handlers/ssh_config/lsp/text-document-completion.go @@ -1,10 +1,50 @@ package lsp import ( + "config-lsp/common" + sshconfig "config-lsp/handlers/ssh_config" + "config-lsp/handlers/ssh_config/handlers" + "regexp" + "github.com/tliron/glsp" protocol "github.com/tliron/glsp/protocol_3_16" ) +var isEmptyPattern = regexp.MustCompile(`^\s*$`) + func TextDocumentCompletion(context *glsp.Context, params *protocol.CompletionParams) (any, error) { + line := params.Position.Line + cursor := common.LSPCharacterAsCursorPosition(params.Position.Character) + + d := sshconfig.DocumentParserMap[params.TextDocument.URI] + + if _, found := d.Config.CommentLines[line]; found { + return nil, nil + } + + option, block := d.Config.FindOption(line) + + if option == nil || + option.Separator == nil || + option.Key == nil || + option.Key.IsPositionBeforeEnd(cursor) { + + return handlers.GetRootCompletions( + d, + block, + // Empty line, or currently typing a new key + option == nil || isEmptyPattern.Match([]byte(option.Value.Raw[cursor:])), + ) + } + + // if option.Separator != nil && option.OptionValue.IsPositionAfterStart(cursor) { + // return handlers.GetOptionCompletions( + // d, + // entry, + // matchBlock, + // cursor, + // ) + // } + return nil, nil } diff --git a/handlers/ssh_config/shared.go b/handlers/ssh_config/shared.go index 5aa8e06..60b905d 100644 --- a/handlers/ssh_config/shared.go +++ b/handlers/ssh_config/shared.go @@ -1,8 +1,8 @@ package sshconfig import ( - "config-lsp/handlers/ssh_config/ast" "config-lsp/handlers/ssh_config/indexes" + "config-lsp/handlers/ssh_config/ast" protocol "github.com/tliron/glsp/protocol_3_16" ) @@ -13,3 +13,4 @@ type SSHDocument struct { } var DocumentParserMap = map[protocol.DocumentUri]*SSHDocument{} + diff --git a/handlers/sshd_config/ast/sshd_config_fields.go b/handlers/sshd_config/ast/sshd_config_fields.go index 8c226bd..11546d4 100644 --- a/handlers/sshd_config/ast/sshd_config_fields.go +++ b/handlers/sshd_config/ast/sshd_config_fields.go @@ -62,7 +62,6 @@ func (c SSHDConfig) FindOption(line uint32) (*SSHDOption, *SSHDMatchBlock) { } return nil, nil - } func (c SSHDConfig) GetAllOptions() []*SSHDOption { diff --git a/handlers/sshd_config/handlers/completions.go b/handlers/sshd_config/handlers/completions.go index 827b636..0082417 100644 --- a/handlers/sshd_config/handlers/completions.go +++ b/handlers/sshd_config/handlers/completions.go @@ -20,23 +20,17 @@ func GetRootCompletions( availableOptions := make(map[string]docvalues.DocumentationValue, 0) - if parentMatchBlock == nil { - for key, option := range fields.Options { - if d.Indexes != nil && utils.KeyExists(d.Indexes.AllOptionsPerName, key) && !utils.KeyExists(fields.AllowedDuplicateOptions, key) { - continue - } + for key, option := range fields.Options { + var exists = false - availableOptions[key] = option + if optionsMap, found := d.Indexes.AllOptionsPerName[key]; found { + if _, found := optionsMap[parentMatchBlock]; found { + exists = true + } } - } else { - for key := range fields.MatchAllowedOptions { - if option, found := fields.Options[key]; found { - if d.Indexes != nil && utils.KeyExists(d.Indexes.AllOptionsPerName, key) && !utils.KeyExists(fields.AllowedDuplicateOptions, key) { - continue - } - availableOptions[key] = option - } + if !exists || utils.KeyExists(fields.AllowedDuplicateOptions, key) { + availableOptions[key] = option } } From a9e58a7f5051f80a78e385210ec6f286a06fc262 Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Sun, 22 Sep 2024 22:23:08 +0200 Subject: [PATCH 080/133] feat(ssh_config): Add completions support --- handlers/ssh_config/handlers/completions.go | 39 +++++++++++++++++++ .../lsp/text-document-completion.go | 16 ++++---- 2 files changed, 47 insertions(+), 8 deletions(-) diff --git a/handlers/ssh_config/handlers/completions.go b/handlers/ssh_config/handlers/completions.go index e6236c6..c918093 100644 --- a/handlers/ssh_config/handlers/completions.go +++ b/handlers/ssh_config/handlers/completions.go @@ -1,6 +1,7 @@ package handlers import ( + "config-lsp/common" docvalues "config-lsp/doc-values" sshconfig "config-lsp/handlers/ssh_config" "config-lsp/handlers/ssh_config/ast" @@ -57,3 +58,41 @@ func GetRootCompletions( }, ), nil } + +func GetOptionCompletions( + d *sshconfig.SSHDocument, + entry *ast.SSHOption, + block ast.SSHBlock, + cursor common.CursorPosition, +) ([]protocol.CompletionItem, error) { + option, found := fields.Options[entry.Key.Key] + + if !found { + return nil, nil + } + + if entry.Key.Key == "Match" { + return nil, nil + // return getMatchCompletions( + // d, + // cursor, + // matchBlock.MatchValue, + // ) + } + + if entry.OptionValue == nil { + return option.FetchCompletions("", 0), nil + } + + // Hello wo|rld + line := entry.OptionValue.Value.Raw + // NEW: docvalues index + return option.FetchCompletions( + line, + common.DeprecatedImprovedCursorToIndex( + cursor, + line, + entry.OptionValue.Start.Character, + ), + ), nil +} diff --git a/handlers/ssh_config/lsp/text-document-completion.go b/handlers/ssh_config/lsp/text-document-completion.go index 5813dae..56d6973 100644 --- a/handlers/ssh_config/lsp/text-document-completion.go +++ b/handlers/ssh_config/lsp/text-document-completion.go @@ -37,14 +37,14 @@ func TextDocumentCompletion(context *glsp.Context, params *protocol.CompletionPa ) } - // if option.Separator != nil && option.OptionValue.IsPositionAfterStart(cursor) { - // return handlers.GetOptionCompletions( - // d, - // entry, - // matchBlock, - // cursor, - // ) - // } + if option.Separator != nil && option.OptionValue.IsPositionAfterStart(cursor) { + return handlers.GetOptionCompletions( + d, + option, + block, + cursor, + ) + } return nil, nil } From 73a850c11abc68dd1c9d4168f3016450febf9702 Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Sun, 22 Sep 2024 22:48:02 +0200 Subject: [PATCH 081/133] fix(ssh_config): Fix fetching options --- handlers/ssh_config/ast/ssh_config_fields.go | 32 ++++++++--- handlers/ssh_config/document_fields_test.go | 59 ++++++++++++++++++++ handlers/ssh_config/fields/fields.go | 2 + handlers/ssh_config/handlers/completions.go | 9 --- 4 files changed, 86 insertions(+), 16 deletions(-) create mode 100644 handlers/ssh_config/document_fields_test.go diff --git a/handlers/ssh_config/ast/ssh_config_fields.go b/handlers/ssh_config/ast/ssh_config_fields.go index 7902b21..9e7d3cb 100644 --- a/handlers/ssh_config/ast/ssh_config_fields.go +++ b/handlers/ssh_config/ast/ssh_config_fields.go @@ -2,6 +2,7 @@ package ast import ( "config-lsp/common" + "config-lsp/utils" "github.com/emirpasic/gods/maps/treemap" ) @@ -145,10 +146,28 @@ func (c SSHConfig) FindOption(line uint32) (*SSHOption, SSHBlock) { } type AllOptionInfo struct { - Block SSHBlock + Block SSHBlock Option *SSHOption } +func (c SSHConfig) GetAllOptionsForBlock(block SSHBlock) []AllOptionInfo { + if block == nil { + return c.GetAllOptions() + } + + return utils.Map( + block.GetOptions().Values(), + func(rawOption interface{}) AllOptionInfo { + option := rawOption.(*SSHOption) + + return AllOptionInfo{ + Block: block, + Option: option, + } + }, + ) +} + func (c SSHConfig) GetAllOptions() []AllOptionInfo { options := make([]AllOptionInfo, 0, 50) @@ -157,21 +176,21 @@ func (c SSHConfig) GetAllOptions() []AllOptionInfo { case *SSHOption: option := rawEntry.(*SSHOption) options = append(options, AllOptionInfo{ - Block: nil, + Block: nil, Option: option, }) case *SSHMatchBlock: block := rawEntry.(SSHBlock) options = append(options, AllOptionInfo{ - Block: block, + Block: block, Option: block.GetEntryOption(), }) for _, rawOption := range block.GetOptions().Values() { option := rawOption.(*SSHOption) options = append(options, AllOptionInfo{ - Block: nil, + Block: block, Option: option, }) } @@ -179,14 +198,14 @@ func (c SSHConfig) GetAllOptions() []AllOptionInfo { block := rawEntry.(SSHBlock) options = append(options, AllOptionInfo{ - Block: block, + Block: block, Option: block.GetEntryOption(), }) for _, rawOption := range block.GetOptions().Values() { option := rawOption.(*SSHOption) options = append(options, AllOptionInfo{ - Block: nil, + Block: block, Option: option, }) } @@ -196,4 +215,3 @@ func (c SSHConfig) GetAllOptions() []AllOptionInfo { return options } - diff --git a/handlers/ssh_config/document_fields_test.go b/handlers/ssh_config/document_fields_test.go new file mode 100644 index 0000000..a4ce15d --- /dev/null +++ b/handlers/ssh_config/document_fields_test.go @@ -0,0 +1,59 @@ +package sshconfig + +import ( + "config-lsp/handlers/ssh_config/ast" + "config-lsp/handlers/ssh_config/indexes" + "config-lsp/utils" + "testing" +) + +func TestComplexExample( + t *testing.T, +) { + input := utils.Dedent(` +ProxyCommand hello + +Host laptop + HostName laptop.lan + ProxyCommand test + +Match originalhost laptop exec "[[ $(/usr/bin/dig +short laptop.lan) == '' ]]" + HostName laptop.sdn +`) + c := ast.NewSSHConfig() + errors := c.Parse(input) + + if len(errors) != 0 { + t.Fatalf("Expected no errors, got %v", errors) + } + + i, errors := indexes.CreateIndexes(*c) + + if len(errors) != 0 { + t.Fatalf("Expected no errors, got %v", errors) + } + + d := &SSHDocument{ + Config: c, + Indexes: i, + } + + options := d.FindOptionsByName("ProxyCommand") + if !(len(options) == 2 && options[0].Option.Start.Line == 0 && options[1].Option.Start.Line == 4) { + t.Errorf("Expected 2 options, got %v", options) + } + + options = d.FindOptionsByName("HostName") + if !(len(options) == 2 && options[0].Option.Start.Line == 3 && options[1].Option.Start.Line == 7) { + t.Errorf("Expected 2 options, got %v", options) + } + + block := d.Config.FindBlock(4) + if !(d.FindOptionByNameAndBlock("ProxyCommand", block).Option.Start.Line == 4) { + t.Errorf("Expected 4, got %v", d.FindOptionByNameAndBlock("PorxyCommand", block).Option.Start.Line) + } + + if !(d.FindOptionByNameAndBlock("ProxyCommand", nil).Option.Start.Line == 0) { + t.Errorf("Expected 0, got %v", d.FindOptionByNameAndBlock("ProxyCommand", nil).Option.Start.Line) + } +} diff --git a/handlers/ssh_config/fields/fields.go b/handlers/ssh_config/fields/fields.go index d90b649..6aeed90 100644 --- a/handlers/ssh_config/fields/fields.go +++ b/handlers/ssh_config/fields/fields.go @@ -11,6 +11,8 @@ var MAX_PORT = 65535 var AllowedDuplicateOptions = map[string]struct{}{ "CertificateFile": {}, + "Match": {}, + "Host": {}, } var Options = map[string]docvalues.DocumentationValue{ diff --git a/handlers/ssh_config/handlers/completions.go b/handlers/ssh_config/handlers/completions.go index c918093..e8974c7 100644 --- a/handlers/ssh_config/handlers/completions.go +++ b/handlers/ssh_config/handlers/completions.go @@ -28,15 +28,6 @@ func GetRootCompletions( } } - // Remove all fields that are already present and are not allowed to be duplicated - for _, info := range d.Config.GetAllOptions() { - if _, found := fields.AllowedDuplicateOptions[info.Option.Key.Key]; found { - continue - } - - delete(availableOptions, info.Option.Key.Key) - } - return utils.MapMapToSlice( availableOptions, func(name string, doc docvalues.DocumentationValue) protocol.CompletionItem { From 07cb9ac045b5b3142cea3e9ab521d9ccac284308 Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Thu, 26 Sep 2024 20:23:34 +0200 Subject: [PATCH 082/133] refactor(ssh_config): Improvements --- handlers/ssh_config/analyzer/options.go | 140 +++++++++++++++++++ handlers/ssh_config/analyzer/options_test.go | 54 +++++++ handlers/ssh_config/analyzer/quotes.go | 59 ++++++++ handlers/ssh_config/analyzer/quotes_test.go | 62 ++++++++ handlers/ssh_config/fields/fields.go | 83 +++++------ handlers/ssh_config/fields/options.go | 19 +++ handlers/ssh_config/handlers/completions.go | 13 +- handlers/ssh_config/indexes/indexes_test.go | 123 +++++++++------- handlers/ssh_config/test_utils/input.go | 33 +++++ 9 files changed, 487 insertions(+), 99 deletions(-) create mode 100644 handlers/ssh_config/analyzer/options.go create mode 100644 handlers/ssh_config/analyzer/options_test.go create mode 100644 handlers/ssh_config/analyzer/quotes.go create mode 100644 handlers/ssh_config/analyzer/quotes_test.go create mode 100644 handlers/ssh_config/fields/options.go create mode 100644 handlers/ssh_config/test_utils/input.go diff --git a/handlers/ssh_config/analyzer/options.go b/handlers/ssh_config/analyzer/options.go new file mode 100644 index 0000000..3acd2b3 --- /dev/null +++ b/handlers/ssh_config/analyzer/options.go @@ -0,0 +1,140 @@ +package analyzer + +import ( + "config-lsp/common" + docvalues "config-lsp/doc-values" + sshconfig "config-lsp/handlers/ssh_config" + "config-lsp/handlers/ssh_config/ast" + "config-lsp/handlers/ssh_config/fields" + "config-lsp/utils" + "errors" + "fmt" +) + +func analyzeStructureIsValid( + d *sshconfig.SSHDocument, +) []common.LSPError { + errs := make([]common.LSPError, 0) + it := d.Config.Options.Iterator() + + for it.Next() { + entry := it.Value().(ast.SSHEntry) + + switch entry.(type) { + case *ast.SSHOption: + errs = append(errs, checkOption(entry.(*ast.SSHOption), nil)...) + case *ast.SSHMatchBlock: + matchBlock := entry.(*ast.SSHMatchBlock) + errs = append(errs, checkMatchBlock(matchBlock)...) + case *ast.SSHHostBlock: + hostBlock := entry.(*ast.SSHHostBlock) + errs = append(errs, checkHostBlock(hostBlock)...) + } + + } + + return errs +} + +func checkOption( + option *ast.SSHOption, + block ast.SSHBlock, +) []common.LSPError { + errs := make([]common.LSPError, 0) + + if option.Key == nil { + return errs + } + + errs = append(errs, checkIsUsingDoubleQuotes(option.Key.Value, option.Key.LocationRange)...) + errs = append(errs, checkQuotesAreClosed(option.Key.Value, option.Key.LocationRange)...) + + docOption, found := fields.Options[option.Key.Key] + + if !found { + errs = append(errs, common.LSPError{ + Range: option.Key.LocationRange, + Err: errors.New(fmt.Sprintf("Unknown option: %s", option.Key.Key)), + }) + + return errs + } + + // Check for values that are not allowed in Host blocks + if block != nil && block.GetBlockType() == ast.SSHBlockTypeHost { + if utils.KeyExists(fields.HostDisallowedOptions, option.Key.Key) { + errs = append(errs, common.LSPError{ + Range: option.Key.LocationRange, + Err: errors.New(fmt.Sprintf("Option '%s' is not allowed in Host blocks", option.Key.Key)), + }) + } + } + + if option.OptionValue == nil || option.OptionValue.Value.Value == "" { + errs = append(errs, common.LSPError{ + Range: option.Key.LocationRange, + Err: errors.New(fmt.Sprintf("Option '%s' requires a value", option.Key.Key)), + }) + } else { + errs = append(errs, checkIsUsingDoubleQuotes(option.OptionValue.Value, option.OptionValue.LocationRange)...) + errs = append(errs, checkQuotesAreClosed(option.OptionValue.Value, option.OptionValue.LocationRange)...) + + invalidValues := docOption.CheckIsValid(option.OptionValue.Value.Value) + + errs = append( + errs, + utils.Map( + invalidValues, + func(invalidValue *docvalues.InvalidValue) common.LSPError { + err := docvalues.LSPErrorFromInvalidValue(option.Start.Line, *invalidValue) + err.ShiftCharacter(option.OptionValue.Start.Character) + + return err + }, + )..., + ) + } + + if option.Separator == nil || option.Separator.Value.Value == "" { + errs = append(errs, common.LSPError{ + Range: option.Key.LocationRange, + Err: errors.New(fmt.Sprintf("There should be a separator between an option and its value")), + }) + } else { + errs = append(errs, checkIsUsingDoubleQuotes(option.Separator.Value, option.Separator.LocationRange)...) + errs = append(errs, checkQuotesAreClosed(option.Separator.Value, option.Separator.LocationRange)...) + } + + return errs +} + +func checkMatchBlock( + matchBlock *ast.SSHMatchBlock, +) []common.LSPError { + errs := make([]common.LSPError, 0) + + it := matchBlock.Options.Iterator() + for it.Next() { + option := it.Value().(*ast.SSHOption) + + errs = append(errs, checkOption(option, matchBlock)...) + } + + return errs +} + +func checkHostBlock( + hostBlock *ast.SSHHostBlock, +) []common.LSPError { + errs := make([]common.LSPError, 0) + + it := hostBlock.Options.Iterator() + for it.Next() { + option := it.Value().(*ast.SSHOption) + + errs = append(errs, checkOption(option, hostBlock)...) + } + + return errs +} + diff --git a/handlers/ssh_config/analyzer/options_test.go b/handlers/ssh_config/analyzer/options_test.go new file mode 100644 index 0000000..63191bc --- /dev/null +++ b/handlers/ssh_config/analyzer/options_test.go @@ -0,0 +1,54 @@ +package analyzer + +import ( + testutils_test "config-lsp/handlers/ssh_config/test_utils" + "testing" +) + +func TestSimpleExample( + t *testing.T, +) { + d := testutils_test.DocumentFromInput(t, ` +ProxyCommand hello + +User root +`) + + errors := analyzeStructureIsValid(d) + + if len(errors) != 0 { + t.Fatalf("Expected no errors, got %v", errors) + } +} + +func TestOptionEmpty( + t *testing.T, +) { + d := testutils_test.DocumentFromInput(t, ` +ProxyCommand + +User root +`) + errors := analyzeStructureIsValid(d) + + if len(errors) != 1 { + t.Fatalf("Expected 1 error, got %v", errors) + } +} + +func TestNoSeparator( + t *testing.T, +) { + d := testutils_test.DocumentFromInput(t, ` +"ProxyCommand""hello" + +User root +`) + errors := analyzeStructureIsValid(d) + + if len(errors) != 1 { + t.Fatalf("Expected 1 error, got %v", errors) + } +} + + diff --git a/handlers/ssh_config/analyzer/quotes.go b/handlers/ssh_config/analyzer/quotes.go new file mode 100644 index 0000000..a07b3b3 --- /dev/null +++ b/handlers/ssh_config/analyzer/quotes.go @@ -0,0 +1,59 @@ +package analyzer + +import ( + "config-lsp/common" + commonparser "config-lsp/common/parser" + sshconfig "config-lsp/handlers/ssh_config" + "errors" + "strings" +) + +func analyzeQuotesAreValid( + d *sshconfig.SSHDocument, +) []common.LSPError { + errs := make([]common.LSPError, 0) + + for _, info := range d.Config.GetAllOptions() { + errs = append(errs, checkIsUsingDoubleQuotes(info.Option.Key.Value, info.Option.Key.LocationRange)...) + errs = append(errs, checkIsUsingDoubleQuotes(info.Option.OptionValue.Value, info.Option.OptionValue.LocationRange)...) + + errs = append(errs, checkQuotesAreClosed(info.Option.Key.Value, info.Option.Key.LocationRange)...) + errs = append(errs, checkQuotesAreClosed(info.Option.OptionValue.Value, info.Option.OptionValue.LocationRange)...) + } + + return errs +} + +func checkIsUsingDoubleQuotes( + value commonparser.ParsedString, + valueRange common.LocationRange, + ) []common.LSPError { + singleQuotePosition := strings.Index(value.Raw, "'") + + if singleQuotePosition != -1 { + return []common.LSPError{ + { + Range: valueRange, + Err: errors.New("ssh_config does not support single quotes. Use double quotes (\") instead."), + }, + } + } + + return nil +} + +func checkQuotesAreClosed( + value commonparser.ParsedString, + valueRange common.LocationRange, +) []common.LSPError { + if strings.Count(value.Raw, "\"")%2 != 0 { + return []common.LSPError{ + { + Range: valueRange, + Err: errors.New("There are unclosed quotes here. Make sure all quotes are closed."), + }, + } + } + + return nil +} diff --git a/handlers/ssh_config/analyzer/quotes_test.go b/handlers/ssh_config/analyzer/quotes_test.go new file mode 100644 index 0000000..9a108d1 --- /dev/null +++ b/handlers/ssh_config/analyzer/quotes_test.go @@ -0,0 +1,62 @@ +package analyzer + +import ( + testutils_test "config-lsp/handlers/ssh_config/test_utils" + "testing" +) + +func TestSimpleInvalidQuotesExample( + t *testing.T, +) { + d := testutils_test.DocumentFromInput(t, ` +PermitRootLogin 'yes' +`) + + errors := analyzeQuotesAreValid(d) + + if !(len(errors) == 1) { + t.Errorf("Expected 1 error, got %v", len(errors)) + } +} + +func TestSingleQuotesKeyAndOptionExample( + t *testing.T, +) { + d := testutils_test.DocumentFromInput(t, ` +'Port' '22' +`) + + errors := analyzeQuotesAreValid(d) + + if !(len(errors) == 2) { + t.Errorf("Expected 2 errors, got %v", len(errors)) + } +} + +func TestSimpleUnclosedQuoteExample( + t *testing.T, +) { + d := testutils_test.DocumentFromInput(t, ` +PermitRootLogin "yes +`) + + errors := analyzeQuotesAreValid(d) + + if !(len(errors) == 1) { + t.Errorf("Expected 1 error, got %v", len(errors)) + } +} + +func TestIncompleteQuotesExample( + t *testing.T, +) { + d := testutils_test.DocumentFromInput(t, ` +"Port +`) + + errors := analyzeQuotesAreValid(d) + + if !(len(errors) == 1) { + t.Errorf("Expected 1 error, got %v", len(errors)) + } +} diff --git a/handlers/ssh_config/fields/fields.go b/handlers/ssh_config/fields/fields.go index 6aeed90..acdd952 100644 --- a/handlers/ssh_config/fields/fields.go +++ b/handlers/ssh_config/fields/fields.go @@ -9,12 +9,6 @@ import ( var ZERO = 0 var MAX_PORT = 65535 -var AllowedDuplicateOptions = map[string]struct{}{ - "CertificateFile": {}, - "Match": {}, - "Host": {}, -} - var Options = map[string]docvalues.DocumentationValue{ "Host": { Documentation: `Restricts the following declarations (up to the next Host or Match keyword) to be only for those hosts that match one of the patterns given after the keyword. If more than one pattern is provided, they should be separated by whitespace. A single ‘*’ as a pattern can be used to provide global defaults for all hosts. The host is usually the hostname argument given on the command line (see the CanonicalizeHostname keyword for exceptions). @@ -110,7 +104,7 @@ var Options = map[string]docvalues.DocumentationValue{ "CASignatureAlgorithms": { Documentation: `Specifies which algorithms are allowed for signing of certificates by certificate authorities (CAs). The default is: - ssh-ed25519,ecdsa-sha2-nistp256, +ssh-ed25519,ecdsa-sha2-nistp256, ecdsa-sha2-nistp384,ecdsa-sha2-nistp521, sk-ssh-ed25519@openssh.com, sk-ecdsa-sha2-nistp256@openssh.com, @@ -204,8 +198,8 @@ The default is not to expire channels of any type for inactivity.`, Documentation: `Specifies the ciphers allowed and their order of preference. Multiple ciphers must be comma-separated. If the specified list begins with a ‘+’ character, then the specified ciphers will be appended to the default set instead of replacing them. If the specified list begins with a ‘-’ character, then the specified ciphers (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a ‘^’ character, then the specified ciphers will be placed at the head of the default set. The supported ciphers are: - - 3des-cbc + +3des-cbc aes128-cbc aes192-cbc aes256-cbc @@ -215,15 +209,14 @@ aes256-ctr aes128-gcm@openssh.com aes256-gcm@openssh.com chacha20-poly1305@openssh.com - + The default is: - - chacha20-poly1305@openssh.com, + +chacha20-poly1305@openssh.com, aes128-ctr,aes192-ctr,aes256-ctr, aes128-gcm@openssh.com,aes256-gcm@openssh.com - The list of available ciphers may also be obtained using - 'ssh -Q cipher'.`, + The list of available ciphers may also be obtained using 'ssh -Q cipher'.`, Value: prefixPlusMinusCaret([]docvalues.EnumString{ docvalues.CreateEnumString("3des-cbc"), docvalues.CreateEnumString("aes128-cbc"), @@ -314,8 +307,7 @@ aes128-gcm@openssh.com,aes256-gcm@openssh.com Value: docvalues.StringValue{}, }, "ExitOnForwardFailure": { - Documentation: `Specifies whether ssh(1) should terminate the connection if it cannot set up all requested dynamic, tunnel, local, and remote port forwardings, (e.g. if either end is unable to bind and listen on a specified port). Note that ExitOnForwardFailure does not apply to connections made over port forwardings and will not, for example, cause ssh(1) to exit if TCP connections to the ultimate forwarding destination fail. The argument must be yes or no - (the default).`, + Documentation: `Specifies whether ssh(1) should terminate the connection if it cannot set up all requested dynamic, tunnel, local, and remote port forwardings, (e.g. if either end is unable to bind and listen on a specified port). Note that ExitOnForwardFailure does not apply to connections made over port forwardings and will not, for example, cause ssh(1) to exit if TCP connections to the ultimate forwarding destination fail. The argument must be yes or no (the default).`, Value: booleanEnumValue, }, "FingerprintHash": { @@ -383,14 +375,13 @@ aes128-gcm@openssh.com,aes256-gcm@openssh.com Value: booleanEnumValue, }, "HashKnownHosts": { - Documentation: `Indicates that ssh(1) should hash host names and addresses when they are added to - ~/.ssh/known_hosts. These hashed names may be used normally by ssh(1) and sshd(8), but they do not visually reveal identifying information if the file's contents are disclosed. The default is no. Note that existing names and addresses in known hosts files will not be converted automatically, but may be manually hashed using ssh-keygen(1).`, + Documentation: `Indicates that ssh(1) should hash host names and addresses when they are added to ~/.ssh/known_hosts. These hashed names may be used normally by ssh(1) and sshd(8), but they do not visually reveal identifying information if the file's contents are disclosed. The default is no. Note that existing names and addresses in known hosts files will not be converted automatically, but may be manually hashed using ssh-keygen(1).`, Value: booleanEnumValue, }, "HostbasedAcceptedAlgorithms": { Documentation: `Specifies the signature algorithms that will be used for hostbased authentication as a comma-separated list of patterns. Alternately if the specified list begins with a ‘+’ character, then the specified signature algorithms will be appended to the default set instead of replacing them. If the specified list begins with a ‘-’ character, then the specified signature algorithms (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a ‘^’ character, then the specified signature algorithms will be placed at the head of the default set. The default for this option is: - - ssh-ed25519-cert-v01@openssh.com, + +ssh-ed25519-cert-v01@openssh.com, ecdsa-sha2-nistp256-cert-v01@openssh.com, ecdsa-sha2-nistp384-cert-v01@openssh.com, ecdsa-sha2-nistp521-cert-v01@openssh.com, @@ -403,7 +394,7 @@ ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521, sk-ssh-ed25519@openssh.com, sk-ecdsa-sha2-nistp256@openssh.com, rsa-sha2-512,rsa-sha2-256 - + The -Q option of ssh(1) may be used to list supported signature algorithms. This was formerly named HostbasedKeyTypes.`, Value: docvalues.CustomValue{ FetchValue: func(_ docvalues.CustomValueContext) docvalues.Value { @@ -426,8 +417,8 @@ rsa-sha2-512,rsa-sha2-256 Documentation: `Specifies the host key signature algorithms that the client wants to use in order of preference. Alternately if the specified list begins with a ‘+’ character, then the specified signature algorithms will be appended to the default set instead of replacing them. If the specified list begins with a ‘-’ character, then the specified signature algorithms (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a ‘^’ character, then the specified signature algorithms will be placed at the head of the default set. The default for this option is: - - ssh-ed25519-cert-v01@openssh.com, + +ssh-ed25519-cert-v01@openssh.com, ecdsa-sha2-nistp256-cert-v01@openssh.com, ecdsa-sha2-nistp384-cert-v01@openssh.com, ecdsa-sha2-nistp521-cert-v01@openssh.com, @@ -440,7 +431,7 @@ ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521, sk-ecdsa-sha2-nistp256@openssh.com, sk-ssh-ed25519@openssh.com, rsa-sha2-512,rsa-sha2-256 - + If hostkeys are known for the destination host then this default is modified to prefer their algorithms. The list of available signature algorithms may also be obtained using 'ssh -Q HostKeyAlgorithms'.`, Value: docvalues.CustomValue{ @@ -479,14 +470,13 @@ rsa-sha2-512,rsa-sha2-256 IdentityFile may be used in conjunction with IdentitiesOnly to select which identities in an agent are offered during authentication. IdentityFile may also be used in conjunction with CertificateFile in order to provide any certificate also needed for authentication with the identity.`, Value: docvalues.StringValue{}, }, + // TODO: Add "IgnoreUnknown": { - Documentation: `Specifies a pattern-list of unknown options to be ignored if they are encountered in configuration parsing. This may be used to suppress errors if ssh_config contains options that are unrecognised by ssh(1). It is recommended that IgnoreUnknown be listed early in the configuration file as it will not be applied to unknown options that appear before - it.`, + Documentation: `Specifies a pattern-list of unknown options to be ignored if they are encountered in configuration parsing. This may be used to suppress errors if ssh_config contains options that are unrecognised by ssh(1). It is recommended that IgnoreUnknown be listed early in the configuration file as it will not be applied to unknown options that appear before it.`, Value: docvalues.StringValue{}, }, "Include": { - Documentation: `Include the specified configuration file(s). Multiple pathnames may be specified and each pathname may contain glob(7) wildcards, tokens as described in the TOKENS section, environment variables as described in the ENVIRONMENT VARIABLES section and, for user configurations, shell-like - ‘~’ references to user home directories. Wildcards will be expanded and processed in lexical order. Files without absolute paths are assumed to be in ~/.ssh if included in a user configuration file or /etc/ssh if included from the system configuration file. Include directive may appear inside a Match or Host block to perform conditional inclusion.`, + Documentation: `Include the specified configuration file(s). Multiple pathnames may be specified and each pathname may contain glob(7) wildcards, tokens as described in the TOKENS section, environment variables as described in the ENVIRONMENT VARIABLES section and, for user configurations, shell-like ‘~’ references to user home directories. Wildcards will be expanded and processed in lexical order. Files without absolute paths are assumed to be in ~/.ssh if included in a user configuration file or /etc/ssh if included from the system configuration file. Include directive may appear inside a Match or Host block to perform conditional inclusion.`, Value: docvalues.ArrayValue{ Separator: " ", DuplicatesExtractor: &docvalues.SimpleDuplicatesExtractor, @@ -541,6 +531,7 @@ rsa-sha2-512,rsa-sha2-256 }, }, "KbdInteractiveAuthentication": { + // TODO: Show deprecation Documentation: `Specifies whether to use keyboard-interactive authentication. The argument to this keyword must be yes (the default) or no. ChallengeResponseAuthentication is a deprecated alias for this.`, Value: booleanEnumValue, }, @@ -564,8 +555,8 @@ rsa-sha2-512,rsa-sha2-256 If the specified list begins with a ‘+’ character, then the specified algorithms will be appended to the default set instead of replacing them. If the specified list begins with a ‘-’ character, then the specified algorithms (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a ‘^’ character, then the specified algorithms will be placed at the head of the default set. The default is: - - sntrup761x25519-sha512,sntrup761x25519-sha512@openssh.com, + +sntrup761x25519-sha512,sntrup761x25519-sha512@openssh.com, mlkem768x25519-sha256, curve25519-sha256,curve25519-sha256@libssh.org, ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521, @@ -573,7 +564,7 @@ diffie-hellman-group-exchange-sha256, diffie-hellman-group16-sha512, diffie-hellman-group18-sha512, diffie-hellman-group14-sha256 - + The list of supported key exchange algorithms may also be obtained using 'ssh -Q kex'.`, Value: prefixPlusMinusCaret([]docvalues.EnumString{ docvalues.CreateEnumString("curve25519-sha256"), @@ -648,13 +639,13 @@ diffie-hellman-group14-sha256 ‘^’ character, then the specified algorithms will be placed at the head of the default set. The algorithms that contain '-etm' calculate the MAC after encryption (encrypt-then-mac). These are considered safer and their use recommended. The default is: - - umac-64-etm@openssh.com,umac-128-etm@openssh.com, + +umac-64-etm@openssh.com,umac-128-etm@openssh.com, hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com, hmac-sha1-etm@openssh.com, umac-64@openssh.com,umac-128@openssh.com, hmac-sha2-256,hmac-sha2-512,hmac-sha1 - + The list of available MAC algorithms may also be obtained using 'ssh -Q mac'.`, Value: prefixPlusMinusCaret([]docvalues.EnumString{ docvalues.CreateEnumString("hmac-md5"), @@ -716,6 +707,7 @@ hmac-sha2-256,hmac-sha2-512,hmac-sha1 Documentation: `Specifies which PKCS#11 provider to use or none to indicate that no provider should be used (the default). The argument to this keyword is a path to the PKCS#11 shared library ssh(1) should use to communicate with a PKCS#11 token providing keys for user authentication.`, Value: booleanEnumValue, }, + // TODO: Show warning "Port": { Documentation: `Specifies the port number to connect on the remote host. The default is 22.`, Value: docvalues.NumberValue{Min: &ZERO, Max: &MAX_PORT}, @@ -723,7 +715,7 @@ hmac-sha2-256,hmac-sha2-512,hmac-sha1 "PreferredAuthentications": { Documentation: `Specifies the order in which the client should try authentication methods. This allows a client to prefer one method (e.g. keyboard-interactive) over another method (e.g. password). The default is: - gssapi-with-mic,hostbased,publickey,keyboard-interactive,password`, +gssapi-with-mic,hostbased,publickey,keyboard-interactive,password`, Value: docvalues.EnumValue{ EnforceValues: true, Values: []docvalues.EnumString{ @@ -736,8 +728,7 @@ hmac-sha2-256,hmac-sha2-512,hmac-sha1 }, }, "ProxyCommand": { - Documentation: `Specifies the command to use to connect to the server. The command string extends to the end of the line, and is executed using the user's shell - ‘exec’ directive to avoid a lingering shell process. + Documentation: `Specifies the command to use to connect to the server. The command string extends to the end of the line, and is executed using the user's shell ‘exec’ directive to avoid a lingering shell process. Arguments to ProxyCommand accept the tokens described in the TOKENS section. The command can be basically anything, and should read from its standard input and write to its standard output. It should eventually connect an sshd(8) server running on some machine, or execute sshd -i somewhere. Host key management will be done using the Hostname of the host being connected (defaulting to the name typed by the user). Setting the command to none disables this option entirely. Note that CheckHostIP is not available for connects with a proxy command. This directive is useful in conjunction with nc(1) and its proxy support. For example, the following directive would connect via an HTTP proxy at 192.0.2.0: @@ -760,8 +751,8 @@ hmac-sha2-256,hmac-sha2-512,hmac-sha1 "PubkeyAcceptedAlgorithms": { Documentation: `Specifies the signature algorithms that will be used for public key authentication as a comma-separated list of patterns. If the specified list begins with a ‘+’ character, then the algorithms after it will be appended to the default instead of replacing it. If the specified list begins with a ‘-’ character, then the specified algorithms (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a ‘^’ character, then the specified algorithms will be placed at the head of the default set. The default for this option is: - - ssh-ed25519-cert-v01@openssh.com, + +ssh-ed25519-cert-v01@openssh.com, ecdsa-sha2-nistp256-cert-v01@openssh.com, ecdsa-sha2-nistp384-cert-v01@openssh.com, ecdsa-sha2-nistp521-cert-v01@openssh.com, @@ -774,7 +765,7 @@ ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521, sk-ssh-ed25519@openssh.com, sk-ecdsa-sha2-nistp256@openssh.com, rsa-sha2-512,rsa-sha2-256 - + The list of available signature algorithms may also be obtained using 'ssh -Q PubkeyAcceptedAlgorithms'.`, Value: docvalues.CustomValue{ FetchValue: func(_ docvalues.CustomValueContext) docvalues.Value { @@ -813,8 +804,7 @@ rsa-sha2-512,rsa-sha2-256 Value: docvalues.StringValue{}, }, "RequestTTY": { - Documentation: `Specifies whether to request a pseudo-tty for the session. The argument may be one of: no (never request a TTY), yes (always request a TTY when standard input is a TTY), force (always request a TTY) or auto (request a TTY when opening a login session). This option mirrors the -t and - -T flags for ssh(1).`, + Documentation: `Specifies whether to request a pseudo-tty for the session. The argument may be one of: no (never request a TTY), yes (always request a TTY when standard input is a TTY), force (always request a TTY) or auto (request a TTY when opening a login session). This option mirrors the -t and -T flags for ssh(1).`, Value: docvalues.EnumValue{ EnforceValues: true, Values: []docvalues.EnumString{ @@ -878,9 +868,7 @@ rsa-sha2-512,rsa-sha2-256 Value: booleanEnumValue, }, "StrictHostKeyChecking": { - Documentation: `If this flag is set to yes, ssh(1) will never automatically add host keys to the - ~/.ssh/known_hosts file, and refuses to connect to hosts whose host key has changed. This provides maximum protection against man-in-the-middle (MITM) attacks, though it can be annoying when the - /etc/ssh/ssh_known_hosts file is poorly maintained or when connections to new hosts are frequently made. This option forces the user to manually add all new hosts. + Documentation: `If this flag is set to yes, ssh(1) will never automatically add host keys to the ~/.ssh/known_hosts file, and refuses to connect to hosts whose host key has changed. This provides maximum protection against man-in-the-middle (MITM) attacks, though it can be annoying when the /etc/ssh/ssh_known_hosts file is poorly maintained or when connections to new hosts are frequently made. This option forces the user to manually add all new hosts. If this flag is set to accept-new then ssh will automatically add new host keys to the user's known_hosts file, but will not permit connections to hosts with changed host keys. If this flag is set to no or off, ssh will automatically add new host keys to the user known hosts files and allow connections to hosts with changed hostkeys to proceed, subject to some restrictions. If this flag is set to ask (the default), new host keys will be added to the user known host files only after the user has confirmed that is what they really want to do, and ssh will refuse to connect to hosts whose host key has changed. The host keys of known hosts will be verified automatically in all cases.`, Value: docvalues.EnumValue{ EnforceValues: true, @@ -918,6 +906,7 @@ rsa-sha2-512,rsa-sha2-256 To disable TCP keepalive messages, the value should be set to no. See also ServerAliveInterval for protocol-level keepalives.`, Value: booleanEnumValue, }, + // TODO: Add "Tag": { Documentation: `Specify a configuration tag name that may be later used by a Match directive to select a block of configuration.`, Value: docvalues.StringValue{}, @@ -935,9 +924,7 @@ rsa-sha2-512,rsa-sha2-256 }, }, "TunnelDevice": { - Documentation: `Specifies the tun(4) devices to open on the client - (local_tun) and the server - (remote_tun). + Documentation: `Specifies the tun(4) devices to open on the client (local_tun) and the server (remote_tun). The argument must be local_tun[:remote_tun]. The devices may be specified by numerical ID or the keyword any, which uses the next available tunnel device. If remote_tun is not specified, it defaults to any. The default is any:any.`, Value: docvalues.StringValue{}, }, diff --git a/handlers/ssh_config/fields/options.go b/handlers/ssh_config/fields/options.go new file mode 100644 index 0000000..06127d6 --- /dev/null +++ b/handlers/ssh_config/fields/options.go @@ -0,0 +1,19 @@ +package fields + +var AllowedDuplicateOptions = map[string]struct{}{ + "CertificateFile": {}, + "Match": {}, + "Host": {}, +} + +// A list of +//