Merge pull request #15 from Myzel394/improve-parsers

Improve parsers
This commit is contained in:
Myzel394 2024-10-05 17:18:25 +02:00 committed by GitHub
commit 6e1d600659
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
418 changed files with 23232 additions and 3420 deletions

20
.eslintrc.js Normal file
View File

@ -0,0 +1,20 @@
/**@type {import('eslint').Linter.Config} */
// eslint-disable-next-line no-undef
module.exports = {
root: true,
parser: '@typescript-eslint/parser',
plugins: [
'@typescript-eslint',
],
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
],
rules: {
'semi': [2, "always"],
'@typescript-eslint/no-unused-vars': 0,
'@typescript-eslint/no-explicit-any': 0,
'@typescript-eslint/explicit-module-boundary-types': 0,
'@typescript-eslint/no-non-null-assertion': 0,
}
};

View File

@ -0,0 +1,70 @@
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: 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:
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

View File

@ -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 develop --command bash -c "cd server && go build"

1
.gitignore vendored
View File

@ -28,3 +28,4 @@ test.lua
config-lsp
result
bin
debug.log

16
README.md Normal file
View File

@ -0,0 +1,16 @@
## 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

View File

@ -1,121 +0,0 @@
package common
import (
"fmt"
"github.com/antlr4-go/antlr/v4"
protocol "github.com/tliron/glsp/protocol_3_16"
)
type Location struct {
Line uint32
Character uint32
}
type LocationRange struct {
Start Location
End Location
}
func (l LocationRange) ShiftHorizontal(offset uint32) LocationRange {
return LocationRange{
Start: Location{
Line: l.Start.Line,
Character: l.Start.Character + offset,
},
End: Location{
Line: l.End.Line,
Character: l.End.Character + offset,
},
}
}
func (l LocationRange) String() string {
if l.Start.Line == l.End.Line {
return fmt.Sprintf("%d:%d-%d", l.Start.Line, l.Start.Character, l.End.Character)
}
return fmt.Sprintf("%d:%d-%d:%d", l.Start.Line, l.Start.Character, l.End.Line, l.End.Character)
}
var GlobalLocationRange = LocationRange{
Start: Location{
Line: 0,
Character: 0,
},
End: Location{
Line: 0,
Character: 0,
},
}
func (l LocationRange) ToLSPRange() protocol.Range {
return protocol.Range{
Start: protocol.Position{
Line: l.Start.Line,
Character: l.Start.Character,
},
End: protocol.Position{
Line: l.End.Line,
Character: l.End.Character,
},
}
}
func (l *LocationRange) ChangeBothLines(newLine uint32) {
l.Start.Line = newLine
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
}
func CreateFullLineRange(line uint32) LocationRange {
return LocationRange{
Start: Location{
Line: line,
Character: 0,
},
End: Location{
Line: line,
Character: 999999,
},
}
}
func CreateSingleCharRange(line uint32, character uint32) LocationRange {
return LocationRange{
Start: Location{
Line: line,
Character: character,
},
End: Location{
Line: line,
Character: character,
},
}
}
func CharacterRangeFromCtx(
ctx antlr.BaseParserRuleContext,
) LocationRange {
line := uint32(ctx.GetStart().GetLine())
start := uint32(ctx.GetStart().GetStart())
end := uint32(ctx.GetStop().GetStop())
return LocationRange{
Start: Location{
Line: line,
Character: start,
},
End: Location{
Line: line,
Character: end + 1,
},
}
}

View File

@ -1,37 +0,0 @@
package docvalues
import (
protocol "github.com/tliron/glsp/protocol_3_16"
)
type CustomValueContext interface {
GetIsContext() bool
}
type EmptyValueContext struct{}
func (EmptyValueContext) GetIsContext() bool {
return true
}
var EmptyValueContextInstance = EmptyValueContext{}
type CustomValue struct {
FetchValue func(context CustomValueContext) Value
}
func (v CustomValue) GetTypeDescription() []string {
return v.FetchValue(EmptyValueContextInstance).GetTypeDescription()
}
func (v CustomValue) CheckIsValid(value string) []*InvalidValue {
return v.FetchValue(EmptyValueContextInstance).CheckIsValid(value)
}
func (v CustomValue) FetchCompletions(line string, cursor uint32) []protocol.CompletionItem {
return v.FetchValue(EmptyValueContextInstance).FetchCompletions(line, cursor)
}
func (v CustomValue) FetchHoverInfo(line string, cursor uint32) []string {
return v.FetchValue(EmptyValueContextInstance).FetchHoverInfo(line, cursor)
}

View File

@ -1,28 +0,0 @@
package docvalues
import (
"strings"
protocol "github.com/tliron/glsp/protocol_3_16"
)
type DocumentationValue struct {
Documentation string
Value Value
}
func (v DocumentationValue) GetTypeDescription() []string {
return v.Value.GetTypeDescription()
}
func (v DocumentationValue) CheckIsValid(value string) []*InvalidValue {
return v.Value.CheckIsValid(value)
}
func (v DocumentationValue) FetchCompletions(line string, cursor uint32) []protocol.CompletionItem {
return v.Value.FetchCompletions(line, cursor)
}
func (v DocumentationValue) FetchHoverInfo(line string, cursor uint32) []string {
return strings.Split(v.Documentation, "\n")
}

View File

@ -1,73 +0,0 @@
package docvalues
import (
"config-lsp/utils"
"fmt"
"strings"
protocol "github.com/tliron/glsp/protocol_3_16"
)
type Prefix struct {
Prefix string
Meaning string
}
type PrefixWithMeaningValue struct {
Prefixes []Prefix
SubValue Value
}
func (v PrefixWithMeaningValue) GetTypeDescription() []string {
subDescription := v.SubValue.GetTypeDescription()
prefixDescription := utils.Map(v.Prefixes, func(prefix Prefix) string {
return fmt.Sprintf("_%s_ -> %s", prefix.Prefix, prefix.Meaning)
})
return append(subDescription,
append(
[]string{"The following prefixes are allowed:"},
prefixDescription...,
)...,
)
}
func (v PrefixWithMeaningValue) CheckIsValid(value string) []*InvalidValue {
for _, prefix := range v.Prefixes {
if strings.HasPrefix(value, prefix.Prefix) {
return v.SubValue.CheckIsValid(value[len(prefix.Prefix):])
}
}
return v.SubValue.CheckIsValid(value)
}
func (v PrefixWithMeaningValue) FetchCompletions(line string, cursor uint32) []protocol.CompletionItem {
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,
}
})
return append(prefixCompletions, v.SubValue.FetchCompletions(line, cursor)...)
}
func (v PrefixWithMeaningValue) FetchHoverInfo(line string, cursor uint32) []string {
for _, prefix := range v.Prefixes {
if strings.HasPrefix(line, prefix.Prefix) {
return append([]string{
fmt.Sprintf("Prefix: _%s_ -> %s", prefix.Prefix, prefix.Meaning),
},
v.SubValue.FetchHoverInfo(line[1:], cursor)...,
)
}
}
return v.SubValue.FetchHoverInfo(line[1:], cursor)
}

View File

@ -26,26 +26,53 @@
};
inputs = [
pkgs.go_1_22
pkgs.wireguard-tools
];
in {
packages = {
default = pkgs.buildGoModule {
server = pkgs.buildGoModule {
nativeBuildInputs = inputs;
pname = "github.com/Myzel394/config-lsp";
version = "v0.0.1";
src = ./.;
vendorHash = "sha256-KhyqogTyb3jNrGP+0Zmn/nfx+WxzjgcrFOp2vivFgT0=";
src = ./server;
vendorHash = "sha256-s+sjOVvqU20+mbEFKg+RCD+dhScqSatk9eseX2IioPI=";
checkPhase = ''
go test -v $(pwd)/...
'';
};
in {
packages = {
default = server;
"vs-code-extension" = let
name = "config-lsp-vs-code-extension";
node-modules = pkgs.mkYarnPackage {
src = ./vs-code-extension;
name = name;
packageJSON = ./vs-code-extension/package.json;
yarnLock = ./vs-code-extension/yarn.lock;
yarnNix = ./vs-code-extension/yarn.nix;
buildPhase = ''
yarn --offline run compile
'';
installPhase = ''
mv deps/${name}/out $out
cp ${server}/bin/config-lsp $out/
'';
distPhase = "true";
};
in node-modules;
};
devShells.default = pkgs.mkShell {
buildInputs = inputs ++ (with pkgs; [
mailutils
swaks
]);
wireguard-tools
antlr
]) ++ (if pkgs.stdenv.isLinux then with pkgs; [
postfix
] else []);
};
devShells."vs-code-extension" = pkgs.mkShell {
buildInputs = [
pkgs.nodejs
];
};
}
);

View File

@ -1,21 +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) {
// _, 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)
// }
return nil, nil
}

View File

@ -1,7 +0,0 @@
package fstab
import (
protocol "github.com/tliron/glsp/protocol_3_16"
)
var documentParserMap = map[protocol.DocumentUri]*FstabParser{}

View File

@ -1,112 +0,0 @@
package fstab
import (
docvalues "config-lsp/doc-values"
fstabdocumentation "config-lsp/handlers/fstab/documentation"
"github.com/tliron/glsp"
protocol "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,
cursor uint32,
) ([]protocol.CompletionItem, error) {
targetField := line.GetFieldAtPosition(cursor)
switch targetField {
case FstabFieldSpec:
value, cursor := GetFieldSafely(line.Fields.Spec, cursor)
return fstabdocumentation.SpecField.FetchCompletions(
value,
cursor,
), nil
case FstabFieldMountPoint:
value, cursor := GetFieldSafely(line.Fields.MountPoint, cursor)
return fstabdocumentation.MountPointField.FetchCompletions(
value,
cursor,
), nil
case FstabFieldFileSystemType:
value, cursor := GetFieldSafely(line.Fields.FilesystemType, cursor)
return fstabdocumentation.FileSystemTypeField.FetchCompletions(
value,
cursor,
), nil
case FstabFieldOptions:
fileSystemType := line.Fields.FilesystemType.Value
var optionsField docvalues.Value
if foundField, found := fstabdocumentation.MountOptionsMapField[fileSystemType]; found {
optionsField = foundField
} else {
optionsField = fstabdocumentation.DefaultMountOptionsField
}
value, cursor := GetFieldSafely(line.Fields.Options, cursor)
completions := optionsField.FetchCompletions(
value,
cursor,
)
return completions, nil
case FstabFieldFreq:
value, cursor := GetFieldSafely(line.Fields.Freq, cursor)
return fstabdocumentation.FreqField.FetchCompletions(
value,
cursor,
), nil
case FstabFieldPass:
value, cursor := GetFieldSafely(line.Fields.Pass, cursor)
return fstabdocumentation.PassField.FetchCompletions(
value,
cursor,
), nil
}
return nil, nil
}
// Safely get value and new cursor position
// If field is nil, return empty string and 0
func GetFieldSafely(field *Field, character uint32) (string, uint32) {
if field == nil {
return "", 0
}
if field.Value == "" {
return "", 0
}
return field.Value, character - field.Start
}

View File

@ -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
}

View File

@ -1,71 +0,0 @@
package fstab
import (
docvalues "config-lsp/doc-values"
fstabdocumentation "config-lsp/handlers/fstab/documentation"
"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) {
line := entry.Line
targetField := line.GetFieldAtPosition(cursor)
switch targetField {
case FstabFieldSpec:
return &SpecHoverField, nil
case FstabFieldMountPoint:
return &MountPointHoverField, nil
case FstabFieldFileSystemType:
return &FileSystemTypeField, nil
case FstabFieldOptions:
fileSystemType := line.Fields.FilesystemType.Value
var optionsField docvalues.Value
if foundField, found := fstabdocumentation.MountOptionsMapField[fileSystemType]; found {
optionsField = foundField
} else {
optionsField = fstabdocumentation.DefaultMountOptionsField
}
relativeCursor := cursor - line.Fields.Options.Start
fieldInfo := optionsField.FetchHoverInfo(line.Fields.Options.Value, relativeCursor)
hover := protocol.Hover{
Contents: protocol.MarkupContent{
Kind: protocol.MarkupKindMarkdown,
Value: strings.Join(fieldInfo, "\n"),
},
}
return &hover, nil
case FstabFieldFreq:
return &FreqHoverField, nil
case FstabFieldPass:
return &PassHoverField, nil
}
return nil, nil
}

View File

@ -1,145 +0,0 @@
package analyzer
import (
"config-lsp/handlers/hosts/ast"
"config-lsp/utils"
"net"
"testing"
)
func TestValidSimpleExampleWorks(
t *testing.T,
) {
input := utils.Dedent(`
1.2.3.4 hello.com
`)
parser := ast.NewHostsParser()
errors := parser.Parse(input)
if len(errors) != 0 {
t.Errorf("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[0].IPAddress == nil {
t.Errorf("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)
}
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 !(parser.Tree.Entries[0].Aliases == nil) {
t.Errorf("Expected no aliases, but got %v", parser.Tree.Entries[0].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 !(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 !(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 !(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 !(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 !(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 !(len(parser.CommentLines) == 0) {
t.Errorf("Expected no comment lines, but got %v", len(parser.CommentLines))
}
}
func TestValidComplexExampleWorks(
t *testing.T,
) {
input := utils.Dedent(`
# This is a comment
1.2.3.4 hello.com test.com # This is another comment
5.5.5.5 test.com
1.2.3.4 example.com check.com
`)
parser := ast.NewHostsParser()
errors := parser.Parse(input)
if len(errors) != 0 {
t.Errorf("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[2].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 !(len(parser.CommentLines) == 1) {
t.Errorf("Expected 1 comment line, but got %v", len(parser.CommentLines))
}
if !(utils.KeyExists(parser.CommentLines, 1)) {
t.Errorf("Expected comment line 2 to exist, but it does not")
}
}
func TestInvalidExampleWorks(
t *testing.T,
) {
input := utils.Dedent(`
1.2.3.4
`)
parser := ast.NewHostsParser()
errors := parser.Parse(input)
if len(errors) == 0 {
t.Errorf("Expected errors, but got none")
}
if !(len(parser.Tree.Entries) == 1) {
t.Errorf("Expected 1 entries, but got %v", len(parser.Tree.Entries))
}
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)
}
if !(parser.Tree.Entries[0].Hostname == nil) {
t.Errorf("Expected hostname to be nil, but got %v", parser.Tree.Entries[0].Hostname)
}
if !(parser.Tree.Entries[0].Aliases == nil) {
t.Errorf("Expected aliases to be nil, but got %v", parser.Tree.Entries[0].Aliases)
}
}

View File

@ -1,48 +0,0 @@
token literal names:
null
null
'/'
'.'
':'
'#'
null
null
null
null
null
token symbolic names:
null
COMMENTLINE
SLASH
DOT
COLON
HASHTAG
SEPARATOR
NEWLINE
DIGITS
OCTETS
DOMAIN
rule names:
lineStatement
entry
aliases
alias
hostname
domain
ipAddress
ipv4Address
singleIPv4Address
ipv6Address
singleIPv6Address
ipv4Digit
ipv6Octet
ipRange
ipRangeBits
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]

View File

@ -1,50 +0,0 @@
token literal names:
null
null
'/'
'.'
':'
'#'
null
null
null
null
null
token symbolic names:
null
COMMENTLINE
SLASH
DOT
COLON
HASHTAG
SEPARATOR
NEWLINE
DIGITS
OCTETS
DOMAIN
rule names:
COMMENTLINE
SLASH
DOT
COLON
HASHTAG
SEPARATOR
NEWLINE
DIGITS
DIGIT
OCTETS
OCTET
DOMAIN
STRING
channel names:
DEFAULT_TOKEN_CHANNEL
HIDDEN
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]

View File

@ -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
}

View File

@ -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)
}

View File

@ -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
}

View File

@ -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}
}

View File

@ -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
}

View File

@ -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{},
),
}

View File

@ -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{}
}

View File

@ -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<OptionName>\w+)(?P<Separator>\s*)(?P<Value>.*)\s*$`),
IgnorePattern: *regexp.MustCompile(`^(?:#|\s*$)`),
IdealSeparator: " ",
AvailableOptions: &Options,
},
}
}
var Parser = createOpenSSHConfigParser()

View File

@ -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
}

View File

@ -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
}

View File

@ -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
}

View File

@ -1,5 +0,0 @@
package openssh
import "regexp"
var isJustDigitsPattern = regexp.MustCompile(`^\d+$`)

View File

@ -2,7 +2,7 @@ package commondocumentation
import docvalues "config-lsp/doc-values"
var AdfsDocumentationAssignable = map[docvalues.EnumString]docvalues.Value{
var AdfsDocumentationAssignable = map[docvalues.EnumString]docvalues.DeprecatedValue{
docvalues.CreateEnumStringWithDoc(
"uid",
"Set the owner of the files in the filesystem (default: uid=0).",

View File

@ -4,7 +4,7 @@ import docvalues "config-lsp/doc-values"
var prefixMaxLength = uint32(30)
var AffsDocumentationAssignable = map[docvalues.EnumString]docvalues.Value{
var AffsDocumentationAssignable = map[docvalues.EnumString]docvalues.DeprecatedValue{
docvalues.CreateEnumStringWithDoc(
"uid",
"Set the owner and group of the root of the filesystem (default: uid=gid=0, but with option uid or gid without specified value, the UID and GID of the current process are taken).",

View File

@ -4,7 +4,7 @@ import docvalues "config-lsp/doc-values"
var maxInlineMin = 2048
var BtrfsDocumentationAssignable = map[docvalues.EnumString]docvalues.Value{
var BtrfsDocumentationAssignable = map[docvalues.EnumString]docvalues.DeprecatedValue{
docvalues.CreateEnumStringWithDoc(
"check_int_print_mask",
"These debugging options control the behavior of the integrity checking module (the BTRFS_FS_CHECK_INTEGRITY config option required). The main goal is to verify that all blocks from a given transaction period are properly linked.",
@ -71,7 +71,7 @@ var BtrfsDocumentationAssignable = map[docvalues.EnumString]docvalues.Value{
"max_inline",
"Specify the maximum amount of space, that can be inlined in a metadata b-tree leaf. The value is specified in bytes, optionally with a K suffix (case insensitive). In practice, this value is limited by the filesystem block size (named sectorsize at mkfs time), and memory page size of the system. In case of sectorsize limit, there's some space unavailable due to leaf headers. For example, a 4Ki",
): docvalues.OrValue{
Values: []docvalues.Value{
Values: []docvalues.DeprecatedValue{
docvalues.EnumValue{
EnforceValues: true,
Values: []docvalues.EnumString{

View File

@ -2,7 +2,7 @@ package commondocumentation
import docvalues "config-lsp/doc-values"
var DebugfsDocumentationAssignable = map[docvalues.EnumString]docvalues.Value{
var DebugfsDocumentationAssignable = map[docvalues.EnumString]docvalues.DeprecatedValue{
docvalues.CreateEnumStringWithDoc(
"uid",
"Set the owner of the mountpoint.",

View File

@ -2,7 +2,7 @@ package commondocumentation
import docvalues "config-lsp/doc-values"
var DevptsDocumentationAssignable = map[docvalues.EnumString]docvalues.Value{
var DevptsDocumentationAssignable = map[docvalues.EnumString]docvalues.DeprecatedValue{
docvalues.CreateEnumStringWithDoc(
"uid",
"This sets the owner or the group of newly created pseudo terminals to the specified values. When nothing is specified, they will be set to the UID and GID of the creating process. For example, if there is a tty group with GID 5, then gid=5 will cause newly created pseudo terminals to belong to the tty group.",

View File

@ -3,7 +3,7 @@ package commondocumentation
import docvalues "config-lsp/doc-values"
var Ext2DocumentationAssignable = map[docvalues.EnumString]docvalues.Value{
var Ext2DocumentationAssignable = map[docvalues.EnumString]docvalues.DeprecatedValue{
docvalues.CreateEnumStringWithDoc(
"none",
"No checking is done at mount time. This is the default. This is fast. It is wise to invoke e2fsck(8) every now and then, e.g. at boot time. The non-default behavior is unsupported (check=normal and check=strict options have been removed). Note that these mount options don't have to be supported if ext4 kernel driver is used for ext2 and ext3 file systems.",

View File

@ -5,7 +5,7 @@ package commondocumentation
import docvalues "config-lsp/doc-values"
var Ext3DocumentationAssignable = map[docvalues.EnumString]docvalues.Value{
var Ext3DocumentationAssignable = map[docvalues.EnumString]docvalues.DeprecatedValue{
docvalues.CreateEnumStringWithDoc(
"journal_dev",
"When the external journal device's major/minor numbers have changed, these options allow the user to specify the new journal location. The journal device is identified either through its new major/minor numbers encoded in devnum, or via a path to the device.",

View File

@ -5,7 +5,7 @@ import docvalues "config-lsp/doc-values"
var zero = 0
var maxJournalIOPrio = 7
var Ext4DocumentationAssignable = map[docvalues.EnumString]docvalues.Value{
var Ext4DocumentationAssignable = map[docvalues.EnumString]docvalues.DeprecatedValue{
docvalues.CreateEnumStringWithDoc(
"inode_readahead_blks",
"This tuning parameter controls the maximum number of inode table blocks that ext4's inode table readahead algorithm will pre-read into the buffer cache. The value must be a power of 2. The default value is 32 blocks.",

View File

@ -4,7 +4,7 @@ import (
docvalues "config-lsp/doc-values"
)
var FatDocumentationAssignable = map[docvalues.EnumString]docvalues.Value{
var FatDocumentationAssignable = map[docvalues.EnumString]docvalues.DeprecatedValue{
docvalues.CreateEnumStringWithDoc(
"blocksize",
"Set blocksize (default 512). This option is obsolete.",

View File

@ -2,7 +2,7 @@ package commondocumentation
import docvalues "config-lsp/doc-values"
var HfsDocumentationAssignable = map[docvalues.EnumString]docvalues.Value{
var HfsDocumentationAssignable = map[docvalues.EnumString]docvalues.DeprecatedValue{
docvalues.CreateEnumStringWithDoc(
"creator",
"Set the creator/type values as shown by the MacOS finder used for creating new files. Default values: '????'.",

View File

@ -2,7 +2,7 @@ package commondocumentation
import docvalues "config-lsp/doc-values"
var HpfsDocumentationAssignable = map[docvalues.EnumString]docvalues.Value{
var HpfsDocumentationAssignable = map[docvalues.EnumString]docvalues.DeprecatedValue{
docvalues.CreateEnumStringWithDoc(
"uid",
"Set the owner and group of all files. (Default: the UID and GID of the current process.)",

View File

@ -2,7 +2,7 @@ package commondocumentation
import docvalues "config-lsp/doc-values"
var Iso9660DocumentationAssignable = map[docvalues.EnumString]docvalues.Value{
var Iso9660DocumentationAssignable = map[docvalues.EnumString]docvalues.DeprecatedValue{
docvalues.CreateEnumStringWithDoc(
"check",
"With check=relaxed, a filename is first converted to lower case before doing the lookup. This is probably only meaningful together with norock and map=normal. (Default: check=strict.)",

View File

@ -2,7 +2,7 @@ package commondocumentation
import docvalues "config-lsp/doc-values"
var JfsDocumentationAssignable = map[docvalues.EnumString]docvalues.Value{
var JfsDocumentationAssignable = map[docvalues.EnumString]docvalues.DeprecatedValue{
docvalues.CreateEnumStringWithDoc(
"iocharset",
"Character set to use for converting from Unicode to ASCII. The default is to do no conversion. Use iocharset=utf8 for UTF8 translations. This requires CONFIG_NLS_UTF8 to be set in the kernel .config file.",

View File

@ -2,6 +2,6 @@ package commondocumentation
import docvalues "config-lsp/doc-values"
var NcpfsDocumentationAssignable = map[docvalues.EnumString]docvalues.Value{}
var NcpfsDocumentationAssignable = map[docvalues.EnumString]docvalues.DeprecatedValue{}
var NcpfsDocumentationEnums = []docvalues.EnumString{}

View File

@ -2,7 +2,7 @@ package commondocumentation
import docvalues "config-lsp/doc-values"
var NtfsDocumentationAssignable = map[docvalues.EnumString]docvalues.Value{
var NtfsDocumentationAssignable = map[docvalues.EnumString]docvalues.DeprecatedValue{
docvalues.CreateEnumStringWithDoc(
"iocharset",
"Character set to use when returning file names. Unlike VFAT, NTFS suppresses names that contain nonconvertible characters. Deprecated.",

View File

@ -2,7 +2,7 @@ package commondocumentation
import docvalues "config-lsp/doc-values"
var OverlayDocumentationAssignable = map[docvalues.EnumString]docvalues.Value{
var OverlayDocumentationAssignable = map[docvalues.EnumString]docvalues.DeprecatedValue{
docvalues.CreateEnumStringWithDoc(
"lowerdir",
"Any filesystem, does not need to be on a writable filesystem.",

View File

@ -2,7 +2,7 @@ package commondocumentation
import docvalues "config-lsp/doc-values"
var ReiserfsDocumentationAssignable = map[docvalues.EnumString]docvalues.Value{
var ReiserfsDocumentationAssignable = map[docvalues.EnumString]docvalues.DeprecatedValue{
docvalues.CreateEnumStringWithDoc(
"hash",
"Choose which hash function reiserfs will use to find files within directories.",

View File

@ -2,7 +2,7 @@ package commondocumentation
import docvalues "config-lsp/doc-values"
var UbifsDocumentationAssignable = map[docvalues.EnumString]docvalues.Value{
var UbifsDocumentationAssignable = map[docvalues.EnumString]docvalues.DeprecatedValue{
docvalues.CreateEnumStringWithDoc(
"compr",
"Select the default compressor which is used when new files are written. It is still possible to read compressed files if mounted with the none option.",

View File

@ -2,7 +2,7 @@ package commondocumentation
import docvalues "config-lsp/doc-values"
var UdfDocumentationAssignable = map[docvalues.EnumString]docvalues.Value{
var UdfDocumentationAssignable = map[docvalues.EnumString]docvalues.DeprecatedValue{
docvalues.CreateEnumStringWithDoc(
"uid",
"Make all files in the filesystem belong to the given user. uid=forget can be specified independently of (or usually in addition to) uid=<user> and results in UDF not storing uids to the media. In fact the recorded uid is the 32-bit overflow uid -1 as defined by the UDF standard. The value is given as either <user> which is a valid user name or the corresponding decimal user id, or the special string 'forget'.",

View File

@ -2,7 +2,7 @@ package commondocumentation
import docvalues "config-lsp/doc-values"
var UfsDocumentationAssignable = map[docvalues.EnumString]docvalues.Value{
var UfsDocumentationAssignable = map[docvalues.EnumString]docvalues.DeprecatedValue{
docvalues.CreateEnumStringWithDoc(
"ufstype",
"UFS is a filesystem widely used in different operating systems. The problem are differences among implementations. Features of some implementations are undocumented, so its hard to recognize the type of ufs automatically. Thats why the user must specify the type of ufs by mount option.",

View File

@ -5,7 +5,7 @@ import (
"config-lsp/utils"
)
var UmsdosDocumentationAssignable = utils.FilterMap(MsdosDocumentationAssignable, func(key docvalues.EnumString, value docvalues.Value) bool {
var UmsdosDocumentationAssignable = utils.FilterMap(MsdosDocumentationAssignable, func(key docvalues.EnumString, value docvalues.DeprecatedValue) bool {
// `dotsOK` is explicitly not supported
if key.InsertText == "dotsOK" {
return false

View File

@ -2,7 +2,7 @@ package commondocumentation
import docvalues "config-lsp/doc-values"
var UsbfsDocumentationAssignable = docvalues.MergeKeyEnumAssignmentMaps(FatDocumentationAssignable, map[docvalues.EnumString]docvalues.Value{
var UsbfsDocumentationAssignable = docvalues.MergeKeyEnumAssignmentMaps(FatDocumentationAssignable, map[docvalues.EnumString]docvalues.DeprecatedValue{
docvalues.CreateEnumStringWithDoc(
"devuid",
"Set the owner of the device files in the usbfs filesystem (default: uid=gid=0)",

View File

@ -2,7 +2,7 @@ package commondocumentation
import docvalues "config-lsp/doc-values"
var VfatDocumentationAssignable = docvalues.MergeKeyEnumAssignmentMaps(FatDocumentationAssignable, map[docvalues.EnumString]docvalues.Value{
var VfatDocumentationAssignable = docvalues.MergeKeyEnumAssignmentMaps(FatDocumentationAssignable, map[docvalues.EnumString]docvalues.DeprecatedValue{
docvalues.CreateEnumStringWithDoc(
"shortname",
"Defines the behavior for creation and display of filenames which fit into 8.3 characters. If a long name for a file exists, it will always be the preferred one for display",

View File

@ -1,6 +1,8 @@
package common
import (
"config-lsp/utils"
protocol "github.com/tliron/glsp/protocol_3_16"
)
@ -30,3 +32,12 @@ type SyntaxError struct {
func (s SyntaxError) Error() string {
return s.Message
}
func ErrsToDiagnostics(errs []LSPError) []protocol.Diagnostic {
return utils.Map(
errs,
func(err LSPError) protocol.Diagnostic {
return err.ToDiagnostic()
},
)
}

View File

@ -0,0 +1,119 @@
package formatting
import (
"fmt"
"strings"
protocol "github.com/tliron/glsp/protocol_3_16"
)
var DefaultFormattingOptions = protocol.FormattingOptions{
"tabSize": float64(4),
"insertSpaces": false,
"trimTrailingWhitespace": true,
}
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")
}
value = surroundWithQuotes(value)
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 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 innerValue[0] == '"' && innerValue[len(innerValue)-1] == '"' && (len(innerValue) >= 2 || innerValue[len(innerValue)-2] != '\\') {
// Already surrounded
value = value[:startPosition-3] + innerValue + value[endPosition+3:]
} else 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)
if insertSpace {
return strings.Repeat(" ", int(tabSize))
} else {
return "\t"
}
}

View File

@ -0,0 +1,137 @@
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)
}
}
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)
}
}
func TestSurroundWithQuotesButAlreadySurrounded(
t *testing.T,
) {
template := FormatTemplate("%s /!'%s/!'")
options := protocol.FormattingOptions{
"tabSize": float64(4),
"insertSpaces": false,
"trimTrailingWhitespace": true,
}
result := template.Format(options, "PermitRootLogin", `"Hello World"`)
expected := `PermitRootLogin "Hello World"`
if result != expected {
t.Errorf("Expected %q but got %q", expected, result)
}
}

216
server/common/location.go Normal file
View File

@ -0,0 +1,216 @@
package common
import (
"fmt"
"github.com/antlr4-go/antlr/v4"
protocol "github.com/tliron/glsp/protocol_3_16"
)
type Location struct {
Line uint32
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{
Line: l.Start.Line,
Character: l.Start.Character + offset,
},
End: Location{
Line: l.End.Line,
Character: l.End.Character + offset,
},
}
}
func (l LocationRange) String() string {
if l.Start.Line == l.End.Line {
return fmt.Sprintf("%d:%d-%d", l.Start.Line, l.Start.Character, l.End.Character)
}
return fmt.Sprintf("%d:%d-%d:%d", l.Start.Line, l.Start.Character, l.End.Line, l.End.Character)
}
var GlobalLocationRange = LocationRange{
Start: Location{
Line: 0,
Character: 0,
},
End: Location{
Line: 0,
Character: 0,
},
}
func (l LocationRange) ToLSPRange() protocol.Range {
return protocol.Range{
Start: protocol.Position{
Line: l.Start.Line,
Character: l.Start.Character,
},
End: protocol.Position{
Line: l.End.Line,
Character: l.End.Character,
},
}
}
func (l *LocationRange) ChangeBothLines(newLine uint32) {
l.Start.Line = newLine
l.End.Line = newLine
}
func (l LocationRange) ContainsCursorByCharacter(character uint32) bool {
return character >= l.Start.Character && character <= l.End.Character
}
func CreateFullLineRange(line uint32) LocationRange {
return LocationRange{
Start: Location{
Line: line,
Character: 0,
},
End: Location{
Line: line,
Character: 999999,
},
}
}
func CreateSingleCharRange(line uint32, character uint32) LocationRange {
return LocationRange{
Start: Location{
Line: line,
Character: character,
},
End: Location{
Line: line,
Character: character,
},
}
}
func CharacterRangeFromCtx(
ctx antlr.BaseParserRuleContext,
) LocationRange {
line := uint32(ctx.GetStart().GetLine())
start := uint32(ctx.GetStart().GetStart())
end := uint32(ctx.GetStop().GetStop())
return LocationRange{
Start: Location{
Line: line,
Character: start,
},
End: Location{
Line: line,
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)
}

View File

@ -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")
}
}

26
server/common/lsp.go Normal file
View File

@ -0,0 +1,26 @@
package common
import protocol "github.com/tliron/glsp/protocol_3_16"
// 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)
}
var SeverityError = protocol.DiagnosticSeverityError
var SeverityWarning = protocol.DiagnosticSeverityWarning
var SeverityInformation = protocol.DiagnosticSeverityInformation
var SeverityHint = protocol.DiagnosticSeverityHint

View File

@ -0,0 +1,126 @@
package parser
type ParseFeatures struct {
ParseDoubleQuotes bool
ParseEscapedCharacters bool
}
var FullFeatures = ParseFeatures{
ParseDoubleQuotes: true,
ParseEscapedCharacters: true,
}
type ParsedString struct {
Raw string
Value string
}
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,
}
}
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
}

View File

@ -0,0 +1,167 @@
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",
}
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",
}
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",
}
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`,
}
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"`,
}
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`,
}
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`,
}
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"`,
}
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`,
}
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`,
}
actual := ParseRawString(input, FullFeatures)
if !(cmp.Equal(expected, actual)) {
t.Errorf("Expected %v, got %v", expected, actual)
}
}

View File

@ -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
}

View File

@ -5,11 +5,11 @@ import (
protocol "github.com/tliron/glsp/protocol_3_16"
)
type Value interface {
type DeprecatedValue interface {
GetTypeDescription() []string
CheckIsValid(value string) []*InvalidValue
FetchCompletions(line string, cursor uint32) []protocol.CompletionItem
FetchHoverInfo(line string, cursor uint32) []string
DeprecatedCheckIsValid(value string) []*InvalidValue
DeprecatedFetchCompletions(line string, cursor uint32) []protocol.CompletionItem
DeprecatedFetchHoverInfo(line string, cursor uint32) []string
}
type InvalidValue struct {
@ -31,7 +31,7 @@ func (v *InvalidValue) GetRange(line uint32, characterStart uint32) protocol.Ran
},
End: protocol.Position{
Line: line,
Character: characterStart + v.End,
Character: characterStart + v.End + 1,
},
}
}

View File

@ -68,7 +68,7 @@ func (e ValueError) GetPublishDiagnosticsParams() protocol.Diagnostic {
}
}
func (e ValueError) Error() string {
return "Value error"
return "DeprecatedValue error"
}
type OptionAlreadyExistsError struct {

View File

@ -6,11 +6,11 @@ import (
"regexp"
)
// UserValue returns a Value that fetches user names from /etc/passwd
// UserValue returns a DeprecatedValue that fetches user names from /etc/passwd
// if `separatorForMultiple` is not empty, it will return an ArrayValue
func UserValue(separatorForMultiple string, enforceValues bool) Value {
func UserValue(separatorForMultiple string, enforceValues bool) DeprecatedValue {
return CustomValue{
FetchValue: func(context CustomValueContext) Value {
FetchValue: func(context CustomValueContext) DeprecatedValue {
infos, err := common.FetchPasswdInfo()
if err != nil {
@ -37,9 +37,9 @@ func UserValue(separatorForMultiple string, enforceValues bool) Value {
}
}
func GroupValue(separatorForMultiple string, enforceValues bool) Value {
func GroupValue(separatorForMultiple string, enforceValues bool) DeprecatedValue {
return CustomValue{
FetchValue: func(context CustomValueContext) Value {
FetchValue: func(context CustomValueContext) DeprecatedValue {
infos, err := common.FetchGroupInfo()
if err != nil {
@ -66,14 +66,14 @@ func GroupValue(separatorForMultiple string, enforceValues bool) Value {
}
}
func PositiveNumberValue() Value {
func PositiveNumberValue() DeprecatedValue {
zero := 0
return NumberValue{
Min: &zero,
}
}
func MaskValue() Value {
func MaskValue() DeprecatedValue {
min := 0
max := 777
return NumberValue{Min: &min, Max: &max}
@ -88,7 +88,7 @@ func SingleEnumValue(value string) EnumValue {
}
}
func DomainValue() Value {
func DomainValue() DeprecatedValue {
return RegexValue{
Regex: *regexp.MustCompile(`^.+?\..+$`),
}

View File

@ -20,9 +20,9 @@ func GenerateBase10Completions(prefix string) []protocol.CompletionItem {
)
}
func MergeKeyEnumAssignmentMaps(maps ...map[EnumString]Value) map[EnumString]Value {
func MergeKeyEnumAssignmentMaps(maps ...map[EnumString]DeprecatedValue) map[EnumString]DeprecatedValue {
existingEnums := make(map[string]interface{})
result := make(map[EnumString]Value)
result := make(map[EnumString]DeprecatedValue)
slices.Reverse(maps)

View File

@ -35,7 +35,7 @@ var ExtractKeyDuplicatesExtractor = func(separator string) func(string) string {
var DuplicatesAllowedExtractor func(string) string = nil
type ArrayValue struct {
SubValue Value
SubValue DeprecatedValue
Separator string
// If this function is nil, no duplicate check is done.
// (value) => Extracted value
@ -45,7 +45,7 @@ type ArrayValue struct {
}
func (v ArrayValue) GetTypeDescription() []string {
subValue := v.SubValue.(Value)
subValue := v.SubValue.(DeprecatedValue)
return append(
[]string{fmt.Sprintf("An Array separated by '%s' of:", v.Separator)},
@ -53,7 +53,7 @@ func (v ArrayValue) GetTypeDescription() []string {
)
}
func (v ArrayValue) CheckIsValid(value string) []*InvalidValue {
func (v ArrayValue) DeprecatedCheckIsValid(value string) []*InvalidValue {
errors := []*InvalidValue{}
values := strings.Split(value, v.Separator)
@ -100,7 +100,7 @@ func (v ArrayValue) CheckIsValid(value string) []*InvalidValue {
currentIndex := uint32(0)
for _, subValue := range values {
newErrors := v.SubValue.CheckIsValid(subValue)
newErrors := v.SubValue.DeprecatedCheckIsValid(subValue)
if len(newErrors) > 0 {
ShiftInvalidValues(currentIndex, newErrors)
@ -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)),
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,26 +156,31 @@ 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 {
func (v ArrayValue) DeprecatedFetchCompletions(line string, cursor uint32) []protocol.CompletionItem {
value, cursor := v.getCurrentValue(line, cursor)
return v.SubValue.FetchCompletions(value, cursor)
return v.SubValue.DeprecatedFetchCompletions(value, cursor)
}
func (v ArrayValue) FetchHoverInfo(line string, cursor uint32) []string {
func (v ArrayValue) DeprecatedFetchHoverInfo(line string, cursor uint32) []string {
value, cursor := v.getCurrentValue(line, cursor)
return v.SubValue.FetchHoverInfo(value, cursor)
return v.SubValue.DeprecatedFetchHoverInfo(value, cursor)
}

View File

@ -0,0 +1,37 @@
package docvalues
import (
protocol "github.com/tliron/glsp/protocol_3_16"
)
type CustomValueContext interface {
GetIsContext() bool
}
type EmptyValueContext struct{}
func (EmptyValueContext) GetIsContext() bool {
return true
}
var EmptyValueContextInstance = EmptyValueContext{}
type CustomValue struct {
FetchValue func(context CustomValueContext) DeprecatedValue
}
func (v CustomValue) GetTypeDescription() []string {
return v.FetchValue(EmptyValueContextInstance).GetTypeDescription()
}
func (v CustomValue) DeprecatedCheckIsValid(value string) []*InvalidValue {
return v.FetchValue(EmptyValueContextInstance).DeprecatedCheckIsValid(value)
}
func (v CustomValue) DeprecatedFetchCompletions(line string, cursor uint32) []protocol.CompletionItem {
return v.FetchValue(EmptyValueContextInstance).DeprecatedFetchCompletions(line, cursor)
}
func (v CustomValue) DeprecatedFetchHoverInfo(line string, cursor uint32) []string {
return v.FetchValue(EmptyValueContextInstance).DeprecatedFetchHoverInfo(line, cursor)
}

View File

@ -1,7 +1,6 @@
package openssh
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) DeprecatedCheckIsValid(value string) []*InvalidValue {
if !dataAmountCheckPattern.MatchString(value) {
return []*docvalues.InvalidValue{
return []*InvalidValue{
{
Err: InvalidDataAmountError{},
Start: 0,
@ -56,7 +55,7 @@ func calculateLineToKilobyte(value string, unit string) string {
}
}
func (v DataAmountValue) FetchCompletions(line string, cursor uint32) []protocol.CompletionItem {
func (v DataAmountValue) DeprecatedFetchCompletions(line string, cursor uint32) []protocol.CompletionItem {
completions := make([]protocol.CompletionItem, 0)
if line != "" && !dataAmountCheckPattern.MatchString(line) {
@ -85,13 +84,13 @@ func (v DataAmountValue) FetchCompletions(line string, cursor uint32) []protocol
if line == "" || isJustDigitsPattern.MatchString(line) {
completions = append(
completions,
docvalues.GenerateBase10Completions(line)...,
GenerateBase10Completions(line)...,
)
}
return completions
}
func (v DataAmountValue) FetchHoverInfo(line string, cursor uint32) []string {
func (v DataAmountValue) DeprecatedFetchHoverInfo(line string, cursor uint32) []string {
return []string{}
}

View File

@ -0,0 +1,28 @@
package docvalues
import (
"strings"
protocol "github.com/tliron/glsp/protocol_3_16"
)
type DocumentationValue struct {
Documentation string
Value DeprecatedValue
}
func (v DocumentationValue) GetTypeDescription() []string {
return v.Value.GetTypeDescription()
}
func (v DocumentationValue) DeprecatedCheckIsValid(value string) []*InvalidValue {
return v.Value.DeprecatedCheckIsValid(value)
}
func (v DocumentationValue) DeprecatedFetchCompletions(line string, cursor uint32) []protocol.CompletionItem {
return v.Value.DeprecatedFetchCompletions(line, cursor)
}
func (v DocumentationValue) DeprecatedFetchHoverInfo(line string, cursor uint32) []string {
return strings.Split(v.Documentation, "\n")
}

View File

@ -78,7 +78,7 @@ func (v EnumValue) GetTypeDescription() []string {
return lines
}
func (v EnumValue) CheckIsValid(value string) []*InvalidValue {
func (v EnumValue) DeprecatedCheckIsValid(value string) []*InvalidValue {
if !v.EnforceValues {
return nil
}
@ -101,7 +101,7 @@ func (v EnumValue) CheckIsValid(value string) []*InvalidValue {
},
}
}
func (v EnumValue) FetchCompletions(line string, cursor uint32) []protocol.CompletionItem {
func (v EnumValue) DeprecatedFetchCompletions(line string, cursor uint32) []protocol.CompletionItem {
completions := make([]protocol.CompletionItem, len(v.Values))
for index, value := range v.Values {
@ -118,7 +118,7 @@ func (v EnumValue) FetchCompletions(line string, cursor uint32) []protocol.Compl
return completions
}
func (v EnumValue) FetchHoverInfo(line string, cursor uint32) []string {
func (v EnumValue) DeprecatedFetchHoverInfo(line string, cursor uint32) []string {
for _, value := range v.Values {
if value.InsertText == line {
return []string{

View File

@ -35,7 +35,7 @@ func (v GIDValue) GetTypeDescription() []string {
return []string{"Group ID"}
}
func (v GIDValue) CheckIsValid(value string) []*InvalidValue {
func (v GIDValue) DeprecatedCheckIsValid(value string) []*InvalidValue {
uid, err := strconv.Atoi(value)
if err != nil {
@ -90,7 +90,7 @@ var defaultGIDsExplanation = []EnumString{
},
}
func (v GIDValue) FetchCompletions(line string, cursor uint32) []protocol.CompletionItem {
func (v GIDValue) DeprecatedFetchCompletions(line string, cursor uint32) []protocol.CompletionItem {
infos, err := common.FetchGroupInfo()
if err != nil {
@ -128,7 +128,7 @@ func (v GIDValue) FetchCompletions(line string, cursor uint32) []protocol.Comple
return completions
}
func (v GIDValue) FetchHoverInfo(line string, cursor uint32) []string {
func (v GIDValue) DeprecatedFetchHoverInfo(line string, cursor uint32) []string {
uid, err := strconv.Atoi(line)
if err != nil {

View File

@ -66,7 +66,7 @@ func (v IPAddressValue) GetTypeDescription() []string {
return []string{"An IP Address"}
}
func (v IPAddressValue) CheckIsValid(value string) []*InvalidValue {
func (v IPAddressValue) DeprecatedCheckIsValid(value string) []*InvalidValue {
var ip net.Prefix
if v.AllowRange {
@ -151,7 +151,7 @@ func (v IPAddressValue) CheckIsValid(value string) []*InvalidValue {
}
}
func (v IPAddressValue) FetchCompletions(line string, cursor uint32) []protocol.CompletionItem {
func (v IPAddressValue) DeprecatedFetchCompletions(line string, cursor uint32) []protocol.CompletionItem {
if v.AllowedIPs != nil && len(*v.AllowedIPs) != 0 {
kind := protocol.CompletionItemKindValue
@ -184,7 +184,7 @@ func (v IPAddressValue) FetchCompletions(line string, cursor uint32) []protocol.
return []protocol.CompletionItem{}
}
func (v IPAddressValue) FetchHoverInfo(line string, cursor uint32) []string {
func (v IPAddressValue) DeprecatedFetchHoverInfo(line string, cursor uint32) []string {
if v.AllowRange {
ip, err := net.ParsePrefix(line)

View File

@ -9,7 +9,7 @@ import (
)
type KeyEnumAssignmentValue struct {
Values map[EnumString]Value
Values map[EnumString]DeprecatedValue
Separator string
ValueIsOptional bool
}
@ -21,7 +21,7 @@ func (v KeyEnumAssignmentValue) GetTypeDescription() []string {
if len(valueDescription) == 1 {
return []string{
fmt.Sprintf("Key-Value pair in form of '<%s>%s<%s>'", firstKey.DescriptionText, v.Separator, valueDescription[0]),
fmt.Sprintf("Key-DeprecatedValue pair in form of '<%s>%s<%s>'", firstKey.DescriptionText, v.Separator, valueDescription[0]),
}
}
}
@ -33,11 +33,11 @@ func (v KeyEnumAssignmentValue) GetTypeDescription() []string {
}
return append([]string{
"Key-Value pair in form of 'key%svalue'", v.Separator,
"Key-DeprecatedValue pair in form of 'key%svalue'", v.Separator,
}, result...)
}
func (v KeyEnumAssignmentValue) getValue(findKey string) (*Value, bool) {
func (v KeyEnumAssignmentValue) getValue(findKey string) (*DeprecatedValue, bool) {
for key, value := range v.Values {
if key.InsertText == findKey {
switch value.(type) {
@ -59,7 +59,7 @@ func (v KeyEnumAssignmentValue) getValue(findKey string) (*Value, bool) {
return nil, false
}
func (v KeyEnumAssignmentValue) CheckIsValid(value string) []*InvalidValue {
func (v KeyEnumAssignmentValue) DeprecatedCheckIsValid(value string) []*InvalidValue {
parts := strings.Split(value, v.Separator)
if len(parts) == 0 || parts[0] == "" {
@ -96,7 +96,7 @@ func (v KeyEnumAssignmentValue) CheckIsValid(value string) []*InvalidValue {
}
}
errors := (*checkValue).CheckIsValid(parts[1])
errors := (*checkValue).DeprecatedCheckIsValid(parts[1])
if len(errors) > 0 {
ShiftInvalidValues(uint32(len(parts[0])+len(v.Separator)), errors)
@ -147,7 +147,7 @@ func (v KeyEnumAssignmentValue) getValueAtCursor(line string, cursor uint32) (st
relativePosition, found := utils.FindPreviousCharacter(line, v.Separator, int(cursor))
if found {
// Value found
// DeprecatedValue found
selected := valueSelected
return line[uint32(relativePosition+1):], &selected, cursor - uint32(relativePosition)
}
@ -165,7 +165,7 @@ func (v KeyEnumAssignmentValue) getValueAtCursor(line string, cursor uint32) (st
return line, &selected, cursor
}
func (v KeyEnumAssignmentValue) FetchCompletions(line string, cursor uint32) []protocol.CompletionItem {
func (v KeyEnumAssignmentValue) DeprecatedFetchCompletions(line string, cursor uint32) []protocol.CompletionItem {
if cursor == 0 {
return v.FetchEnumCompletions()
}
@ -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 {
@ -188,14 +188,14 @@ func (v KeyEnumAssignmentValue) FetchCompletions(line string, cursor uint32) []p
return v.FetchEnumCompletions()
}
return (*keyValue).FetchCompletions(line, cursor)
return (*keyValue).DeprecatedFetchCompletions(line, cursor)
} else {
return v.FetchEnumCompletions()
}
}
func (v KeyEnumAssignmentValue) FetchHoverInfo(line string, cursor uint32) []string {
if len(v.CheckIsValid(line)) != 0 {
func (v KeyEnumAssignmentValue) DeprecatedFetchHoverInfo(line string, cursor uint32) []string {
if len(v.DeprecatedCheckIsValid(line)) != 0 {
return []string{}
}
@ -228,7 +228,7 @@ func (v KeyEnumAssignmentValue) FetchHoverInfo(line string, cursor uint32) []str
return []string{}
}
info := (*checkValue).FetchHoverInfo(value, cursor)
info := (*checkValue).DeprecatedFetchHoverInfo(value, cursor)
return append(
[]string{

View File

@ -23,9 +23,9 @@ func (KeyValueAssignmentContext) GetIsContext() bool {
}
type KeyValueAssignmentValue struct {
Key Value
Key DeprecatedValue
// If this is a `CustomValue`, it will receive a `KeyValueAssignmentContext`
Value Value
Value DeprecatedValue
ValueIsOptional bool
Separator string
}
@ -36,18 +36,18 @@ func (v KeyValueAssignmentValue) GetTypeDescription() []string {
if len(keyDescription) == 1 && len(valueDescription) == 1 {
return []string{
fmt.Sprintf("Key-Value pair in form of '<%s>%s<%s>'", keyDescription[0], v.Separator, valueDescription[0]),
fmt.Sprintf("Key-DeprecatedValue pair in form of '<%s>%s<%s>'", keyDescription[0], v.Separator, valueDescription[0]),
}
} else {
return []string{
fmt.Sprintf("Key-Value pair in form of 'key%svalue'", v.Separator),
fmt.Sprintf("Key-DeprecatedValue pair in form of 'key%svalue'", v.Separator),
fmt.Sprintf("#### Key\n%s", strings.Join(v.Key.GetTypeDescription(), "\n")),
fmt.Sprintf("#### Value:\n%s", strings.Join(v.Value.GetTypeDescription(), "\n")),
fmt.Sprintf("#### DeprecatedValue:\n%s", strings.Join(v.Value.GetTypeDescription(), "\n")),
}
}
}
func (v KeyValueAssignmentValue) getValue(selectedKey string) Value {
func (v KeyValueAssignmentValue) getValue(selectedKey string) DeprecatedValue {
switch v.Value.(type) {
case CustomValue:
{
@ -65,7 +65,7 @@ func (v KeyValueAssignmentValue) getValue(selectedKey string) Value {
}
}
func (v KeyValueAssignmentValue) CheckIsValid(value string) []*InvalidValue {
func (v KeyValueAssignmentValue) DeprecatedCheckIsValid(value string) []*InvalidValue {
parts := strings.Split(value, v.Separator)
if len(parts) == 0 || parts[0] == "" {
@ -73,7 +73,7 @@ func (v KeyValueAssignmentValue) CheckIsValid(value string) []*InvalidValue {
return nil
}
err := v.Key.CheckIsValid(parts[0])
err := v.Key.DeprecatedCheckIsValid(parts[0])
if err != nil {
return err
@ -93,7 +93,7 @@ func (v KeyValueAssignmentValue) CheckIsValid(value string) []*InvalidValue {
}
}
errors := v.getValue(parts[0]).CheckIsValid(parts[1])
errors := v.getValue(parts[0]).DeprecatedCheckIsValid(parts[1])
if len(errors) > 0 {
ShiftInvalidValues(uint32(len(parts[0])+len(v.Separator)), errors)
@ -103,15 +103,15 @@ func (v KeyValueAssignmentValue) CheckIsValid(value string) []*InvalidValue {
return nil
}
func (v KeyValueAssignmentValue) FetchCompletions(line string, cursor uint32) []protocol.CompletionItem {
if cursor == 0 {
return v.Key.FetchCompletions(line, cursor)
func (v KeyValueAssignmentValue) DeprecatedFetchCompletions(line string, cursor uint32) []protocol.CompletionItem {
if cursor == 0 || line == "" {
return v.Key.DeprecatedFetchCompletions(line, cursor)
}
relativePosition, found := utils.FindPreviousCharacter(
line,
v.Separator,
max(0, int(cursor-1)),
int(cursor),
)
if found {
@ -119,9 +119,9 @@ func (v KeyValueAssignmentValue) FetchCompletions(line string, cursor uint32) []
line = line[uint32(relativePosition+len(v.Separator)):]
cursor -= uint32(relativePosition)
return v.getValue(selectedKey).FetchCompletions(line, cursor)
return v.getValue(selectedKey).DeprecatedFetchCompletions(line, cursor)
} else {
return v.Key.FetchCompletions(line, cursor)
return v.Key.DeprecatedFetchCompletions(line, cursor)
}
}
@ -129,7 +129,7 @@ func (v KeyValueAssignmentValue) getValueAtCursor(line string, cursor uint32) (s
relativePosition, found := utils.FindPreviousCharacter(line, v.Separator, int(cursor))
if found {
// Value found
// DeprecatedValue found
selected := valueSelected
return line[:uint32(relativePosition)], &selected, cursor - uint32(relativePosition)
}
@ -147,8 +147,8 @@ func (v KeyValueAssignmentValue) getValueAtCursor(line string, cursor uint32) (s
return line, &selected, cursor
}
func (v KeyValueAssignmentValue) FetchHoverInfo(line string, cursor uint32) []string {
if len(v.CheckIsValid(line)) != 0 {
func (v KeyValueAssignmentValue) DeprecatedFetchHoverInfo(line string, cursor uint32) []string {
if len(v.DeprecatedCheckIsValid(line)) != 0 {
return []string{}
}
@ -160,12 +160,12 @@ func (v KeyValueAssignmentValue) FetchHoverInfo(line string, cursor uint32) []st
if *selected == keySelected {
// Get key documentation
return v.Key.FetchHoverInfo(value, cursor)
return v.Key.DeprecatedFetchHoverInfo(value, cursor)
} else if *selected == valueSelected {
// Get for value documentation
key := strings.SplitN(line, v.Separator, 2)[0]
return v.getValue(key).FetchHoverInfo(value, cursor)
return v.getValue(key).DeprecatedFetchHoverInfo(value, cursor)
}
return []string{}

View File

@ -29,7 +29,7 @@ func (v MaskModeValue) GetTypeDescription() []string {
var maskModePattern = regexp.MustCompile("^[0-7]{4}$")
func (v MaskModeValue) CheckIsValid(value string) []*InvalidValue {
func (v MaskModeValue) DeprecatedCheckIsValid(value string) []*InvalidValue {
if !maskModePattern.MatchString(value) {
return []*InvalidValue{{
Err: MaskModeInvalidError{},
@ -41,7 +41,7 @@ func (v MaskModeValue) CheckIsValid(value string) []*InvalidValue {
return []*InvalidValue{}
}
func (v MaskModeValue) FetchCompletions(line string, cursor uint32) []protocol.CompletionItem {
func (v MaskModeValue) DeprecatedFetchCompletions(line string, cursor uint32) []protocol.CompletionItem {
kind := protocol.CompletionItemKindValue
perm0644 := "0644"
@ -147,7 +147,7 @@ func getMaskRepresentation(digit uint8) string {
return ""
}
func (v MaskModeValue) FetchHoverInfo(line string, cursor uint32) []string {
func (v MaskModeValue) DeprecatedFetchHoverInfo(line string, cursor uint32) []string {
if !maskModePattern.MatchString(line) {
return []string{}
}

View File

@ -48,7 +48,7 @@ func (v NumberValue) GetTypeDescription() []string {
return []string{"A number"}
}
func (v NumberValue) CheckIsValid(value string) []*InvalidValue {
func (v NumberValue) DeprecatedCheckIsValid(value string) []*InvalidValue {
number, err := strconv.Atoi(value)
if err != nil {
@ -73,10 +73,10 @@ func (v NumberValue) CheckIsValid(value string) []*InvalidValue {
return nil
}
func (v NumberValue) FetchCompletions(line string, cursor uint32) []protocol.CompletionItem {
func (v NumberValue) DeprecatedFetchCompletions(line string, cursor uint32) []protocol.CompletionItem {
return []protocol.CompletionItem{}
}
func (v NumberValue) FetchHoverInfo(line string, cursor uint32) []string {
func (v NumberValue) DeprecatedFetchHoverInfo(line string, cursor uint32) []string {
return []string{}
}

View File

@ -8,14 +8,14 @@ import (
)
type OrValue struct {
Values []Value
Values []DeprecatedValue
}
func (v OrValue) GetTypeDescription() []string {
lines := make([]string, 0)
for _, subValueRaw := range v.Values {
subValue := subValueRaw.(Value)
subValue := subValueRaw.(DeprecatedValue)
subLines := subValue.GetTypeDescription()
for index, line := range subLines {
@ -34,11 +34,11 @@ func (v OrValue) GetTypeDescription() []string {
lines...,
)
}
func (v OrValue) CheckIsValid(value string) []*InvalidValue {
func (v OrValue) DeprecatedCheckIsValid(value string) []*InvalidValue {
errors := make([]*InvalidValue, 0)
for _, subValue := range v.Values {
valueErrors := subValue.CheckIsValid(value)
valueErrors := subValue.DeprecatedCheckIsValid(value)
if len(valueErrors) == 0 {
return nil
@ -49,7 +49,7 @@ func (v OrValue) CheckIsValid(value string) []*InvalidValue {
return errors
}
func (v OrValue) FetchCompletions(line string, cursor uint32) []protocol.CompletionItem {
func (v OrValue) DeprecatedFetchCompletions(line string, cursor uint32) []protocol.CompletionItem {
// Check for special cases
if len(v.Values) == 2 {
switch v.Values[0].(type) {
@ -63,11 +63,11 @@ func (v OrValue) FetchCompletions(line string, cursor uint32) []protocol.Complet
_, found := utils.FindPreviousCharacter(
line,
keyEnumValue.Separator,
max(0, int(cursor-1)),
int(cursor),
)
if found {
return keyEnumValue.FetchCompletions(line, cursor)
return keyEnumValue.DeprecatedFetchCompletions(line, cursor)
}
}
}
@ -76,19 +76,19 @@ func (v OrValue) FetchCompletions(line string, cursor uint32) []protocol.Complet
completions := make([]protocol.CompletionItem, 0)
for _, subValue := range v.Values {
completions = append(completions, subValue.FetchCompletions(line, cursor)...)
completions = append(completions, subValue.DeprecatedFetchCompletions(line, cursor)...)
}
return completions
}
func (v OrValue) FetchHoverInfo(line string, cursor uint32) []string {
func (v OrValue) DeprecatedFetchHoverInfo(line string, cursor uint32) []string {
for _, subValue := range v.Values {
valueErrors := subValue.CheckIsValid(line)
valueErrors := subValue.DeprecatedCheckIsValid(line)
if len(valueErrors) == 0 {
// Found
return subValue.FetchHoverInfo(line, cursor)
return subValue.DeprecatedFetchHoverInfo(line, cursor)
}
}

View File

@ -46,7 +46,7 @@ func (v PathValue) GetTypeDescription() []string {
return []string{strings.Join(hints, ", ")}
}
func (v PathValue) CheckIsValid(value string) []*InvalidValue {
func (v PathValue) DeprecatedCheckIsValid(value string) []*InvalidValue {
if !utils.DoesPathExist(value) {
return []*InvalidValue{{
Err: PathDoesNotExistError{},
@ -78,10 +78,10 @@ func (v PathValue) CheckIsValid(value string) []*InvalidValue {
}
}
func (v PathValue) FetchCompletions(line string, cursor uint32) []protocol.CompletionItem {
func (v PathValue) DeprecatedFetchCompletions(line string, cursor uint32) []protocol.CompletionItem {
return []protocol.CompletionItem{}
}
func (v PathValue) FetchHoverInfo(line string, cursor uint32) []string {
func (v PathValue) DeprecatedFetchHoverInfo(line string, cursor uint32) []string {
return []string{}
}

View File

@ -34,7 +34,7 @@ func isPowerOfTwo(number int) bool {
return true
}
func (v PowerOfTwoValue) CheckIsValid(value string) []*InvalidValue {
func (v PowerOfTwoValue) DeprecatedCheckIsValid(value string) []*InvalidValue {
number, err := strconv.Atoi(value)
if err != nil {
@ -60,7 +60,7 @@ func (v PowerOfTwoValue) CheckIsValid(value string) []*InvalidValue {
var powers = []int{1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536}
func (v PowerOfTwoValue) FetchCompletions(line string, cursor uint32) []protocol.CompletionItem {
func (v PowerOfTwoValue) DeprecatedFetchCompletions(line string, cursor uint32) []protocol.CompletionItem {
textFormat := protocol.InsertTextFormatPlainText
kind := protocol.CompletionItemKindValue
@ -76,6 +76,6 @@ func (v PowerOfTwoValue) FetchCompletions(line string, cursor uint32) []protocol
)
}
func (v PowerOfTwoValue) FetchHoverInfo(line string, cursor uint32) []string {
func (v PowerOfTwoValue) DeprecatedFetchHoverInfo(line string, cursor uint32) []string {
return []string{}
}

View File

@ -0,0 +1,85 @@
package docvalues
import (
"config-lsp/utils"
"fmt"
"strings"
protocol "github.com/tliron/glsp/protocol_3_16"
)
type Prefix struct {
Prefix string
Meaning string
}
type PrefixWithMeaningValue struct {
Prefixes []Prefix
SubValue DeprecatedValue
}
func (v PrefixWithMeaningValue) GetTypeDescription() []string {
subDescription := v.SubValue.GetTypeDescription()
prefixDescription := utils.Map(v.Prefixes, func(prefix Prefix) string {
return fmt.Sprintf("_%s_ -> %s", prefix.Prefix, prefix.Meaning)
})
return append(subDescription,
append(
[]string{"The following prefixes are allowed:"},
prefixDescription...,
)...,
)
}
func (v PrefixWithMeaningValue) DeprecatedCheckIsValid(value string) []*InvalidValue {
for _, prefix := range v.Prefixes {
if strings.HasPrefix(value, prefix.Prefix) {
return v.SubValue.DeprecatedCheckIsValid(value[len(prefix.Prefix):])
}
}
return v.SubValue.DeprecatedCheckIsValid(value)
}
func (v PrefixWithMeaningValue) DeprecatedFetchCompletions(line string, cursor uint32) []protocol.CompletionItem {
textFormat := protocol.InsertTextFormatPlainText
kind := protocol.CompletionItemKindText
// 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.DeprecatedFetchCompletions(line, cursor)...)
}
func (v PrefixWithMeaningValue) DeprecatedFetchHoverInfo(line string, cursor uint32) []string {
for _, prefix := range v.Prefixes {
if strings.HasPrefix(line, prefix.Prefix) {
return append([]string{
fmt.Sprintf("Prefix: _%s_ -> %s", prefix.Prefix, prefix.Meaning),
},
v.SubValue.DeprecatedFetchHoverInfo(line[1:], cursor)...,
)
}
}
return v.SubValue.DeprecatedFetchHoverInfo(line[1:], cursor)
}

View File

@ -25,7 +25,7 @@ func (v RegexValue) GetTypeDescription() []string {
}
}
func (v RegexValue) CheckIsValid(value string) []*InvalidValue {
func (v RegexValue) DeprecatedCheckIsValid(value string) []*InvalidValue {
if !v.Regex.MatchString(value) {
return []*InvalidValue{{
Err: RegexInvalidError{Regex: v.Regex.String()},
@ -37,11 +37,11 @@ func (v RegexValue) CheckIsValid(value string) []*InvalidValue {
return []*InvalidValue{}
}
func (v RegexValue) FetchCompletions(line string, cursor uint32) []protocol.CompletionItem {
func (v RegexValue) DeprecatedFetchCompletions(line string, cursor uint32) []protocol.CompletionItem {
return []protocol.CompletionItem{}
}
func (v RegexValue) FetchHoverInfo(line string, cursor uint32) []string {
func (v RegexValue) DeprecatedFetchHoverInfo(line string, cursor uint32) []string {
return []string{
fmt.Sprintf("Pattern: `%s`", v.Regex.String()),
}

View File

@ -24,7 +24,7 @@ func (v StringValue) GetTypeDescription() []string {
return []string{"String"}
}
func (v StringValue) CheckIsValid(value string) []*InvalidValue {
func (v StringValue) DeprecatedCheckIsValid(value string) []*InvalidValue {
if value == "" {
return []*InvalidValue{{
Err: EmptyStringError{},
@ -45,10 +45,10 @@ func (v StringValue) CheckIsValid(value string) []*InvalidValue {
return nil
}
func (v StringValue) FetchCompletions(line string, cursor uint32) []protocol.CompletionItem {
func (v StringValue) DeprecatedFetchCompletions(line string, cursor uint32) []protocol.CompletionItem {
return []protocol.CompletionItem{}
}
func (v StringValue) FetchHoverInfo(line string, cursor uint32) []string {
func (v StringValue) DeprecatedFetchHoverInfo(line string, cursor uint32) []string {
return []string{}
}

View File

@ -15,7 +15,7 @@ type Suffix struct {
type SuffixWithMeaningValue struct {
Suffixes []Suffix
SubValue Value
SubValue DeprecatedValue
}
func (v SuffixWithMeaningValue) GetTypeDescription() []string {
@ -33,17 +33,17 @@ func (v SuffixWithMeaningValue) GetTypeDescription() []string {
)
}
func (v SuffixWithMeaningValue) CheckIsValid(value string) []*InvalidValue {
func (v SuffixWithMeaningValue) DeprecatedCheckIsValid(value string) []*InvalidValue {
for _, suffix := range v.Suffixes {
if strings.HasSuffix(value, suffix.Suffix) {
return v.SubValue.CheckIsValid(value[:len(value)-len(suffix.Suffix)])
return v.SubValue.DeprecatedCheckIsValid(value[:len(value)-len(suffix.Suffix)])
}
}
return v.SubValue.CheckIsValid(value)
return v.SubValue.DeprecatedCheckIsValid(value)
}
func (v SuffixWithMeaningValue) FetchCompletions(line string, cursor uint32) []protocol.CompletionItem {
func (v SuffixWithMeaningValue) DeprecatedFetchCompletions(line string, cursor uint32) []protocol.CompletionItem {
textFormat := protocol.InsertTextFormatPlainText
kind := protocol.CompletionItemKindText
@ -56,19 +56,19 @@ func (v SuffixWithMeaningValue) FetchCompletions(line string, cursor uint32) []p
}
})
return append(suffixCompletions, v.SubValue.FetchCompletions(line, cursor)...)
return append(suffixCompletions, v.SubValue.DeprecatedFetchCompletions(line, cursor)...)
}
func (v SuffixWithMeaningValue) FetchHoverInfo(line string, cursor uint32) []string {
func (v SuffixWithMeaningValue) DeprecatedFetchHoverInfo(line string, cursor uint32) []string {
for _, suffix := range v.Suffixes {
if strings.HasSuffix(line, suffix.Suffix) {
return append([]string{
fmt.Sprintf("Suffix: _%s_ -> %s", suffix.Suffix, suffix.Meaning),
},
v.SubValue.FetchHoverInfo(line[:len(line)-len(suffix.Suffix)], cursor)...,
v.SubValue.DeprecatedFetchHoverInfo(line[:len(line)-len(suffix.Suffix)], cursor)...,
)
}
}
return v.SubValue.FetchHoverInfo(line, cursor)
return v.SubValue.DeprecatedFetchHoverInfo(line, cursor)
}

View File

@ -1,7 +1,6 @@
package openssh
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) DeprecatedCheckIsValid(value string) []*InvalidValue {
if !timeFormatCheckPattern.MatchString(value) {
return []*docvalues.InvalidValue{
return []*InvalidValue{
{
Err: InvalidTimeFormatError{},
Start: 0,
@ -56,7 +56,7 @@ func calculateInSeconds(value int, unit string) int {
}
}
func (v TimeFormatValue) FetchCompletions(line string, cursor uint32) []protocol.CompletionItem {
func (v TimeFormatValue) DeprecatedFetchCompletions(line string, cursor uint32) []protocol.CompletionItem {
completions := make([]protocol.CompletionItem, 0)
if line != "" && !timeFormatCompletionsPattern.MatchString(line) {
@ -99,13 +99,13 @@ func (v TimeFormatValue) FetchCompletions(line string, cursor uint32) []protocol
if line == "" || isJustDigitsPattern.MatchString(line) {
completions = append(
completions,
docvalues.GenerateBase10Completions(line)...,
GenerateBase10Completions(line)...,
)
}
return completions
}
func (v TimeFormatValue) FetchHoverInfo(line string, cursor uint32) []string {
func (v TimeFormatValue) DeprecatedFetchHoverInfo(line string, cursor uint32) []string {
return []string{}
}

View File

@ -35,7 +35,7 @@ func (v UIDValue) GetTypeDescription() []string {
return []string{"User ID"}
}
func (v UIDValue) CheckIsValid(value string) []*InvalidValue {
func (v UIDValue) DeprecatedCheckIsValid(value string) []*InvalidValue {
uid, err := strconv.Atoi(value)
if err != nil {
@ -90,7 +90,7 @@ var defaultUIDsExplanation = []EnumString{
},
}
func (v UIDValue) FetchCompletions(line string, cursor uint32) []protocol.CompletionItem {
func (v UIDValue) DeprecatedFetchCompletions(line string, cursor uint32) []protocol.CompletionItem {
infos, err := common.FetchPasswdInfo()
if err != nil {
@ -129,7 +129,7 @@ func (v UIDValue) FetchCompletions(line string, cursor uint32) []protocol.Comple
return completions
}
func (v UIDValue) FetchHoverInfo(line string, cursor uint32) []string {
func (v UIDValue) DeprecatedFetchHoverInfo(line string, cursor uint32) []string {
uid, err := strconv.Atoi(line)
if err != nil {

View File

@ -28,7 +28,7 @@ func (v UmaskValue) GetTypeDescription() []string {
var umaskPattern = regexp.MustCompile("^[0-7]{4}$")
func (v UmaskValue) CheckIsValid(value string) []*InvalidValue {
func (v UmaskValue) DeprecatedCheckIsValid(value string) []*InvalidValue {
if !umaskPattern.MatchString(value) {
return []*InvalidValue{{
Err: UmaskInvalidError{},
@ -40,7 +40,7 @@ func (v UmaskValue) CheckIsValid(value string) []*InvalidValue {
return []*InvalidValue{}
}
func (v UmaskValue) FetchCompletions(line string, cursor uint32) []protocol.CompletionItem {
func (v UmaskValue) DeprecatedFetchCompletions(line string, cursor uint32) []protocol.CompletionItem {
kind := protocol.CompletionItemKindValue
return []protocol.CompletionItem{
@ -111,6 +111,6 @@ func (v UmaskValue) FetchCompletions(line string, cursor uint32) []protocol.Comp
}
}
func (v UmaskValue) FetchHoverInfo(line string, cursor uint32) []string {
func (v UmaskValue) DeprecatedFetchHoverInfo(line string, cursor uint32) []string {
return []string{}
}

View File

@ -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

View File

@ -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=

Some files were not shown because too many files have changed in this diff Show More