merge main

This commit is contained in:
Myzel394 2024-11-29 21:29:31 +01:00
commit 592e5b9172
No known key found for this signature in database
GPG Key ID: ED20A1D1D423AF3F
120 changed files with 3151 additions and 843 deletions

135
.github/workflows/release.yaml vendored Normal file
View File

@ -0,0 +1,135 @@
name: build and release
permissions:
contents: write
on:
release:
types: [ published ]
jobs:
build-server:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Check git version matches flake version
shell: bash
run: |
if ! [ $(echo '${{ github.ref }}' | cut -d'v' -f 2) = $(grep '# CI:CD-VERSION$' flake.nix | cut -d'"' -f 2) ];
then
echo "Version mismatch between Git and flake"
exit 1
fi
- name: Check version in code matches flake version
shell: bash
run: |
if ! [ $(grep '// CI:CD-VERSION$' server/root-handler/common.go | cut -d'"' -f 2) = $(grep '# CI:CD-VERSION$' flake.nix | cut -d'"' -f 2) ];
then
echo "Version mismatch between code and flake"
exit 1
fi
- name: Check vs code package.json version matches flake version
shell: bash
run: |
if ! [ $(grep '"version": "' vs-code-extension/package.json | cut -d'"' -f 4) = $(grep '# CI:CD-VERSION$' flake.nix | cut -d'"' -f 2) ];
then
echo "Version mismatch between vs code package.json and flake"
exit 1
fi
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: stable
- name: Run GoReleaser
uses: goreleaser/goreleaser-action@v6
with:
distribution: goreleaser
version: "~> v2"
args: release --clean
env:
GITHUB_TOKEN: ${{ secrets.GH_CONFIGLSP_TOKEN }}
build-extension:
name: Build extension for ${{ matrix.target }}
runs-on: ubuntu-latest
needs:
# Wait for server to build so that we know the checks have passed
- build-server
strategy:
fail-fast: false
matrix:
include:
- goos: linux
goarch: amd64
vscode_target: linux-x64
- goos: linux
goarch: arm64
vscode_target: linux-arm64
- goos: darwin
goarch: amd64
vscode_target: darwin-x64
- goos: darwin
goarch: arm64
vscode_target: darwin-arm64
- goos: windows
goarch: amd64
vscode_target: win32-x64
- goos: windows
goarch: arm64
vscode_target: win32-arm64
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: cachix/install-nix-action@v27
with:
github_access_token: ${{ secrets.GITHUB_TOKEN }}
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: stable
- name: Create bare extension
run: nix build .#"vs-code-extension-bare"
- name: Build extension
run: cd server && GOOS=${{ matrix.goos }} GOARCH=${{ matrix.goarch }} go build -a -gcflags=all="-l -B" -ldflags="-s -w" -o config-lsp
- name: Prepare folder
run: cp -rL result dist && chmod -R 777 dist
- name: Move binary to extension
run: mv server/config-lsp dist/out/
- name: Shrink binary
if: ${{ matrix.goos == 'linux' }}
run: nix develop .#"vs-code-extension" --command bash -c "upx dist/out/config-lsp"
- name: Package extension
run: nix develop .#"vs-code-extension" --command bash -c "cd dist && vsce package --target ${{ matrix.vscode_target }}"
- name: Move vsix to root
run: mv dist/*.vsix .
- uses: softprops/action-gh-release@v2
with:
files: '*.vsix'
- name: Upload extension to VS Code Marketplace
run: nix develop .#"vs-code-extension" --command bash -c "vsce publish --packagePath *.vsix -p ${{ secrets.VSCE_PAT }}"

2
.gitignore vendored
View File

@ -29,3 +29,5 @@ config-lsp
result
bin
debug.log
dist/

57
.goreleaser.yaml Normal file
View File

@ -0,0 +1,57 @@
# This is an example .goreleaser.yml file with some sensible defaults.
# Make sure to check the documentation at https://goreleaser.com
# The lines below are called `modelines`. See `:help modeline`
# Feel free to remove those if you don't want/need to use them.
# yaml-language-server: $schema=https://goreleaser.com/static/schema.json
# vim: set ts=2 sw=2 tw=0 fo=cnqoj
version: 2
project_name: config-lsp
builds:
- env:
- CGO_ENABLED=0
goos:
- linux
- windows
- darwin
dir: ./server
archives:
- format: tar.gz
# this name template makes the OS and Arch compatible with the results of `uname`.
name_template: >-
{{ .ProjectName }}_
{{- title .Os }}_
{{- if eq .Arch "amd64" }}x86_64
{{- else if eq .Arch "386" }}i386
{{- else }}{{ .Arch }}{{ end }}
{{- if .Arm }}v{{ .Arm }}{{ end }}
# use zip for windows archives
format_overrides:
- goos: windows
format: zip
changelog:
sort: asc
filters:
exclude:
- "^docs:"
- "^test:"
brews:
- name: config-lsp
homepage: "https://github.com/Myzel394/config-lsp"
description: "Finally a LSP for your config files: gitconfig, fstab, aliases, hosts, wireguard, ssh_config, sshd_config, and more to come!"
url_template: "https://github.com/Myzel394/config-lsp/releases/download/{{ .Tag }}/{{ .ArtifactName }}"
repository:
owner: Myzel394
name: homebrew-formulae
branch: main
commit_author:
name: goreleaserbot
email: bot@goreleaser.com
commit_msg_template: "Brew formula update for {{ .ProjectName }} version {{ .Tag }}"
directory: Formula

0
LICENSE.md Normal file
View File

101
README.md
View File

@ -1,12 +1,17 @@
# config-lsp
A language server for configuration files. The goal is to make editing config files modern and easy.
## Supported Features
| | diagnostics | `completion` | `hover` | `code-action` | `definition` | `rename` | `signature-help` |
|-------------|-------------|--------------|---------|---------------|--------------|----------|------------------|
| aliases | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| fstab | ✅ | ✅ | ✅ | ❓ | ❓ | ❓ | 🟡 |
| hosts | ✅ | ✅ | ✅ | ✅ | ❓ | ❓ | 🟡 |
| sshd_config | ✅ | ✅ | ✅ | ❓ | ✅ | ❓ | 🟡 |
| wireguard | ✅ | ✅ | ✅ | ✅ | ❓ | ❓ | 🟡 |
| aliases | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| fstab | ✅ | ✅ | ✅ | ❓ | ❓ | ❓ | 🟡 |
| hosts | ✅ | ✅ | ✅ | ✅ | ❓ | ❓ | ✅ |
| ssh_config | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| sshd_config | ✅ | ✅ | ✅ | ❓ | ✅ | ❓ | ✅ |
| wireguard | ✅ | ✅ | ✅ | ✅ | ❓ | ❓ | 🟡 |
✅ = Supported
@ -14,3 +19,89 @@
❓ = No idea what to implement here, please let me know if you have any ideas
## What further configs will be supported?
As config-lsp is a hobby project and I'm working completely alone on it,
I will first focus on widely used and well known config files.
You are welcome to request any config file, as far as it's fairly well known.
## Installation
### VS Code Extension
[Install the extension from the marketplace](https://marketplace.visualstudio.com/items?itemName=myzel394.config-lsp)
Alternatively, you can also manually install the extension:
1. Download the latest extension version from the [release page](https://github.com/Myzel394/config-lsp/releases) - You can find the extension under the "assets" section. The filename ends with `.vsix`
2. Open VS Code
3. Open the extensions sidebar
4. In the top bar, click on the three dots and select "Install from VSIX..."
5. Select the just downloaded `.vsix` file
6. You may need to restart VS Code
7. Enjoy!
### Manual installation
To use `config-lsp` in any other editor, you'll need to install it manually.
Don't worry, it's easy!
#### Installing the latest Binary
##### Brew
```sh
brew install myzel394/formulae/config-lsp
```
##### Manual Binary
Download the latest binary from the [releases page](https://github.com/Myzel394/config-lsp/releases) and put it in your PATH.
##### Compiling
You can either compile the binary using go:
```sh
go build -o config-lsp
```
or build it using Nix:
```sh
nix flake build
```
#### Neovim installation
Using [nvim-lspconfig](https://github.com/neovim/nvim-lspconfig) you can add `config-lsp` by adding the following to your `lsp.lua` (filename might differ):
```lua
if not configs.config_lsp then
configs.config_lsp = {
default_config = {
cmd = { 'config-lsp' },
filetypes = {
"sshconfig",
"sshdconfig",
"fstab",
"aliases",
-- Matches wireguard configs and /etc/hosts
"conf",
},
root_dir = vim.loop.cwd,
},
}
end
lspconfig.config_lsp.setup {}
`````
## Supporting config-lsp
You can either contribute to the project, [see CONTRIBUTING.md](CONTRIBUTING.md), or you can sponsor me via [GitHub Sponsors](https://github.com/sponsors/Myzel394) or via [crypto currencies](https://github.com/Myzel394/contact-me?tab=readme-ov-file#donations).
Oh and spreading the word about config-lsp is also a great way to support the project :)

18
flake.lock generated
View File

@ -26,11 +26,11 @@
]
},
"locked": {
"lastModified": 1722589758,
"narHash": "sha256-sbbA8b6Q2vB/t/r1znHawoXLysCyD4L/6n6/RykiSnA=",
"lastModified": 1728509152,
"narHash": "sha256-tQo1rg3TlwgyI8eHnLvZSlQx9d/o2Rb4oF16TfaTOw0=",
"owner": "tweag",
"repo": "gomod2nix",
"rev": "4e08ca09253ef996bd4c03afa383b23e35fe28a1",
"rev": "d5547e530464c562324f171006fc8f639aa01c9f",
"type": "github"
},
"original": {
@ -41,11 +41,11 @@
},
"nixpkgs": {
"locked": {
"lastModified": 1723637854,
"narHash": "sha256-med8+5DSWa2UnOqtdICndjDAEjxr5D7zaIiK4pn0Q7c=",
"lastModified": 1728888510,
"narHash": "sha256-nsNdSldaAyu6PE3YUA+YQLqUDJh+gRbBooMMekZJwvI=",
"owner": "nixos",
"repo": "nixpkgs",
"rev": "c3aa7b8938b17aebd2deecf7be0636000d62a2b9",
"rev": "a3c0b3b21515f74fd2665903d4ce6bc4dc81c77c",
"type": "github"
},
"original": {
@ -97,11 +97,11 @@
"systems": "systems_2"
},
"locked": {
"lastModified": 1710146030,
"narHash": "sha256-SZ5L6eA7HJ/nmkzGG7/ISclqe6oZdOZTNoesiInkXPQ=",
"lastModified": 1726560853,
"narHash": "sha256-X6rJYSESBVr3hBoH0WbKE5KvhPU5bloyZ2L4K60/fPQ=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "b1d9ab70662946ef0850d488da1c9019f3a9752a",
"rev": "c1dfcf08411b08f6b8615f7d8971a2bfa81d5e8a",
"type": "github"
},
"original": {

View File

@ -12,8 +12,18 @@
};
outputs = { self, nixpkgs, utils, gomod2nix }:
utils.lib.eachDefaultSystem (system:
utils.lib.eachSystem [
"x86_64-linux"
"aarch64-linux"
"x86_64-darwin"
"aarch64-darwin"
"x86_64-windows"
"aarch64-windows"
] (system:
let
version = "0.1.2"; # CI:CD-VERSION
pkgs = import nixpkgs {
inherit system;
overlays = [
@ -27,21 +37,39 @@
inputs = [
pkgs.go_1_22
];
server = pkgs.buildGoModule {
serverUncompressed = pkgs.buildGoModule {
nativeBuildInputs = inputs;
pname = "github.com/Myzel394/config-lsp";
version = "v0.0.1";
version = version;
src = ./server;
vendorHash = "sha256-s+sjOVvqU20+mbEFKg+RCD+dhScqSatk9eseX2IioPI";
vendorHash = "sha256-eO1eY+2XuOCd/dKwgFtu05+bnn/Cv8ZbUIwRjCwJF+U=";
ldflags = [ "-s" "-w" ];
checkPhase = ''
go test -v $(pwd)/...
'';
};
server = pkgs.stdenv.mkDerivation {
name = "config-lsp-${version}";
src = serverUncompressed;
buildInputs = [
pkgs.upx
];
buildPhase = ''
mkdir -p $out/bin
cp $src/bin/config-lsp $out/bin/
chmod +rw $out/bin/config-lsp
# upx is currently not supported for darwin
if [ "${system}" != "x86_64-darwin" ] && [ "${system}" != "aarch64-darwin" ]; then
upx --ultra-brute $out/bin/config-lsp
fi
'';
};
in {
packages = {
default = server;
"vs-code-extension" = let
name = "config-lsp-vs-code-extension";
"vs-code-extension-bare" = let
name = "config-lsp";
node-modules = pkgs.mkYarnPackage {
src = ./vs-code-extension;
name = name;
@ -50,13 +78,56 @@
yarnNix = ./vs-code-extension/yarn.nix;
buildPhase = ''
yarn --offline run compile
yarn --offline run compile:prod
'';
installPhase = ''
mv deps/${name}/out $out
cp ${server}/bin/config-lsp $out/
mkdir -p extension
# No idea why this is being created
rm deps/${name}/config-lsp
cp -rL deps/${name}/. extension
mkdir -p $out
cp -r extension/. $out
'';
distPhase = "true";
buildInputs = [
pkgs.vsce
];
};
in node-modules;
"vs-code-extension" = let
name = "config-lsp";
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:prod
'';
installPhase = ''
mkdir -p extension
# No idea why this is being created
rm deps/${name}/config-lsp
cp -rL deps/${name}/. extension
cp ${server}/bin/config-lsp extension/out/config-lsp
cd extension && ${pkgs.vsce}/bin/vsce package
mkdir -p $out
cp *.vsix $out
'';
distPhase = "true";
buildInputs = [
pkgs.vsce
];
};
in node-modules;
};
@ -72,6 +143,8 @@
devShells."vs-code-extension" = pkgs.mkShell {
buildInputs = [
pkgs.nodejs
pkgs.vsce
pkgs.yarn2nix
];
};
}

View File

@ -0,0 +1,22 @@
package commondocumentation
import docvalues "config-lsp/doc-values"
var VboxsfDocumentationAssignable = docvalues.MergeKeyEnumAssignmentMaps(FatDocumentationAssignable, map[docvalues.EnumString]docvalues.DeprecatedValue{
docvalues.CreateEnumStringWithDoc(
"iocharset",
"This option sets the character set used for I/O operations. Note that on Linux guests, if the iocharset option is not specified, then the Guest Additions driver will attempt to use the character set specified by the CONFIG_NLS_DEFAULT kernel option. If this option is not set either, then UTF-8 is used.",
): docvalues.EnumValue{
EnforceValues: true,
Values: AvailableCharsets,
},
docvalues.CreateEnumStringWithDoc(
"convertcp",
"This option specifies the character set used for the shared folder name. This is UTF-8 by default.",
): docvalues.EnumValue{
EnforceValues: true,
Values: AvailableCharsets,
},
})
var VboxsfDocumentationEnums = []docvalues.EnumString{}

View File

@ -3,6 +3,7 @@ package docvalues
import (
"config-lsp/utils"
"fmt"
"regexp"
"strings"
protocol "github.com/tliron/glsp/protocol_3_16"
@ -42,6 +43,9 @@ type ArrayValue struct {
// This is used to extract the value from the user input,
// because you may want to preprocess the value before checking for duplicates
DuplicatesExtractor *(func(string) string)
// If true, array ArrayValue ignores the `Separator` if it's within quotes
RespectQuotes bool
}
func (v ArrayValue) GetTypeDescription() []string {
@ -53,9 +57,18 @@ func (v ArrayValue) GetTypeDescription() []string {
)
}
// TODO: Add support for quotes
func (v ArrayValue) DeprecatedCheckIsValid(value string) []*InvalidValue {
errors := []*InvalidValue{}
values := strings.Split(value, v.Separator)
var values []string
if v.RespectQuotes {
splitPattern := *regexp.MustCompile(fmt.Sprintf(`".+?"|[^%s]+`, v.Separator))
values = splitPattern.FindAllString(value, -1)
} else {
values = strings.Split(value, v.Separator)
}
if *v.DuplicatesExtractor != nil {
valuesOccurrences := utils.SliceToMap(
@ -122,9 +135,27 @@ func (v ArrayValue) getCurrentValue(line string, cursor uint32) (string, uint32)
MIN := uint32(0)
MAX := uint32(len(line) - 1)
var cursorSearchStart = cursor
var cursorSearchEnd = cursor
var start uint32
var end uint32
// Hello,world,how,are,you
// Hello,"world,how",are,you
if v.RespectQuotes {
quotes := utils.GetQuoteRanges(line)
if len(quotes) > 0 {
quote := quotes.GetQuoteForIndex(int(cursor))
if quote != nil {
cursorSearchStart = uint32(quote[0])
cursorSearchEnd = uint32(quote[1])
}
}
}
// hello,w[o]rld,and,more
// [h]ello,world
// hello,[w]orld
@ -135,7 +166,7 @@ func (v ArrayValue) getCurrentValue(line string, cursor uint32) (string, uint32)
relativePosition, found := utils.FindPreviousCharacter(
line,
v.Separator,
int(cursor),
int(cursorSearchStart),
)
if found {
@ -151,7 +182,7 @@ func (v ArrayValue) getCurrentValue(line string, cursor uint32) (string, uint32)
relativePosition, found = utils.FindNextCharacter(
line,
v.Separator,
int(start),
int(cursorSearchEnd),
)
if found {

View File

@ -5,17 +5,18 @@ go 1.22.5
require (
github.com/antlr4-go/antlr/v4 v4.13.1
github.com/emirpasic/gods v1.18.1
github.com/google/go-cmp v0.6.0
github.com/k0kubun/pp v3.0.1+incompatible
github.com/tliron/commonlog v0.2.17
github.com/tliron/glsp v0.2.2
golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56
github.com/google/go-cmp v0.6.0
)
require (
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // 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
github.com/k0kubun/colorstring v0.0.0-20150214042306-9440f1994b88 // indirect
github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect

View File

@ -13,6 +13,8 @@ github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aN
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI=
github.com/iancoleman/strcase v0.3.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho=
github.com/k0kubun/colorstring v0.0.0-20150214042306-9440f1994b88 h1:uC1QfSlInpQF+M0ao65imhwqKnz3Q2z/d8PWZRMQvDM=
github.com/k0kubun/colorstring v0.0.0-20150214042306-9440f1994b88/go.mod h1:3w7q1U84EfirKl04SVQ/s7nPm1ZPhiXd34z40TNz36k=
github.com/k0kubun/pp v3.0.1+incompatible h1:3tqvf7QgUnZ5tXO6pNAZlrvHgl6DvifjDrd9g2S9Z40=
github.com/k0kubun/pp v3.0.1+incompatible/go.mod h1:GWse8YhT0p8pT4ir3ZgBbfZild3tgzSScAn6HmfYukg=
github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=

View File

@ -66,14 +66,14 @@ func GetCompletionsForEntry(
return completions, nil
}
switch (*value).(type) {
switch value.(type) {
case ast.AliasValueUser:
return getUserCompletions(
i,
excludedUsers,
), nil
case ast.AliasValueError:
errorValue := (*value).(ast.AliasValueError)
errorValue := value.(ast.AliasValueError)
isAtErrorCode := errorValue.Code == nil &&
errorValue.Location.IsPositionAfterStart(cursor) &&

View File

@ -9,7 +9,7 @@ import (
func GetValueAtPosition(
position common.Position,
entry *ast.AliasEntry,
) *ast.AliasValueInterface {
) ast.AliasValueInterface {
if entry.Values == nil || len(entry.Values.Values) == 0 {
return nil
}
@ -36,5 +36,5 @@ func GetValueAtPosition(
return nil
}
return &entry.Values.Values[index]
return entry.Values.Values[index]
}

View File

@ -28,8 +28,8 @@ func GetRootSignatureHelp(
},
{
Label: []uint32{
uint32(len("<alias>:")),
uint32(len("<alias>:") + len("<value1>")),
uint32(len("<alias>: ")),
uint32(len("<alias>: ") + len("<value1>")),
},
Documentation: "A value to associate with the alias",
},

View File

@ -28,11 +28,7 @@ func TextDocumentCompletion(context *glsp.Context, params *protocol.CompletionPa
entry := rawEntry.(*ast.AliasEntry)
if entry.Key == nil {
return handlers.GetAliasesCompletions(d.Indexes), nil
}
if entry.Key.Location.ContainsPosition(cursor) {
if entry.Key == nil || entry.Key.Location.ContainsPosition(cursor) {
return handlers.GetAliasesCompletions(d.Indexes), nil
}
@ -40,13 +36,9 @@ func TextDocumentCompletion(context *glsp.Context, params *protocol.CompletionPa
return nil, nil
}
if entry.Separator.IsPositionBeforeEnd(cursor) {
return handlers.GetCompletionsForEntry(
cursor,
entry,
d.Indexes,
)
}
return nil, nil
return handlers.GetCompletionsForEntry(
cursor,
entry,
d.Indexes,
)
}

View File

@ -32,7 +32,7 @@ func TextDocumentDefinition(context *glsp.Context, params *protocol.DefinitionPa
return handlers.GetDefinitionLocationForValue(
*d.Indexes,
*rawValue,
rawValue,
params.TextDocument.URI,
), nil
}

View File

@ -49,10 +49,10 @@ func TextDocumentHover(
}
contents := []string{}
contents = append(contents, handlers.GetAliasValueTypeInfo(*value)...)
contents = append(contents, handlers.GetAliasValueTypeInfo(value)...)
contents = append(contents, "")
contents = append(contents, "#### Value")
contents = append(contents, handlers.GetAliasValueHoverInfo(*document.Indexes, *value))
contents = append(contents, handlers.GetAliasValueHoverInfo(*document.Indexes, value))
text := strings.Join(contents, "\n")

View File

@ -34,9 +34,9 @@ func TextDocumentPrepareRename(context *glsp.Context, params *protocol.PrepareRe
return nil, nil
}
switch (*rawValue).(type) {
switch rawValue.(type) {
case ast.AliasValueUser:
userValue := (*rawValue).(ast.AliasValueUser)
userValue := rawValue.(ast.AliasValueUser)
return userValue.Location.ToLSPRange(), nil
}

View File

@ -44,9 +44,9 @@ func TextDocumentRename(context *glsp.Context, params *protocol.RenameParams) (*
return nil, nil
}
switch (*rawValue).(type) {
switch rawValue.(type) {
case ast.AliasValueUser:
userValue := (*rawValue).(ast.AliasValueUser)
userValue := rawValue.(ast.AliasValueUser)
changes := handlers.RenameAlias(
*d.Indexes,

View File

@ -14,7 +14,7 @@ func TextDocumentSignatureHelp(context *glsp.Context, params *protocol.Signature
document := aliases.DocumentParserMap[params.TextDocument.URI]
line := params.Position.Line
cursor := common.LSPCharacterAsCursorPosition(common.CursorToCharacterIndex(params.Position.Character))
cursor := common.LSPCharacterAsCursorPosition(params.Position.Character)
if _, found := document.Parser.CommentLines[line]; found {
// Comment
@ -36,17 +36,15 @@ func TextDocumentSignatureHelp(context *glsp.Context, params *protocol.Signature
if entry.Values != nil && entry.Values.Location.ContainsPosition(cursor) {
value := handlers.GetValueAtPosition(cursor, entry)
if value == nil {
if value == nil || value.GetAliasValue().Value == "" {
// For some reason, this does not really work,
// When we return all, and then a user value is entered
// and the `GetValueSignatureHelp` is called, still the old
// signatures with all signature are shown
// return handlers.GetAllValuesSignatureHelp(), nil
return nil, nil
return handlers.GetAllValuesSignatureHelp(), nil
}
return handlers.GetValueSignatureHelp(cursor, *value), nil
return handlers.GetValueSignatureHelp(cursor, value), nil
}
return nil, nil

View File

@ -20,9 +20,7 @@ mountPoint
;
fileSystem
: ADFS | AFFS | BTRFS | EXFAT
// Still match unknown file systems
| STRING | QUOTED_STRING
: STRING | QUOTED_STRING
;
mountOptions
@ -57,20 +55,3 @@ QUOTED_STRING
: '"' WHITESPACE? (STRING WHITESPACE)* STRING? ('"')?
;
// ///// Supported file systems /////
ADFS
: ('A' | 'a') ('D' | 'd') ('F' | 'f') ('S' | 's')
;
AFFS
: ('A' | 'a') ('F' | 'f') ('F' | 'f') ('S' | 's')
;
BTRFS
: ('B' | 'b') ('T' | 't') ('R' | 'r') ('F' | 'f') ('S' | 's')
;
EXFAT
: ('E' | 'e') ('X' | 'x') ('F' | 'f') ('A' | 'a') ('T' | 't')
;

View File

@ -14,17 +14,23 @@ type analyzerContext struct {
func Analyze(
document *shared.FstabDocument,
) []protocol.Diagnostic {
ctx := analyzerContext{
ctx := &analyzerContext{
document: document,
}
analyzeFieldAreFilled(&ctx)
analyzeFieldAreFilled(ctx)
if len(ctx.diagnostics) > 0 {
return ctx.diagnostics
}
analyzeValuesAreValid(&ctx)
analyzeValuesAreValid(ctx)
if len(ctx.diagnostics) > 0 {
return ctx.diagnostics
}
analyzeFSCKField(ctx)
return ctx.diagnostics
}

View File

@ -0,0 +1,49 @@
package analyzer
import (
"config-lsp/common"
"config-lsp/handlers/fstab/ast"
"config-lsp/handlers/fstab/fields"
"fmt"
"strings"
protocol "github.com/tliron/glsp/protocol_3_16"
)
func analyzeFSCKField(ctx *analyzerContext) {
it := ctx.document.Config.Entries.Iterator()
var rootEntry *ast.FstabEntry
for it.Next() {
entry := it.Value().(*ast.FstabEntry)
if entry.Fields != nil && entry.Fields.Fsck != nil && entry.Fields.Fsck.Value.Value == "1" {
fileSystem := strings.ToLower(entry.Fields.FilesystemType.Value.Value)
if _, found := fields.FsckOneDisabledFilesystems[fileSystem]; found {
// From https://wiki.archlinux.org/title/Fstab
ctx.diagnostics = append(ctx.diagnostics, protocol.Diagnostic{
Range: entry.Fields.Fsck.ToLSPRange(),
Message: "If the root file system is btrfs or XFS, the fsck order should be set to 0 instead of 1. See fsck.btrfs(8) and fsck.xfs(8).",
Severity: &common.SeverityWarning,
})
continue
}
if entry.Fields.Fsck.Value.Value == "1" {
if rootEntry != nil {
ctx.diagnostics = append(ctx.diagnostics, protocol.Diagnostic{
Range: entry.Fields.Fsck.ToLSPRange(),
Message: fmt.Sprintf("Only the root file system should have a fsck of 1. Other file systems should have a fsck of 2 or 0. The root file system is already using a fsck=1 on line %d", rootEntry.Fields.Start.Line),
Severity: &common.SeverityWarning,
})
} else {
rootEntry = entry
}
}
}
}
}

View File

@ -0,0 +1,44 @@
package analyzer
import (
testutils_test "config-lsp/handlers/fstab/test_utils"
"testing"
)
func TestFSCKMultipleRoots(
t *testing.T,
) {
document := testutils_test.DocumentFromInput(t, `
UUID=12345678-1234-1234-1234-123456789012 /boot ext4 defaults 0 1
UUID=12345678-1234-1234-1234-123456789012 / btrfs defaults 0 1
UUID=12345678-1234-1234-1234-123456789012 /home ext4 defaults 0 2
`)
ctx := &analyzerContext{
document: document,
}
analyzeFSCKField(ctx)
if len(ctx.diagnostics) != 1 {
t.Errorf("Expected 1 error, got %v", len(ctx.diagnostics))
}
}
func TestFSCKBtrfsUsingRoot(
t *testing.T,
) {
document := testutils_test.DocumentFromInput(t, `
UUID=12345678-1234-1234-1234-123456789012 /boot btrfs defaults 0 1
`)
ctx := &analyzerContext{
document: document,
}
analyzeFSCKField(ctx)
if len(ctx.diagnostics) != 1 {
t.Errorf("Expected 1 error, got %v", len(ctx.diagnostics))
}
}

View File

@ -33,8 +33,8 @@ func analyzeValuesAreValid(
checkField(ctx, entry.Fields.Freq, fields.FreqField)
}
if entry.Fields.Pass != nil {
checkField(ctx, entry.Fields.Pass, fields.PassField)
if entry.Fields.Fsck != nil {
checkField(ctx, entry.Fields.Fsck, fields.FsckField)
}
}
}

View File

@ -14,7 +14,7 @@ const (
FstabFieldFileSystemType FstabFieldName = "filesystemtype"
FstabFieldOptions FstabFieldName = "options"
FstabFieldFreq FstabFieldName = "freq"
FstabFieldPass FstabFieldName = "pass"
FstabFieldFsck FstabFieldName = "fsck"
)
type FstabField struct {
@ -29,7 +29,7 @@ type FstabFields struct {
FilesystemType *FstabField
Options *FstabField
Freq *FstabField
Pass *FstabField
Fsck *FstabField
}
type FstabEntry struct {

View File

@ -20,7 +20,7 @@ import (
// LABEL=test ext4 defaults 0 0
func (e FstabEntry) GetFieldAtPosition(position common.Position) FstabFieldName {
// No fields defined, empty line
if e.Fields.Spec == nil && e.Fields.MountPoint == nil && e.Fields.FilesystemType == nil && e.Fields.Options == nil && e.Fields.Freq == nil && e.Fields.Pass == nil {
if e.Fields.Spec == nil && e.Fields.MountPoint == nil && e.Fields.FilesystemType == nil && e.Fields.Options == nil && e.Fields.Freq == nil && e.Fields.Fsck == nil {
return FstabFieldSpec
}
@ -41,8 +41,8 @@ func (e FstabEntry) GetFieldAtPosition(position common.Position) FstabFieldName
if e.Fields.Freq != nil && e.Fields.Freq.ContainsPosition(position) {
return FstabFieldFreq
}
if e.Fields.Pass != nil && e.Fields.Pass.ContainsPosition(position) {
return FstabFieldPass
if e.Fields.Fsck != nil && e.Fields.Fsck.ContainsPosition(position) {
return FstabFieldFsck
}
// Okay let's try to fetch the field by assuming the user is typing from left to right normally
@ -63,8 +63,8 @@ func (e FstabEntry) GetFieldAtPosition(position common.Position) FstabFieldName
return FstabFieldFreq
}
if e.Fields.Freq != nil && e.Fields.Freq.IsPositionAfterEnd(position) && (e.Fields.Pass == nil || e.Fields.Pass.IsPositionBeforeEnd(position)) {
return FstabFieldPass
if e.Fields.Freq != nil && e.Fields.Freq.IsPositionAfterEnd(position) && (e.Fields.Fsck == nil || e.Fields.Fsck.IsPositionBeforeEnd(position)) {
return FstabFieldFsck
}
// Okay shit no idea, let's just give whatever is missing
@ -89,7 +89,7 @@ func (e FstabEntry) GetFieldAtPosition(position common.Position) FstabFieldName
return FstabFieldFreq
}
return FstabFieldPass
return FstabFieldFsck
}
// LABEL=test /mnt/test btrfs subvol=backup,fat=32 [0] [0]
@ -122,7 +122,7 @@ func (e FstabEntry) getDefinedFieldsAmount() uint8 {
if e.Fields.Freq != nil {
definedAmount++
}
if e.Fields.Pass != nil {
if e.Fields.Fsck != nil {
definedAmount++
}

View File

@ -128,7 +128,7 @@ func (s *fstabParserListener) EnterPass(ctx *parser.PassContext) {
text := ctx.GetText()
value := commonparser.ParseRawString(text, commonparser.FullFeatures)
s.fstabContext.currentEntry.Fields.Pass = &FstabField{
s.fstabContext.currentEntry.Fields.Fsck = &FstabField{
LocationRange: location,
Value: value,
}

View File

@ -161,7 +161,7 @@ func (c *FstabConfig) parseStatement(
// FilesystemType: filesystemType,
// Options: options,
// Freq: freq,
// Pass: pass,
// Fsck: pass,
// },
// }
//

View File

@ -27,7 +27,7 @@ LABEL=example /mnt/example fat32 defaults 0 2
rawFirstEntry, _ := c.Entries.Get(uint32(0))
firstEntry := rawFirstEntry.(*FstabEntry)
if !(firstEntry.Fields.Spec.Value.Value == "LABEL=test" && firstEntry.Fields.MountPoint.Value.Value == "/mnt/test" && firstEntry.Fields.FilesystemType.Value.Value == "ext4" && firstEntry.Fields.Options.Value.Value == "defaults" && firstEntry.Fields.Freq.Value.Value == "0" && firstEntry.Fields.Pass.Value.Value == "0") {
if !(firstEntry.Fields.Spec.Value.Value == "LABEL=test" && firstEntry.Fields.MountPoint.Value.Value == "/mnt/test" && firstEntry.Fields.FilesystemType.Value.Value == "ext4" && firstEntry.Fields.Options.Value.Value == "defaults" && firstEntry.Fields.Freq.Value.Value == "0" && firstEntry.Fields.Fsck.Value.Value == "0") {
t.Fatalf("Expected entry to be LABEL=test /mnt/test ext4 defaults 0 0, got %v", firstEntry)
}
@ -71,8 +71,8 @@ LABEL=example /mnt/example fat32 defaults 0 2
t.Errorf("Expected freq end to be 0:36, got %v", firstEntry.Fields.Freq.LocationRange.End)
}
if !(firstEntry.Fields.Pass.LocationRange.Start.Line == 0 && firstEntry.Fields.Pass.LocationRange.Start.Character == 37) {
t.Errorf("Expected pass start to be 0:37, got %v", firstEntry.Fields.Pass.LocationRange.Start)
if !(firstEntry.Fields.Fsck.LocationRange.Start.Line == 0 && firstEntry.Fields.Fsck.LocationRange.Start.Character == 37) {
t.Errorf("Expected pass start to be 0:37, got %v", firstEntry.Fields.Fsck.LocationRange.Start)
}
field := firstEntry.GetFieldAtPosition(common.IndexPosition(0))

View File

@ -0,0 +1,40 @@
package fields
import docvalues "config-lsp/doc-values"
var FsckField = docvalues.EnumValue{
EnforceValues: false,
Values: []docvalues.EnumString{
docvalues.CreateEnumStringWithDoc(
"0",
"Defaults to zero (dont check the filesystem) if not present.",
),
docvalues.CreateEnumStringWithDoc(
"1",
"The root filesystem should be specified with a fs_passno of 1.",
),
docvalues.CreateEnumStringWithDoc(
"2",
"Other filesystems [than the root filesystem] should have a fs_passno of 2.",
),
},
}
var FsckFieldWhenDisabledFilesystems = docvalues.EnumValue{
EnforceValues: false,
Values: []docvalues.EnumString{
docvalues.CreateEnumStringWithDoc(
"0",
"Defaults to zero (dont check the filesystem) if not present.",
),
docvalues.CreateEnumStringWithDoc(
"2",
"Other filesystems [than the root filesystem] should have a fs_passno of 2.",
),
},
}
var FsckOneDisabledFilesystems = map[string]struct{}{
"btrfs": {},
"xfs": {},
}

View File

@ -470,6 +470,10 @@ var MountOptionsMapField = map[string]optionField{
Enums: commondocumentation.UmsdosDocumentationEnums,
Assignable: commondocumentation.UmsdosDocumentationAssignable,
},
"vboxsf": {
Enums: commondocumentation.VboxsfDocumentationEnums,
Assignable: commondocumentation.VboxsfDocumentationAssignable,
},
"vfat": {
Enums: commondocumentation.VfatDocumentationEnums,
Assignable: commondocumentation.VfatDocumentationAssignable,

View File

@ -1,26 +0,0 @@
package fields
import docvalues "config-lsp/doc-values"
var PassField = docvalues.OrValue{
Values: []docvalues.DeprecatedValue{
docvalues.EnumValue{
EnforceValues: false,
Values: []docvalues.EnumString{
docvalues.CreateEnumStringWithDoc(
"0",
"Defaults to zero (dont check the filesystem) if not present.",
),
docvalues.CreateEnumStringWithDoc(
"1",
"The root filesystem should be specified with a fs_passno of 1.",
),
docvalues.CreateEnumStringWithDoc(
"2",
"Other filesystems [than the root filesystem] should have a fs_passno of 2.",
),
},
},
docvalues.NumberValue{},
},
}

View File

@ -4,7 +4,9 @@ import (
"config-lsp/common"
"config-lsp/handlers/fstab/ast"
"config-lsp/handlers/fstab/fields"
"config-lsp/utils"
"fmt"
"strings"
"github.com/tliron/glsp/protocol_3_16"
)
@ -84,13 +86,21 @@ func GetCompletion(
value,
cursor,
), nil
case ast.FstabFieldPass:
value, cursor := getFieldSafely(entry.Fields.Pass, cursor)
case ast.FstabFieldFsck:
value, cursor := getFieldSafely(entry.Fields.Fsck, cursor)
return fields.PassField.DeprecatedFetchCompletions(
value,
cursor,
), nil
if entry.Fields.FilesystemType != nil &&
utils.KeyExists(fields.FsckOneDisabledFilesystems, strings.ToLower(entry.Fields.FilesystemType.Value.Value)) {
return fields.FsckFieldWhenDisabledFilesystems.DeprecatedFetchCompletions(
value,
cursor,
), nil
} else {
return fields.FsckField.DeprecatedFetchCompletions(
value,
cursor,
), nil
}
}
return nil, nil

View File

@ -42,7 +42,7 @@ func GetHoverInfo(
return &hover, nil
case ast.FstabFieldFreq:
return &FreqHoverField, nil
case ast.FstabFieldPass:
case ast.FstabFieldFsck:
return &PassHoverField, nil
}

View File

@ -35,7 +35,27 @@ func Analyze(
d.Indexes = i
analyzeIncludeValues(ctx)
if len(ctx.diagnostics) == 0 {
for _, include := range d.Indexes.Includes {
for _, value := range include.Values {
for _, path := range value.Paths {
_, err := parseFile(string(path))
if err != nil {
ctx.diagnostics = append(ctx.diagnostics, protocol.Diagnostic{
Range: value.LocationRange.ToLSPRange(),
Message: err.Error(),
})
}
}
}
}
}
analyzeValuesAreValid(ctx)
analyzeTokens(ctx)
analyzeIgnoreUnknownHasNoUnnecessary(ctx)
analyzeDependents(ctx)
analyzeBlocks(ctx)

View File

@ -0,0 +1,143 @@
package analyzer
import (
"config-lsp/common"
sshconfig "config-lsp/handlers/ssh_config"
"config-lsp/handlers/ssh_config/ast"
"config-lsp/handlers/ssh_config/fields"
"config-lsp/handlers/ssh_config/indexes"
"config-lsp/utils"
"errors"
"fmt"
"os"
"path"
"path/filepath"
"regexp"
"strings"
protocol "github.com/tliron/glsp/protocol_3_16"
)
var whitespacePattern = regexp.MustCompile(`\S+`)
var environmtalVariablePattern = regexp.MustCompile(`\${.+?}`)
func analyzeIncludeValues(
ctx *analyzerContext,
) {
for _, include := range ctx.document.Indexes.Includes {
for _, value := range include.Values {
if !canBeAnalyzed(value.Value) {
continue
}
validPaths, err := createIncludePaths(value.Value)
if err != nil {
ctx.diagnostics = append(ctx.diagnostics, protocol.Diagnostic{
Range: value.LocationRange.ToLSPRange(),
Message: err.Error(),
Severity: &common.SeverityError,
})
} else {
value.Paths = validPaths
}
}
}
}
// We can't evaluate environmental variables or tokens as we don't know the actual
// values
func canBeAnalyzed(
path string,
) bool {
if environmtalVariablePattern.MatchString(path) {
return false
}
for token := range fields.AvailableTokens {
if strings.Contains(path, token) {
return false
}
}
return true
}
func createIncludePaths(
suggestedPath string,
) ([]indexes.ValidPath, error) {
var absolutePath string
if path.IsAbs(suggestedPath) {
absolutePath = suggestedPath
} else if strings.HasPrefix(suggestedPath, "~") {
homeFolder, err := os.UserHomeDir()
if err != nil {
return nil, errors.New(fmt.Sprintf("Could not find home folder (error: %s)", err))
}
absolutePath = path.Join(homeFolder, suggestedPath[1:])
} else {
homeFolder, err := os.UserHomeDir()
if err != nil {
return nil, errors.New(fmt.Sprintf("Could not find home folder (error: %s)", err))
}
absolutePath = path.Join(homeFolder, ".ssh", suggestedPath)
}
files, err := filepath.Glob(absolutePath)
if err != nil {
return nil, errors.New(fmt.Sprintf("Could not find file %s (error: %s)", absolutePath, err))
}
if len(files) == 0 {
return nil, errors.New(fmt.Sprintf("Could not find file %s", absolutePath))
}
return utils.Map(
files,
func(file string) indexes.ValidPath {
return indexes.ValidPath(file)
},
), nil
}
func parseFile(
filePath string,
) (*sshconfig.SSHDocument, error) {
if d, ok := sshconfig.DocumentParserMap[filePath]; ok {
return d, nil
}
c := ast.NewSSHConfig()
content, err := os.ReadFile(filePath)
if err != nil {
return nil, err
}
parseErrors := c.Parse(string(content))
if len(parseErrors) > 0 {
return nil, errors.New(fmt.Sprintf("Errors in %s", filePath))
}
d := &sshconfig.SSHDocument{
Config: c,
}
errs := Analyze(d)
if len(errs) > 0 {
return nil, errors.New(fmt.Sprintf("Errors in %s", filePath))
}
sshconfig.DocumentParserMap[filePath] = d
return d, nil
}

View File

@ -30,7 +30,7 @@ func checkIsUsingDoubleQuotes(
singleQuotePosition := strings.Index(value.Raw, "'")
// Single quote
if singleQuotePosition != -1 && !quoteRanges.IsCharInside(singleQuotePosition) {
if singleQuotePosition != -1 && !quoteRanges.IsIndexInsideQuotes(singleQuotePosition) {
ctx.diagnostics = append(ctx.diagnostics, protocol.Diagnostic{
Range: valueRange.ToLSPRange(),
Message: "ssh_config does not support single quotes. Use double quotes (\") instead.",

View File

@ -0,0 +1,49 @@
package analyzer
import (
"config-lsp/common"
"config-lsp/handlers/ssh_config/fields"
"config-lsp/utils"
"fmt"
"strings"
protocol "github.com/tliron/glsp/protocol_3_16"
)
func analyzeTokens(
ctx *analyzerContext,
) {
for _, info := range ctx.document.Config.GetAllOptions() {
if info.Option.Key == nil || info.Option.OptionValue == nil {
continue
}
key := info.Option.Key.Key
text := info.Option.OptionValue.Value.Value
var tokens []string
if foundTokens, found := fields.OptionsTokensMap[key]; found {
tokens = foundTokens
} else {
tokens = []string{}
}
disallowedTokens := utils.Without(utils.KeysOfMap(fields.AvailableTokens), tokens)
for _, token := range disallowedTokens {
if strings.Contains(text, token) {
optionName := string(key)
if formatted, found := fields.FieldsNameFormattedMap[key]; found {
optionName = formatted
}
ctx.diagnostics = append(ctx.diagnostics, protocol.Diagnostic{
Range: info.Option.OptionValue.ToLSPRange(),
Message: fmt.Sprintf("Token '%s' is not allowed for option '%s'", token, optionName),
Severity: &common.SeverityError,
})
}
}
}
}

View File

@ -0,0 +1,62 @@
package analyzer
import (
testutils_test "config-lsp/handlers/ssh_config/test_utils"
"testing"
protocol "github.com/tliron/glsp/protocol_3_16"
)
func TestInvalidTokensForNonExisting(
t *testing.T,
) {
d := testutils_test.DocumentFromInput(t, `
ThisOptionDoesNotExist Hello%%World
`)
ctx := &analyzerContext{
document: d,
diagnostics: make([]protocol.Diagnostic, 0),
}
analyzeTokens(ctx)
if !(len(ctx.diagnostics) == 1) {
t.Errorf("Expected 1 error, got %v", len(ctx.diagnostics))
}
}
func TestInvalidTokensForExistingOption(
t *testing.T,
) {
d := testutils_test.DocumentFromInput(t, `
Tunnel Hello%%World
`)
ctx := &analyzerContext{
document: d,
diagnostics: make([]protocol.Diagnostic, 0),
}
analyzeTokens(ctx)
if !(len(ctx.diagnostics) == 1) {
t.Errorf("Expected 1 error, got %v", len(ctx.diagnostics))
}
}
func TestValidTokens(
t *testing.T,
) {
d := testutils_test.DocumentFromInput(t, `
LocalCommand Hello World %% and %d
`)
ctx := &analyzerContext{
document: d,
diagnostics: make([]protocol.Diagnostic, 0),
}
analyzeTokens(ctx)
if len(ctx.diagnostics) > 0 {
t.Fatalf("Expected no errors, but got %v", len(ctx.diagnostics))
}
}

View File

@ -98,6 +98,7 @@ var Options = map[NormalizedOptionName]docvalues.DocumentationValue{
Value: docvalues.ArrayValue{
Separator: ",",
DuplicatesExtractor: &docvalues.SimpleDuplicatesExtractor,
RespectQuotes: true,
SubValue: docvalues.StringValue{},
},
},
@ -127,6 +128,7 @@ rsa-sha2-512,rsa-sha2-256
SubValue: docvalues.ArrayValue{
Separator: ",",
DuplicatesExtractor: &docvalues.DuplicatesAllowedExtractor,
RespectQuotes: true,
// TODO: Add
SubValue: docvalues.StringValue{},
},
@ -170,6 +172,7 @@ The default is not to expire channels of any type for inactivity.`,
Value: docvalues.ArrayValue{
Separator: " ",
DuplicatesExtractor: &channelTimeoutExtractor,
RespectQuotes: true,
SubValue: docvalues.KeyValueAssignmentValue{
ValueIsOptional: false,
Separator: "=",
@ -361,6 +364,7 @@ aes128-gcm@openssh.com,aes256-gcm@openssh.com
Value: docvalues.ArrayValue{
Separator: " ",
DuplicatesExtractor: &docvalues.SimpleDuplicatesExtractor,
RespectQuotes: true,
SubValue: docvalues.PathValue{
RequiredType: docvalues.PathTypeFile,
},
@ -479,6 +483,7 @@ rsa-sha2-512,rsa-sha2-256
Value: docvalues.ArrayValue{
Separator: " ",
DuplicatesExtractor: &docvalues.SimpleDuplicatesExtractor,
RespectQuotes: true,
SubValue: docvalues.StringValue{},
},
},
@ -493,7 +498,9 @@ rsa-sha2-512,rsa-sha2-256
},
},
docvalues.ArrayValue{
Separator: " ",
Separator: " ",
DuplicatesExtractor: &docvalues.SimpleDuplicatesExtractor,
RespectQuotes: true,
SubValue: docvalues.EnumValue{
EnforceValues: true,
Values: []docvalues.EnumString{
@ -539,6 +546,7 @@ rsa-sha2-512,rsa-sha2-256
Value: docvalues.ArrayValue{
Separator: ",",
DuplicatesExtractor: &docvalues.SimpleDuplicatesExtractor,
RespectQuotes: true,
SubValue: docvalues.EnumValue{
EnforceValues: true,
Values: []docvalues.EnumString{
@ -951,7 +959,9 @@ rsa-sha2-512,rsa-sha2-256
~/.ssh/known_hosts,
~/.ssh/known_hosts2.`,
Value: docvalues.ArrayValue{
Separator: " ",
Separator: " ",
DuplicatesExtractor: &docvalues.SimpleDuplicatesExtractor,
RespectQuotes: true,
SubValue: docvalues.PathValue{
RequiredType: docvalues.PathTypeFile,
},

View File

@ -0,0 +1,73 @@
package fields
import "config-lsp/utils"
var AvailableTokens = map[string]string{
"%%": "A literal %.",
"%C": "Hash of %l%h%p%r%j.",
"%d": "Local user's home directory.",
"%f": "The fingerprint of the server's host key.",
"%H": "The known_hosts hostname or address that is being searched for.",
"%h": "The remote hostname.",
"%I": "A string describing the reason for a KnownHostsCommand execution: either ADDRESS when looking up a host by address (only when CheckHostIP is enabled), HOSTNAME when searching by hostname, or ORDER when preparing the host key algorithm preference list to use for the destination host.",
"%i": "The local user ID.",
"%j": "The contents of the ProxyJump option, or the empty string if this option is unset.",
"%K": "The base64 encoded host key.",
"%k": "The host key alias if specified, otherwise the original remote hostname given on the command line.",
"%L": "The local hostname.",
"%l": "The local hostname, including the domain name.",
"%n": "The original remote hostname, as given on the command line.",
"%p": "The remote port.",
"%r": "The remote username.",
"%T": "The local tun(4) or tap(4) network interface assigned if tunnel forwarding was requested, or \"NONE\" otherwise.",
"%t": "The type of the server host key, e.g. ssh-ed25519.",
"%u": "The local username.",
}
// A map of <option name> to <list of supported tokens>
// This is derived from the TOKENS section of ssh_config
var OptionsTokensMap = map[NormalizedOptionName][]string{
"certificatefile": firstTokens,
"controlpath": firstTokens,
"identityagent": firstTokens,
"identityfile": firstTokens,
"include": firstTokens,
"localforward": firstTokens,
"match": firstTokens,
"exec": firstTokens,
"remotecommand": firstTokens,
"remoteforward": firstTokens,
"revokedhostkeys": firstTokens,
"userknownhostsfile": firstTokens,
"knownhostscommand": append(firstTokens, []string{
"%f", "%H", "%I", "%K", "%t",
}...),
"hostname": {
"%%",
"%h",
},
"localcommand": utils.KeysOfMap(AvailableTokens),
"proxycommand": {
"%%", "%h", "%n", "%p", "%r",
},
}
var firstTokens = []string{
"%%",
"%C",
"%d",
"%h",
"%i",
"%j",
"%k",
"%L",
"%l",
"%n",
"%p",
"%r",
"%u",
}

View File

@ -31,6 +31,7 @@ func prefixPlusMinusCaret(values []docvalues.EnumString) docvalues.PrefixWithMea
SubValue: docvalues.ArrayValue{
Separator: ",",
DuplicatesExtractor: &docvalues.SimpleDuplicatesExtractor,
RespectQuotes: true,
SubValue: docvalues.EnumValue{
Values: values,
},

View File

@ -15,7 +15,7 @@ func GetRootCompletions(
d *sshconfig.SSHDocument,
parentBlock ast.SSHBlock,
suggestValue bool,
) ([]protocol.CompletionItem, error) {
) []protocol.CompletionItem {
kind := protocol.CompletionItemKindField
availableOptions := make(map[fields.NormalizedOptionName]docvalues.DocumentationValue, 0)
@ -58,7 +58,7 @@ func GetRootCompletions(
return *completion
},
), nil
)
}
func GetOptionCompletions(
@ -67,11 +67,11 @@ func GetOptionCompletions(
block ast.SSHBlock,
line uint32,
cursor common.CursorPosition,
) ([]protocol.CompletionItem, error) {
) []protocol.CompletionItem {
option, found := fields.Options[entry.Key.Key]
if !found {
return nil, nil
return nil
}
if entry.Key.Key == matchOption {
@ -92,18 +92,48 @@ func GetOptionCompletions(
}
if entry.OptionValue == nil {
return option.DeprecatedFetchCompletions("", 0), nil
return option.DeprecatedFetchCompletions("", 0)
}
// token completions
completions := getTokenCompletions(entry, cursor)
// Hello wo|rld
lineValue := entry.OptionValue.Value.Raw
// NEW: docvalues index
return option.DeprecatedFetchCompletions(
completions = append(completions, option.DeprecatedFetchCompletions(
lineValue,
common.DeprecatedImprovedCursorToIndex(
cursor,
lineValue,
entry.OptionValue.Start.Character,
),
), nil
)...)
return completions
}
func getTokenCompletions(
entry *ast.SSHOption,
cursor common.CursorPosition,
) []protocol.CompletionItem {
completions := make([]protocol.CompletionItem, 0)
index := common.CursorToCharacterIndex(uint32(cursor))
if entry.Value.Raw[index] == '%' {
if tokens, found := fields.OptionsTokensMap[entry.Key.Key]; found {
for _, token := range tokens {
description := fields.AvailableTokens[token]
kind := protocol.CompletionItemKindConstant
completions = append(completions, protocol.CompletionItem{
Label: token,
Kind: &kind,
Documentation: description,
})
}
}
}
return completions
}

View File

@ -14,12 +14,12 @@ func getMatchCompletions(
d *sshconfig.SSHDocument,
cursor common.CursorPosition,
match *matchparser.Match,
) ([]protocol.CompletionItem, error) {
) []protocol.CompletionItem {
if match == nil || len(match.Entries) == 0 {
completions := getMatchCriteriaCompletions()
completions = append(completions, getMatchAllKeywordCompletion())
return completions, nil
return completions
}
entry := match.GetEntryAtPosition(cursor)
@ -39,10 +39,10 @@ func getMatchCompletions(
completions = append(completions, getMatchAllKeywordCompletion())
}
return completions, nil
return completions
}
return getMatchValueCompletions(entry, cursor), nil
return getMatchValueCompletions(entry, cursor)
}
func getMatchCriteriaCompletions() []protocol.CompletionItem {

View File

@ -15,7 +15,7 @@ func getTagCompletions(
line uint32,
cursor common.CursorPosition,
entry *ast.SSHOption,
) ([]protocol.CompletionItem, error) {
) []protocol.CompletionItem {
completions := make([]protocol.CompletionItem, 0)
for name, info := range d.Indexes.Tags {
@ -35,7 +35,7 @@ func getTagCompletions(
})
}
return completions, nil
return completions
}
func renderMatchBlock(

View File

@ -0,0 +1,43 @@
package handlers
import (
"config-lsp/common"
"config-lsp/handlers/ssh_config/indexes"
"config-lsp/utils"
"slices"
protocol "github.com/tliron/glsp/protocol_3_16"
)
func GetIncludeOptionLocation(
include *indexes.SSHIndexIncludeLine,
index common.IndexPosition,
) []protocol.Location {
foundIndex, found := slices.BinarySearchFunc(
include.Values,
index,
func(current *indexes.SSHIndexIncludeValue, target common.IndexPosition) int {
if current.IsPositionAfterEnd(target) {
return -1
}
if current.IsPositionBeforeStart(target) {
return 1
}
return 0
},
)
if !found {
return nil
}
path := include.Values[foundIndex]
return utils.Map(path.Paths, func(path indexes.ValidPath) protocol.Location {
return protocol.Location{
URI: path.AsURI(),
}
})
}

View File

@ -14,6 +14,10 @@ func FetchCodeActions(
) []protocol.CodeAction {
line := params.Range.Start.Line
if d.Indexes == nil {
return nil
}
if unknownOption, found := d.Indexes.UnknownOptions[line]; found {
var blockLine *uint32

View File

@ -0,0 +1,150 @@
package handlers
import (
"config-lsp/common"
"config-lsp/handlers/ssh_config/ast"
protocol "github.com/tliron/glsp/protocol_3_16"
)
func GetOptionSignatureHelp(
option *ast.SSHOption,
cursor common.CursorPosition,
) *protocol.SignatureHelp {
var index uint32
if option == nil || option.Key == nil || (option.OptionValue == nil || option.Key.ContainsPosition(cursor)) {
index = 0
} else {
index = 1
}
signature := uint32(0)
return &protocol.SignatureHelp{
ActiveSignature: &signature,
Signatures: []protocol.SignatureInformation{
{
Label: "<option> <value>",
ActiveParameter: &index,
Parameters: []protocol.ParameterInformation{
{
Label: []uint32{
0,
uint32(len("<option>") + 1),
},
Documentation: "The option name",
},
{
Label: []uint32{
uint32(len("<option>")),
uint32(len("<option>") + len("<value>") + 1),
},
Documentation: "The value for the option",
},
},
},
},
}
}
func GetMatchSignatureHelp(
match *ast.SSHMatchBlock,
cursor common.CursorPosition,
) *protocol.SignatureHelp {
var index uint32
if match.MatchOption.Key.ContainsPosition(cursor) {
index = 0
} else {
entry := match.MatchValue.GetEntryAtPosition(cursor)
if entry == nil || entry.Criteria.ContainsPosition(cursor) {
index = 1
} else {
index = 2
}
}
signature := uint32(0)
return &protocol.SignatureHelp{
ActiveSignature: &signature,
Signatures: []protocol.SignatureInformation{
{
Label: "Match <criteria> <values>",
ActiveParameter: &index,
Parameters: []protocol.ParameterInformation{
{
Label: []uint32{
0,
uint32(len("Match") + 1),
},
Documentation: "The \"Match\" keyword",
},
{
Label: []uint32{
uint32(len("Match ")),
uint32(len("Match ") + len("<criteria>")),
},
Documentation: "The criteria name",
},
{
Label: []uint32{
uint32(len("Host <criteria> ")),
uint32(len("Host <criteria> ") + len("<values>") + 1),
},
Documentation: "Values for the criteria",
},
},
},
},
}
}
func GetHostSignatureHelp(
host *ast.SSHHostBlock,
cursor common.CursorPosition,
) *protocol.SignatureHelp {
var index uint32
if host.HostOption.Key.ContainsPosition(cursor) {
index = 0
} else if len(host.HostValue.Hosts) >= 1 && host.HostValue.Hosts[0].ContainsPosition(cursor) {
index = 1
} else {
index = 2
}
signature := uint32(0)
return &protocol.SignatureHelp{
ActiveSignature: &signature,
Signatures: []protocol.SignatureInformation{
{
Label: "Host <host1> [<host2> ...]",
ActiveParameter: &index,
Parameters: []protocol.ParameterInformation{
{
Label: []uint32{
0,
uint32(len("Host") + 1),
},
Documentation: "The \"Host\" keyword",
},
{
Label: []uint32{
uint32(len("Host ")),
uint32(len("Host ") + len("<host1>") + 1),
},
Documentation: "A host that should match",
},
{
Label: []uint32{
uint32(len("Host <host1> ")),
uint32(len("Host <host1> ") + len("[<host2> ...]") + 1),
},
Documentation: "Additional (optional) hosts that should match",
},
},
},
},
}
}

View File

@ -44,7 +44,7 @@ type SSHIndexTagInfo struct {
type SSHIndexes struct {
AllOptionsPerName map[fields.NormalizedOptionName](map[ast.SSHBlock]([]*ast.SSHOption))
Includes []*SSHIndexIncludeLine
Includes map[uint32]*SSHIndexIncludeLine
BlockRanges map[uint32]ast.SSHBlock
@ -57,6 +57,8 @@ type SSHIndexes struct {
// This is a map of <line> to <option>
UnknownOptions map[uint32]ast.AllOptionInfo
Tags map[string]SSHIndexTagInfo
// Map of available tags
Tags map[string]SSHIndexTagInfo
// Map of <Tag name> to <option per block>
TagImports map[string](map[ast.SSHBlock]*ast.SSHOption)
}

View File

@ -8,14 +8,15 @@ import (
"errors"
"fmt"
"regexp"
"strings"
)
var whitespacePattern = regexp.MustCompile(`\S+`)
var includePattern = regexp.MustCompile(`".+?"|[^\s]+`)
func NewSSHIndexes() *SSHIndexes {
return &SSHIndexes{
AllOptionsPerName: make(map[fields.NormalizedOptionName](map[ast.SSHBlock]([]*ast.SSHOption))),
Includes: make([]*SSHIndexIncludeLine, 0),
Includes: make(map[uint32]*SSHIndexIncludeLine),
IgnoredOptions: make(map[ast.SSHBlock]SSHIndexIgnoredUnknowns),
UnknownOptions: make(map[uint32]ast.AllOptionInfo),
Tags: make(map[string]SSHIndexTagInfo),
@ -57,15 +58,21 @@ func CreateIndexes(config ast.SSHConfig) (*SSHIndexes, []common.LSPError) {
// Add Includes
for block, options := range indexes.AllOptionsPerName[includeOption] {
includeOption := options[0]
rawValue := includeOption.OptionValue.Value.Value
pathIndexes := whitespacePattern.FindAllStringIndex(rawValue, -1)
// We want to parse quotes manually
rawValue := includeOption.OptionValue.Value.Raw
pathIndexes := includePattern.FindAllStringIndex(rawValue, -1)
paths := make([]*SSHIndexIncludeValue, 0)
for _, pathIndex := range pathIndexes {
startIndex := pathIndex[0]
endIndex := pathIndex[1]
rawPath := rawValue[startIndex:endIndex]
rawPath := strings.ReplaceAll(
rawValue[startIndex:endIndex],
`"`,
"",
)
offset := includeOption.OptionValue.Start.Character
path := SSHIndexIncludeValue{

View File

@ -173,3 +173,48 @@ Match tagged myuser
t.Errorf("Expected first tag import to be 'good_ip', but got %v", indexes.TagImports)
}
}
func TestIncludeExample(
t *testing.T,
) {
input := utils.Dedent(`
PermitRootLogin yes
Include /etc/ssh/sshd_config.d/*.conf hello_world
`)
config := ast.NewSSHConfig()
errors := config.Parse(input)
if len(errors) > 0 {
t.Fatalf("Expected no errors, but got %v", len(errors))
}
indexes, errors := CreateIndexes(*config)
if len(errors) > 0 {
t.Fatalf("Expected no errors, but got %v", len(errors))
}
if !(len(indexes.Includes) == 1) {
t.Fatalf("Expected 1 include, but got %v", len(indexes.Includes))
}
if !(len(indexes.Includes[1].Values) == 2) {
t.Fatalf("Expected 2 include path, but got %v", len(indexes.Includes[1].Values))
}
if !(indexes.Includes[1].Values[0].Value == "/etc/ssh/sshd_config.d/*.conf" &&
indexes.Includes[1].Values[0].Start.Line == 1 &&
indexes.Includes[1].Values[0].End.Line == 1 &&
indexes.Includes[1].Values[0].Start.Character == 8 &&
indexes.Includes[1].Values[0].End.Character == 37) {
t.Errorf("Expected '/etc/ssh/sshd_config.d/*.conf' on line 1, but got %v on line %v", indexes.Includes[1].Values[0].Value, indexes.Includes[1].Values[0].Start.Line)
}
if !(indexes.Includes[1].Values[1].Value == "hello_world" &&
indexes.Includes[1].Values[1].Start.Line == 1 &&
indexes.Includes[1].Values[1].End.Line == 1 &&
indexes.Includes[1].Values[1].Start.Character == 38 &&
indexes.Includes[1].Values[1].End.Character == 49) {
t.Errorf("Expected 'hello_world' on line 1, but got %v on line %v", indexes.Includes[1].Values[1].Value, indexes.Includes[1].Values[1].Start.Line)
}
}

View File

@ -34,7 +34,7 @@ func TextDocumentCompletion(context *glsp.Context, params *protocol.CompletionPa
block,
// Empty line, or currently typing a new key
option == nil || isEmptyPattern.Match([]byte(option.Value.Raw[cursor:])),
)
), nil
}
if option.Separator != nil && option.OptionValue.IsPositionAfterStart(cursor) {
@ -44,7 +44,7 @@ func TextDocumentCompletion(context *glsp.Context, params *protocol.CompletionPa
block,
line,
cursor,
)
), nil
}
return nil, nil

View File

@ -1,8 +1,10 @@
package lsp
import (
"config-lsp/common"
sshconfig "config-lsp/handlers/ssh_config"
"config-lsp/handlers/ssh_config/fields"
"config-lsp/handlers/ssh_config/handlers"
"github.com/tliron/glsp"
protocol "github.com/tliron/glsp/protocol_3_16"
@ -12,9 +14,16 @@ var tagOption = fields.CreateNormalizedName("Tag")
func TextDocumentDefinition(context *glsp.Context, params *protocol.DefinitionParams) ([]protocol.Location, error) {
line := params.Position.Line
index := common.LSPCharacterAsIndexPosition(params.Position.Character)
d := sshconfig.DocumentParserMap[params.TextDocument.URI]
if include, found := d.Indexes.Includes[line]; found {
return handlers.GetIncludeOptionLocation(
include,
index,
), nil
}
option, _ := d.Config.FindOption(line)
if option != nil && option.Key.Key == tagOption && option.OptionValue != nil {

View File

@ -1,10 +1,49 @@
package lsp
import (
"config-lsp/common"
sshconfig "config-lsp/handlers/ssh_config"
"config-lsp/handlers/ssh_config/ast"
"config-lsp/handlers/ssh_config/fields"
"config-lsp/handlers/ssh_config/handlers"
"github.com/tliron/glsp"
protocol "github.com/tliron/glsp/protocol_3_16"
)
var hostOption = fields.CreateNormalizedName("Host")
func TextDocumentSignatureHelp(context *glsp.Context, params *protocol.SignatureHelpParams) (*protocol.SignatureHelp, error) {
return nil, nil
document := sshconfig.DocumentParserMap[params.TextDocument.URI]
line := uint32(params.Position.Line)
cursor := common.LSPCharacterAsCursorPosition(params.Position.Character)
if _, found := document.Config.CommentLines[line]; found {
// Comment
return nil, nil
}
option, block := document.Config.FindOption(line)
if option != nil {
if option.Key != nil {
switch option.Key.Key {
case matchOption:
return handlers.GetMatchSignatureHelp(
block.(*ast.SSHMatchBlock),
cursor,
), nil
case hostOption:
return handlers.GetHostSignatureHelp(
block.(*ast.SSHHostBlock),
cursor,
), nil
}
}
return handlers.GetOptionSignatureHelp(option, cursor), nil
} else {
return handlers.GetOptionSignatureHelp(option, cursor), nil
}
}

View File

@ -55,6 +55,7 @@ func Analyze(
}
analyzeMatchBlocks(ctx)
analyzeTokens(ctx)
return ctx.diagnostics
}

View File

@ -12,10 +12,12 @@ import (
protocol "github.com/tliron/glsp/protocol_3_16"
)
var matchOption = fields.CreateNormalizedName("Match")
func analyzeMatchBlocks(
ctx *analyzerContext,
) {
for matchBlock, options := range ctx.document.Indexes.AllOptionsPerName["Match"] {
for matchBlock, options := range ctx.document.Indexes.AllOptionsPerName[matchOption] {
option := options[0]
// Check if the match block has filled out all fields
if matchBlock == nil || matchBlock.MatchValue == nil || len(matchBlock.MatchValue.Entries) == 0 {

View File

@ -40,7 +40,8 @@ func checkOption(
checkIsUsingDoubleQuotes(ctx, option.Key.Value, option.Key.LocationRange)
checkQuotesAreClosed(ctx, option.Key.Value, option.Key.LocationRange)
docOption, found := fields.Options[option.Key.Key]
key := option.Key.Key
docOption, found := fields.Options[key]
if !found {
ctx.diagnostics = append(ctx.diagnostics, protocol.Diagnostic{
@ -52,7 +53,7 @@ func checkOption(
return
}
if _, found := fields.MatchAllowedOptions[option.Key.Key]; !found && isInMatchBlock {
if _, found := fields.MatchAllowedOptions[key]; !found && isInMatchBlock {
ctx.diagnostics = append(ctx.diagnostics, protocol.Diagnostic{
Range: option.Key.ToLSPRange(),
Message: fmt.Sprintf("Option '%s' is not allowed inside Match blocks", option.Key.Key),

View File

@ -30,7 +30,7 @@ func checkIsUsingDoubleQuotes(
singleQuotePosition := strings.Index(value.Raw, "'")
// Single quote
if singleQuotePosition != -1 && !quoteRanges.IsCharInside(singleQuotePosition) {
if singleQuotePosition != -1 && !quoteRanges.IsIndexInsideQuotes(singleQuotePosition) {
ctx.diagnostics = append(ctx.diagnostics, protocol.Diagnostic{
Range: valueRange.ToLSPRange(),
Message: "sshd_config does not support single quotes. Use double quotes (\") instead.",

View File

@ -0,0 +1,49 @@
package analyzer
import (
"config-lsp/common"
"config-lsp/handlers/sshd_config/fields"
"config-lsp/utils"
"fmt"
"strings"
protocol "github.com/tliron/glsp/protocol_3_16"
)
func analyzeTokens(
ctx *analyzerContext,
) {
for _, option := range ctx.document.Config.GetAllOptions() {
if option.Key == nil || option.OptionValue == nil {
continue
}
key := option.Key.Key
text := option.OptionValue.Value.Value
var tokens []string
if foundTokens, found := fields.OptionsTokensMap[key]; found {
tokens = foundTokens
} else {
tokens = []string{}
}
disallowedTokens := utils.Without(utils.KeysOfMap(fields.AvailableTokens), tokens)
for _, token := range disallowedTokens {
if strings.Contains(text, token) {
optionName := string(key)
if formatted, found := fields.FieldsNameFormattedMap[key]; found {
optionName = formatted
}
ctx.diagnostics = append(ctx.diagnostics, protocol.Diagnostic{
Range: option.OptionValue.ToLSPRange(),
Message: fmt.Sprintf("Token '%s' is not allowed for option '%s'", token, optionName),
Severity: &common.SeverityError,
})
}
}
}
}

View File

@ -0,0 +1,62 @@
package analyzer
import (
testutils_test "config-lsp/handlers/sshd_config/test_utils"
"testing"
protocol "github.com/tliron/glsp/protocol_3_16"
)
func TestInvalidTokensForNonExisting(
t *testing.T,
) {
d := testutils_test.DocumentFromInput(t, `
ThisOptionDoesNotExist Hello%%World
`)
ctx := &analyzerContext{
document: d,
diagnostics: make([]protocol.Diagnostic, 0),
}
analyzeTokens(ctx)
if !(len(ctx.diagnostics) == 1) {
t.Errorf("Expected 1 error, got %v", len(ctx.diagnostics))
}
}
func TestInvalidTokensForExistingOption(
t *testing.T,
) {
d := testutils_test.DocumentFromInput(t, `
Tunnel Hello%%World
`)
ctx := &analyzerContext{
document: d,
diagnostics: make([]protocol.Diagnostic, 0),
}
analyzeTokens(ctx)
if !(len(ctx.diagnostics) == 1) {
t.Errorf("Expected 1 error, got %v", len(ctx.diagnostics))
}
}
func TestValidTokens(
t *testing.T,
) {
d := testutils_test.DocumentFromInput(t, `
AuthorizedPrincipalsCommand Hello World %% and %d
`)
ctx := &analyzerContext{
document: d,
diagnostics: make([]protocol.Diagnostic, 0),
}
analyzeTokens(ctx)
if len(ctx.diagnostics) > 0 {
t.Fatalf("Expected no errors, but got %v", len(ctx.diagnostics))
}
}

View File

@ -4,6 +4,7 @@ import (
"config-lsp/common"
commonparser "config-lsp/common/parser"
"config-lsp/handlers/sshd_config/ast/parser"
"config-lsp/handlers/sshd_config/fields"
"config-lsp/handlers/sshd_config/match-parser"
"strings"
@ -76,7 +77,7 @@ func (s *sshdParserListener) EnterKey(ctx *parser.KeyContext) {
s.sshdContext.currentOption.Key = &SSHDKey{
LocationRange: location,
Value: value,
Key: key,
Key: fields.CreateNormalizedName(key),
}
}

View File

@ -234,7 +234,7 @@ Match Address 192.168.0.2
}
firstOption, firstMatchBlock := p.FindOption(uint32(3))
if !(firstOption.Key.Key == "PasswordAuthentication" && firstOption.OptionValue.Value.Value == "yes") {
if !(firstOption.Key.Key == "passwordauthentication" && firstOption.OptionValue.Value.Value == "yes") {
t.Errorf("Expected first option to be 'PasswordAuthentication yes' and first match block to be 'Match Address 192.168.0.1', but got: %v, %v", firstOption, firstMatchBlock)
}

View File

@ -3,14 +3,16 @@ package ast
import (
"config-lsp/common"
commonparser "config-lsp/common/parser"
"config-lsp/handlers/sshd_config/fields"
"config-lsp/handlers/sshd_config/match-parser"
"github.com/emirpasic/gods/maps/treemap"
)
type SSHDKey struct {
common.LocationRange
Value commonparser.ParsedString
Key string
Key fields.NormalizedOptionName
}
type SSHDValue struct {

View File

@ -0,0 +1,9 @@
package fields
import "strings"
type NormalizedOptionName string
func CreateNormalizedName(s string) NormalizedOptionName {
return NormalizedOptionName(strings.ToLower(s))
}

View File

@ -10,12 +10,12 @@ var ZERO = 0
var MAX_PORT = 65535
var MAX_FILE_MODE = 0777
var Options = map[string]docvalues.DocumentationValue{
"AcceptEnv": {
var Options = map[NormalizedOptionName]docvalues.DocumentationValue{
"acceptenv": {
Documentation: `Specifies what environment variables sent by the client will be copied into the session's environ(7). See SendEnv and SetEnv in ssh_config(5) for how to configure the client. The TERM environment variable is always accepted whenever the client requests a pseudo-terminal as it is required by the protocol. Variables are specified by name, which may contain the wildcard characters * and ?. Multiple environment variables may be separated by whitespace or spread across multiple AcceptEnv directives. Be warned that some environment variables could be used to bypass restricted user environments. For this reason, care should be taken in the use of this directive. The default is not to accept any environment variables.`,
Value: docvalues.StringValue{},
},
"AddressFamily": {
"addressfamily": {
Documentation: `Specifies which address family should be used by sshd(8). Valid arguments are any (the default), inet (use IPv4 only), or inet6 (use IPv6 only).`,
Value: docvalues.EnumValue{
EnforceValues: true,
@ -26,17 +26,17 @@ var Options = map[string]docvalues.DocumentationValue{
},
},
},
"AllowAgentForwarding": {
"allowagentforwarding": {
Documentation: `Specifies whether ssh-agent(1) forwarding is permitted. The default is yes. Note that disabling agent forwarding does not improve security unless users are also denied shell access, as they can always install their own forwarders.`,
Value: booleanEnumValue,
},
"AllowGroups": {
"allowgroups": {
Documentation: `This keyword can be followed by a list of group name patterns, separated by spaces. If specified, login is allowed only for users whose primary group or supplementary group list matches one of the patterns. Only group names are valid; a numerical group ID is not recognized. By default, login is allowed for all groups. The allow/deny groups directives are processed in the following order: DenyGroups, AllowGroups.
See PATTERNS in ssh_config(5) for more information on patterns. This keyword may appear multiple times in sshd_config with each instance appending to the list.`,
Value: docvalues.GroupValue(" ", false),
},
"AllowStreamLocalForwarding": {
"allowstreamlocalforwarding": {
Documentation: `Specifies whether StreamLocal (Unix-domain socket) forwarding is permitted. The available options are yes (the default) or all to allow StreamLocal forwarding, no to prevent all StreamLocal forwarding, local to allow local (from the perspective of ssh(1)) forwarding only or remote to allow remote forwarding only. Note that disabling StreamLocal forwarding does not improve security unless users are also denied shell access, as they can always install their own forwarders.`,
Value: docvalues.EnumValue{
EnforceValues: true,
@ -49,7 +49,7 @@ See PATTERNS in ssh_config(5) for more information on patterns. This keyword may
},
},
},
"AllowTcpForwarding": {
"allowtcpforwarding": {
Documentation: `Specifies whether TCP forwarding is permitted. The available options are yes (the default) or all to allow TCP forwarding, no to prevent all TCP forwarding, local to allow local (from the perspective of ssh(1)) forwarding only or remote to allow remote forwarding only. Note that disabling TCP forwarding does not improve security unless users are also denied shell access, as they can always install their own forwarders.`,
Value: docvalues.EnumValue{
EnforceValues: true,
@ -62,12 +62,12 @@ See PATTERNS in ssh_config(5) for more information on patterns. This keyword may
},
},
},
"AllowUsers": {
"allowusers": {
Documentation: `This keyword can be followed by a list of user name patterns, separated by spaces. If specified, login is allowed only for user names that match one of the patterns. Only user names are valid; a numerical user ID is not recognized. By default, login is allowed for all users. If the pattern takes the form USER@HOST then USER and HOST are separately checked, restricting logins to particular users from particular hosts. HOST criteria may additionally contain addresses to match in CIDR address/masklen format. The allow/deny users directives are processed in the following order: DenyUsers, AllowUsers.
See PATTERNS in ssh_config(5) for more information on patterns. This keyword may appear multiple times in sshd_config with each instance appending to the list.`,
Value: docvalues.UserValue(" ", false),
},
"AuthenticationMethods": {
"authenticationmethods": {
Documentation: `Specifies the authentication methods that must be successfully completed for a user to be granted access. This option must be followed by one or more lists of comma-separated authentication method names, or by the single string any to indicate the default behaviour of accepting any single authentication method. If the default is overridden, then successful authentication requires completion of every method in at least one of these lists.
For example, "publickey,password publickey,keyboard-interactive" would require the user to complete public key authentication, followed by either password or keyboard interactive authentication. Only methods that are next in one or more lists are offered at each stage, so for this example it would not be possible to attempt password or keyboard-interactive authentication before public key.
For keyboard interactive authentication it is also possible to restrict authentication to a specific device by appending a colon followed by the device identifier bsdauth or pam. depending on the server configuration. For example, "keyboard-interactive:bsdauth" would restrict keyboard interactive authentication to the bsdauth device.
@ -83,6 +83,9 @@ See PATTERNS in ssh_config(5) for more information on patterns. This keyword may
},
},
docvalues.ArrayValue{
Separator: ",",
DuplicatesExtractor: &docvalues.SimpleDuplicatesExtractor,
RespectQuotes: true,
SubValue: docvalues.EnumValue{
EnforceValues: true,
Values: []docvalues.EnumString{
@ -111,34 +114,35 @@ See PATTERNS in ssh_config(5) for more information on patterns. This keyword may
},
},
},
"AuthorizedKeysCommand": {
"authorizedkeyscommand": {
Documentation: `Specifies a program to be used to look up the user's public keys. The program must be owned by root, not writable by group or others and specified by an absolute path. Arguments to AuthorizedKeysCommand accept the tokens described in the TOKENS section. If no arguments are specified then the username of the target user is used.
The program should produce on standard output zero or more lines of authorized_keys output (see AUTHORIZED_KEYS in sshd(8)). AuthorizedKeysCommand is tried after the usual AuthorizedKeysFile files and will not be executed if a matching key is found there. By default, no AuthorizedKeysCommand is run.`,
Value: docvalues.StringValue{},
},
"AuthorizedKeysCommandUser": {
"authorizedkeyscommanduser": {
Documentation: `Specifies the user under whose account the AuthorizedKeysCommand is run. It is recommended to use a dedicated user that has no other role on the host than running authorized keys commands. If AuthorizedKeysCommand is specified but AuthorizedKeysCommandUser is not, then sshd(8) will refuse to start.`,
Value: docvalues.UserValue("", true),
},
"AuthorizedKeysFile": {
"authorizedkeysfile": {
Documentation: `Specifies the file that contains the public keys used for user authentication. The format is described in the AUTHORIZED_KEYS FILE FORMAT section of sshd(8). Arguments to AuthorizedKeysFile accept the tokens described in the “TOKENS” section. After expansion, AuthorizedKeysFile is taken to be an absolute path or one relative to the user's home directory. Multiple files may be listed, separated by whitespace. Alternately this option may be set to none to skip checking for user keys in files. The default is ".ssh/authorized_keys .ssh/authorized_keys2".`,
Value: docvalues.ArrayValue{
SubValue: docvalues.StringValue{},
Separator: " ",
DuplicatesExtractor: &docvalues.DuplicatesAllowedExtractor,
RespectQuotes: true,
},
},
"AuthorizedPrincipalsCommand": {
"authorizedprincipalscommand": {
Documentation: `Specifies a program to be used to generate the list of allowed certificate principals as per AuthorizedPrincipalsFile. The program must be owned by root, not writable by group or others and specified by an absolute path. Arguments to AuthorizedPrincipalsCommand accept the tokens described in the TOKENS section. If no arguments are specified then the username of the target user is used.
The program should produce on standard output zero or more lines of AuthorizedPrincipalsFile output. If either AuthorizedPrincipalsCommand or AuthorizedPrincipalsFile is specified, then certificates offered by the client for authentication must contain a principal that is listed. By default, no AuthorizedPrincipalsCommand is run.`,
Value: docvalues.StringValue{},
},
"AuthorizedPrincipalsCommandUser": {
"authorizedprincipalscommanduser": {
Documentation: `Specifies the user under whose account the AuthorizedPrincipalsCommand is run. It is recommended to use a dedicated user that has no other role on the host than running authorized principals commands. If AuthorizedPrincipalsCommand is specified but AuthorizedPrincipalsCommandUser is not, then sshd(8) will refuse to start.`,
Value: docvalues.UserValue("", true),
},
"AuthorizedPrincipalsFile": {
"authorizedprincipalsfile": {
Documentation: `Specifies a file that lists principal names that are accepted for certificate authentication. When using certificates signed by a key listed in TrustedUserCAKeys, this file lists names, one of which must appear in the certificate for it to be accepted for authentication. Names are listed one per line preceded by key options (as described in AUTHORIZED_KEYS FILE FORMAT in sshd(8)). Empty lines and comments starting with # are ignored.
Arguments to AuthorizedPrincipalsFile accept the tokens described in the TOKENS section. After expansion, AuthorizedPrincipalsFile is taken to be an absolute path or one relative to the user's home directory. The default is none, i.e. not to use a principals file in this case, the username of the user must appear in a certificate's principals list for it to be accepted.
Note that AuthorizedPrincipalsFile is only used when authentication proceeds using a CA listed in TrustedUserCAKeys and is not consulted for certification authorities trusted via ~/.ssh/authorized_keys, though the principals= key option offers a similar facility (see sshd(8) for details).`,
@ -146,13 +150,13 @@ See PATTERNS in ssh_config(5) for more information on patterns. This keyword may
RequiredType: docvalues.PathTypeFile,
},
},
"Banner": {
"banner": {
Documentation: `The contents of the specified file are sent to the remote user before authentication is allowed. If the argument is none then no banner is displayed. By default, no banner is displayed.`,
Value: docvalues.PathValue{
RequiredType: docvalues.PathTypeFile,
},
},
"CASignatureAlgorithms": {
"casignaturealgorithms": {
Documentation: `Specifies which algorithms are allowed for signing of certificates by certificate authorities (CAs). The default is:
ssh-ed25519,ecdsa-sha2-nistp256, ecdsa-sha2-nistp384,ecdsa-sha2-nistp521, sk-ssh-ed25519@openssh.com, sk-ecdsa-sha2-nistp256@openssh.com, rsa-sha2-512,rsa-sha2-256
If the specified list begins with a + character, then the specified algorithms will be appended to the default set instead of replacing them. If the specified list begins with a - character, then the specified algorithms (including wildcards) will be removed from the default set instead of replacing them.
@ -171,12 +175,13 @@ See PATTERNS in ssh_config(5) for more information on patterns. This keyword may
SubValue: docvalues.ArrayValue{
Separator: ",",
DuplicatesExtractor: &docvalues.DuplicatesAllowedExtractor,
RespectQuotes: true,
// TODO: Add
SubValue: docvalues.StringValue{},
},
},
},
"ChannelTimeout": {
"channeltimeout": {
Documentation: `Specifies whether and how quickly sshd(8) should close inactive channels. Timeouts are specified as one or more type=interval pairs separated by whitespace, where the type must be the special keyword global or a channel type name from the list below, optionally containing wildcard characters.
The timeout value interval is specified in seconds or may use any of the units documented in the TIME FORMATS section. For example, session=5m would cause interactive sessions to terminate after five minutes of inactivity. Specifying a zero value disables the inactivity timeout.
The special timeout global applies to all active channels, taken together. Traffic on any active channel will reset the timeout, but when the timeout expires then all open channels will be closed. Note that this global timeout is not matched by wildcards and must be specified explicitly.
@ -195,6 +200,7 @@ See PATTERNS in ssh_config(5) for more information on patterns. This keyword may
Value: docvalues.ArrayValue{
Separator: " ",
DuplicatesExtractor: &channelTimeoutExtractor,
RespectQuotes: true,
SubValue: docvalues.KeyValueAssignmentValue{
ValueIsOptional: false,
Separator: "=",
@ -215,14 +221,14 @@ See PATTERNS in ssh_config(5) for more information on patterns. This keyword may
},
},
},
"ChrootDirectory": {
"chrootdirectory": {
Documentation: `Specifies the pathname of a directory to chroot(2) to after authentication. At session startup sshd(8) checks that all components of the pathname are root-owned directories which are not writable by group or others. After the chroot, sshd(8) changes the working directory to the user's home directory. Arguments to ChrootDirectory accept the tokens described in the TOKENS section.
The ChrootDirectory must contain the necessary files and directories to support the user's session. For an interactive session this requires at least a shell, typically sh(1), and basic /dev nodes such as null(4), zero(4), stdin(4), stdout(4), stderr(4), and tty(4) devices. For file transfer sessions using SFTP no additional configuration of the environment is necessary if the in-process sftp-server is used, though sessions which use logging may require /dev/log inside the chroot directory on some operating systems (see sftp-server(8) for details).
For safety, it is very important that the directory hierarchy be prevented from modification by other processes on the system (especially those outside the jail). Misconfiguration can lead to unsafe environments which sshd(8) cannot detect.
The default is none, indicating not to chroot(2).`,
Value: docvalues.StringValue{},
},
"Ciphers": {
"ciphers": {
Documentation: `Specifies the ciphers allowed. Multiple ciphers must be comma-separated. If the specified list begins with a + character, then the specified ciphers will be appended to the default set instead of replacing them. If the specified list begins with a - character, then the specified ciphers (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a ^ character, then the specified ciphers will be placed at the head of the default set.
The supported ciphers are:
3des-cbc aes128-cbc aes192-cbc aes256-cbc aes128-ctr aes192-ctr aes256-ctr aes128-gcm@openssh.com aes256-gcm@openssh.com chacha20-poly1305@openssh.com
@ -242,16 +248,16 @@ See PATTERNS in ssh_config(5) for more information on patterns. This keyword may
docvalues.CreateEnumString("chacha20-poly1305@openssh.com"),
}),
},
"ClientAliveCountMax": {
"clientalivecountmax": {
Documentation: `Sets the number of client alive messages which may be sent without sshd(8) receiving any messages back from the client. If this threshold is reached while client alive messages are being sent, sshd will disconnect the client, terminating the session. It is important to note that the use of client alive messages is very different from TCPKeepAlive. The client alive messages are sent through the encrypted channel and therefore will not be spoofable. The TCP keepalive option enabled by TCPKeepAlive is spoofable. The client alive mechanism is valuable when the client or server depend on knowing when a connection has become unresponsive.
The default value is 3. If ClientAliveInterval is set to 15, and ClientAliveCountMax is left at the default, unresponsive SSH clients will be disconnected after approximately 45 seconds. Setting a zero ClientAliveCountMax disables connection termination.`,
Value: docvalues.NumberValue{Min: &ZERO},
},
"ClientAliveInterval": {
"clientaliveinterval": {
Documentation: `Sets a timeout interval in seconds after which if no data has been received from the client, sshd(8) will send a message through the encrypted channel to request a response from the client. The default is 0, indicating that these messages will not be sent to the client.`,
Value: docvalues.NumberValue{Min: &ZERO},
},
"Compression": {
"compression": {
Documentation: `Specifies whether compression is enabled after the user has authenticated successfully. The argument must be yes, delayed (a legacy synonym for yes) or no. The default is yes.`,
Value: docvalues.EnumValue{
EnforceValues: true,
@ -262,25 +268,25 @@ See PATTERNS in ssh_config(5) for more information on patterns. This keyword may
},
},
},
"DenyGroups": {
"denygroups": {
Documentation: `This keyword can be followed by a list of group name patterns, separated by spaces. Login is disallowed for users whose primary group or supplementary group list matches one of the patterns. Only group names are valid; a numerical group ID is not recognized. By default, login is allowed for all groups. The allow/deny groups directives are processed in the following order: DenyGroups, AllowGroups.
See PATTERNS in ssh_config(5) for more information on patterns. This keyword may appear multiple times in sshd_config with each instance appending to the list.`,
Value: docvalues.GroupValue(" ", false),
},
"DenyUsers": {
"denyusers": {
Documentation: `This keyword can be followed by a list of user name patterns, separated by spaces. Login is disallowed for user names that match one of the patterns. Only user names are valid; a numerical user ID is not recognized. By default, login is allowed for all users. If the pattern takes the form USER@HOST then USER and HOST are separately checked, restricting logins to particular users from particular hosts. HOST criteria may additionally contain addresses to match in CIDR address/masklen format. The allow/deny users directives are processed in the following order: DenyUsers, AllowUsers.
See PATTERNS in ssh_config(5) for more information on patterns. This keyword may appear multiple times in sshd_config with each instance appending to the list.`,
Value: docvalues.UserValue(" ", false),
},
"DisableForwarding": {
"disableforwarding": {
Documentation: `Disables all forwarding features, including X11, ssh-agent(1), TCP and StreamLocal. This option overrides all other forwarding-related options and may simplify restricted configurations.`,
Value: booleanEnumValue,
},
"ExposeAuthInfo": {
"exposeauthinfo": {
Documentation: `Writes a temporary file containing a list of authentication methods and public credentials (e.g. keys) used to authenticate the user. The location of the file is exposed to the user session through the SSH_USER_AUTH environment variable. The default is no.`,
Value: booleanEnumValue,
},
"FingerprintHash": {
"fingerprinthash": {
Documentation: `Specifies the hash algorithm used when logging key fingerprints. Valid options are: md5 and sha256. The default is sha256.`,
Value: docvalues.EnumValue{
EnforceValues: true,
@ -290,27 +296,27 @@ See PATTERNS in ssh_config(5) for more information on patterns. This keyword may
},
},
},
"ForceCommand": {
"forcecommand": {
Documentation: `Forces the execution of the command specified by ForceCommand, ignoring any command supplied by the client and ~/.ssh/rc if present. The command is invoked by using the user's login shell with the -c option. This applies to shell, command, or subsystem execution. It is most useful inside a Match block. The command originally supplied by the client is available in the SSH_ORIGINAL_COMMAND environment variable. Specifying a command of internal-sftp will force the use of an in- process SFTP server that requires no support files when used with ChrootDirectory. The default is none.`,
Value: docvalues.StringValue{},
},
"GatewayPorts": {
"gatewayports": {
Documentation: `Specifies whether remote hosts are allowed to connect to ports forwarded for the client. By default, sshd(8) binds remote port forwardings to the loopback address. This prevents other remote hosts from connecting to forwarded ports. GatewayPorts can be used to specify that sshd should allow remote port forwardings to bind to non-loopback addresses, thus allowing other hosts to connect. The argument may be no to force remote port forwardings to be available to the local host only, yes to force remote port forwardings to bind to the wildcard address, or clientspecified to allow the client to select the address to which the forwarding is bound. The default is no.`,
Value: booleanEnumValue,
},
"GSSAPIAuthentication": {
"gssapiauthentication": {
Documentation: `Specifies whether user authentication based on GSSAPI is allowed. The default is no.`,
Value: booleanEnumValue,
},
"GSSAPICleanupCredentials": {
"gssapicleanupcredentials": {
Documentation: `Specifies whether to automatically destroy the user's credentials cache on logout. The default is yes.`,
Value: booleanEnumValue,
},
"GSSAPIStrictAcceptorCheck": {
"gssapistrictacceptorcheck": {
Documentation: `Determines whether to be strict about the identity of the GSSAPI acceptor a client authenticates against. If set to yes then the client must authenticate against the host service on the current hostname. If set to no then the client may authenticate against any service key stored in the machine's default store. This facility is provided to assist with operation on multi homed machines. The default is yes.`,
Value: booleanEnumValue,
},
"HostbasedAcceptedAlgorithms": {
"hostbasedacceptedalgorithms": {
Documentation: `Specifies the signature algorithms that will be accepted for hostbased authentication as a list of comma-separated patterns. Alternately if the specified list begins with a + character, then the specified signature algorithms will be appended to the default set instead of replacing them. If the specified list begins with a - character, then the specified signature algorithms (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a ^ character, then the specified signature algorithms will be placed at the head of the default set. The default for this option is:
ssh-ed25519-cert-v01@openssh.com, ecdsa-sha2-nistp256-cert-v01@openssh.com, ecdsa-sha2-nistp384-cert-v01@openssh.com, ecdsa-sha2-nistp521-cert-v01@openssh.com, sk-ssh-ed25519-cert-v01@openssh.com, sk-ecdsa-sha2-nistp256-cert-v01@openssh.com, rsa-sha2-512-cert-v01@openssh.com, rsa-sha2-256-cert-v01@openssh.com, ssh-ed25519, ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521, sk-ssh-ed25519@openssh.com, sk-ecdsa-sha2-nistp256@openssh.com, rsa-sha2-512,rsa-sha2-256
The list of available signature algorithms may also be obtained using "ssh -Q HostbasedAcceptedAlgorithms". This was formerly named HostbasedAcceptedKeyTypes.`,
@ -327,25 +333,25 @@ See PATTERNS in ssh_config(5) for more information on patterns. This keyword may
},
},
},
"HostbasedAuthentication": {
"hostbasedauthentication": {
Documentation: `Specifies whether rhosts or /etc/hosts.equiv authentication together with successful public key client host authentication is allowed (host-based authentication). The default is no.`,
Value: booleanEnumValue,
},
"HostbasedUsesNameFromPacketOnly": {
"hostbasedusesnamefrompacketonly": {
Documentation: `Specifies whether or not the server will attempt to perform a reverse name lookup when matching the name in the ~/.shosts, ~/.rhosts, and /etc/hosts.equiv files during HostbasedAuthentication. A setting of yes means that sshd(8) uses the name supplied by the client rather than attempting to resolve the name from the TCP connection itself. The default is no.`,
Value: booleanEnumValue,
},
"HostCertificate": {
"hostcertificate": {
Documentation: `Specifies a file containing a public host certificate. The certificate's public key must match a private host key already specified by HostKey. The default behaviour of sshd(8) is not to load any certificates.`,
Value: docvalues.PathValue{},
},
"HostKey": {
"hostkey": {
Documentation: `Specifies a file containing a private host key used by SSH. The defaults are /etc/ssh/ssh_host_ecdsa_key, /etc/ssh/ssh_host_ed25519_key and /etc/ssh/ssh_host_rsa_key.
Note that sshd(8) will refuse to use a file if it is group/world-accessible and that the HostKeyAlgorithms option restricts which of the keys are actually used by sshd(8).
It is possible to have multiple host key files. It is also possible to specify public host key files instead. In this case operations on the private key will be delegated to an ssh-agent(1).`,
Value: docvalues.PathValue{},
},
"HostKeyAgent": {
"hostkeyagent": {
Documentation: `Identifies the UNIX-domain socket used to communicate with an agent that has access to the private host keys. If the string "SSH_AUTH_SOCK" is specified, the location of the socket will be read from the SSH_AUTH_SOCK environment variable.`,
Value: docvalues.OrValue{
Values: []docvalues.DeprecatedValue{
@ -359,7 +365,7 @@ See PATTERNS in ssh_config(5) for more information on patterns. This keyword may
},
},
},
"HostKeyAlgorithms": {
"hostkeyalgorithms": {
Documentation: `Specifies the host key signature algorithms that the server offers. The default for this option is:
ssh-ed25519-cert-v01@openssh.com, ecdsa-sha2-nistp256-cert-v01@openssh.com, ecdsa-sha2-nistp384-cert-v01@openssh.com, ecdsa-sha2-nistp521-cert-v01@openssh.com, sk-ssh-ed25519-cert-v01@openssh.com, sk-ecdsa-sha2-nistp256-cert-v01@openssh.com, rsa-sha2-512-cert-v01@openssh.com, rsa-sha2-256-cert-v01@openssh.com, ssh-ed25519, ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521, sk-ssh-ed25519@openssh.com, sk-ecdsa-sha2-nistp256@openssh.com, rsa-sha2-512,rsa-sha2-256
The list of available signature algorithms may also be obtained using "ssh -Q HostKeyAlgorithms".`,
@ -371,7 +377,7 @@ See PATTERNS in ssh_config(5) for more information on patterns. This keyword may
},
},
},
"IgnoreRhosts": {
"ignorerhosts": {
Documentation: `Specifies whether to ignore per-user .rhosts and .shosts files during HostbasedAuthentication. The system-wide /etc/hosts.equiv and /etc/shosts.equiv are still used regardless of this setting.
Accepted values are yes (the default) to ignore all per- user files, shosts-only to allow the use of .shosts but to ignore .rhosts or no to allow both .shosts and rhosts.`,
Value: docvalues.EnumValue{
@ -383,21 +389,22 @@ See PATTERNS in ssh_config(5) for more information on patterns. This keyword may
},
},
},
"IgnoreUserKnownHosts": {
"ignoreuserknownhosts": {
Documentation: `Specifies whether sshd(8) should ignore the user's ~/.ssh/known_hosts during HostbasedAuthentication and use only the system-wide known hosts file /etc/ssh/ssh_known_hosts. The default is “no”.`,
Value: booleanEnumValue,
},
"Include": {
"include": {
Documentation: `Include the specified configuration file(s). Multiple pathnames may be specified and each pathname may contain glob(7) wildcards that will be expanded and processed in lexical order. Files without absolute paths are assumed to be in /etc/ssh. An Include directive may appear inside a Match block to perform conditional inclusion.`,
Value: docvalues.ArrayValue{
Separator: " ",
DuplicatesExtractor: &docvalues.SimpleDuplicatesExtractor,
RespectQuotes: true,
SubValue: docvalues.StringValue{},
},
// TODO: Add extra check
},
"IPQoS": {
"ipqos": {
Documentation: `Specifies the IPv4 type-of-service or DSCP class for the connection. Accepted values are af11, af12, af13, af21, af22, af23, af31, af32, af33, af41, af42, af43, cs0, cs1, cs2, cs3, cs4, cs5, cs6, cs7, ef, le, lowdelay, throughput, reliability, a numeric value, or none to use the operating system default. This option may take one or two arguments, separated by whitespace. If one argument is specified, it is used as the packet class unconditionally. If two values are specified, the first is automatically selected for interactive sessions and the second for non-interactive sessions. The default is af21 (Low-Latency Data) for interactive sessions and cs1 (Lower Effort) for non-interactive sessions.`,
Value: docvalues.OrValue{
Values: []docvalues.DeprecatedValue{
@ -408,7 +415,9 @@ See PATTERNS in ssh_config(5) for more information on patterns. This keyword may
},
},
docvalues.ArrayValue{
Separator: " ",
Separator: " ",
DuplicatesExtractor: &docvalues.SimpleDuplicatesExtractor,
RespectQuotes: true,
SubValue: docvalues.EnumValue{
EnforceValues: true,
Values: []docvalues.EnumString{
@ -444,27 +453,27 @@ See PATTERNS in ssh_config(5) for more information on patterns. This keyword may
},
},
},
"KbdInteractiveAuthentication": {
"kbdinteractiveauthentication": {
Documentation: `Specifies whether to allow keyboard-interactive authentication. All authentication styles from login.conf(5) are supported. The default is yes. The argument to this keyword must be yes or no. ChallengeResponseAuthentication is a deprecated alias for this.`,
Value: booleanEnumValue,
},
"KerberosAuthentication": {
"kerberosauthentication": {
Documentation: `Specifies whether the password provided by the user for PasswordAuthentication will be validated through the Kerberos KDC. To use this option, the server needs a Kerberos servtab which allows the verification of the KDC's identity. The default is no.`,
Value: booleanEnumValue,
},
"KerberosGetAFSToken": {
"kerberosgetafstoken": {
Documentation: `If AFS is active and the user has a Kerberos 5 TGT, attempt to acquire an AFS token before accessing the user's home directory. The default is no.`,
Value: booleanEnumValue,
},
"KerberosOrLocalPasswd": {
"kerberosorlocalpasswd": {
Documentation: `If password authentication through Kerberos fails then the password will be validated via any additional local mechanism such as /etc/passwd. The default is yes.`,
Value: booleanEnumValue,
},
"KerberosTicketCleanup": {
"kerberosticketcleanup": {
Documentation: `Specifies whether to automatically destroy the user's ticket cache file on logout. The default is yes.`,
Value: booleanEnumValue,
},
"KexAlgorithms": {
"kexalgorithms": {
Documentation: `Specifies the available KEX (Key Exchange) algorithms. Multiple algorithms must be comma-separated. Alternately if the specified list begins with a + character, then the specified algorithms will be appended to the default set instead of replacing them. If the specified list begins with a - character, then the specified algorithms (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a ^ character, then the specified algorithms will be placed at the head of the default set. The supported algorithms are:
curve25519-sha256 curve25519-sha256@libssh.org diffie-hellman-group1-sha1 diffie-hellman-group14-sha1 diffie-hellman-group14-sha256 diffie-hellman-group16-sha512 diffie-hellman-group18-sha512 diffie-hellman-group-exchange-sha1 diffie-hellman-group-exchange-sha256 ecdh-sha2-nistp256 ecdh-sha2-nistp384 ecdh-sha2-nistp521 sntrup761x25519-sha512@openssh.com
The default is:
@ -486,7 +495,7 @@ See PATTERNS in ssh_config(5) for more information on patterns. This keyword may
docvalues.CreateEnumString("sntrup761x25519-sha512@openssh.com"),
}),
},
"ListenAddress": {
"listenaddress": {
Documentation: `Specifies the local addresses sshd(8) should listen on. The following forms may be used:
ListenAddress hostname|address [rdomain domain] ListenAddress hostname:port [rdomain domain] ListenAddress IPv4_address:port [rdomain domain] ListenAddress [hostname|address]:port [rdomain domain]
The optional rdomain qualifier requests sshd(8) listen in an explicit routing domain. If port is not specified, sshd will listen on the address and all Port options specified. The default is to listen on all local addresses on the current default routing domain. Multiple ListenAddress options are permitted. For more information on routing domains, see rdomain(4).`,
@ -502,11 +511,11 @@ See PATTERNS in ssh_config(5) for more information on patterns. This keyword may
Value: docvalues.NumberValue{Min: &ZERO, Max: &MAX_PORT},
},
},
"LoginGraceTime": {
"logingracetime": {
Documentation: `The server disconnects after this time if the user has not successfully logged in. If the value is 0, there is no time limit. The default is 120 seconds.`,
Value: docvalues.TimeFormatValue{},
},
"LogLevel": {
"loglevel": {
Documentation: `Gives the verbosity level that is used when logging messages from sshd(8). The possible values are: QUIET, FATAL, ERROR, INFO, VERBOSE, DEBUG, DEBUG1, DEBUG2, and DEBUG3. The default is INFO. DEBUG and DEBUG1 are equivalent. DEBUG2 and DEBUG3 each specify higher levels of debugging output. Logging with a DEBUG level violates the privacy of users and is not recommended.`,
Value: docvalues.EnumValue{
EnforceValues: true,
@ -523,14 +532,14 @@ See PATTERNS in ssh_config(5) for more information on patterns. This keyword may
},
},
},
"LogVerbose": {
"logverbose": {
Documentation: `Specify one or more overrides to LogLevel. An override consists of a pattern lists that matches the source file, function and line number to force detailed logging for. For example, an override pattern of:
kex.c:*:1000,*:kex_exchange_identification():*,packet.c:*
would enable detailed logging for line 1000 of kex.c, everything in the kex_exchange_identification() function, and all code in the packet.c file. This option is intended for debugging and no overrides are enabled by default.`,
Value: docvalues.StringValue{},
},
"MACs": {
"macs": {
Documentation: `Specifies the available MAC (message authentication code) algorithms. The MAC algorithm is used for data integrity protection. Multiple algorithms must be comma-separated. If the specified list begins with a + character, then the specified algorithms will be appended to the default set instead of replacing them. If the specified list begins with a - character, then the specified algorithms (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a ^ character, then the specified algorithms will be placed at the head of the default set.
The algorithms that contain "-etm" calculate the MAC after encryption (encrypt-then-mac). These are considered safer and their use recommended. The supported MACs are:
hmac-md5 hmac-md5-96 hmac-sha1 hmac-sha1-96 hmac-sha2-256 hmac-sha2-512 umac-64@openssh.com umac-128@openssh.com hmac-md5-etm@openssh.com hmac-md5-96-etm@openssh.com hmac-sha1-etm@openssh.com hmac-sha1-96-etm@openssh.com hmac-sha2-256-etm@openssh.com hmac-sha2-512-etm@openssh.com umac-64-etm@openssh.com umac-128-etm@openssh.com
@ -558,7 +567,7 @@ See PATTERNS in ssh_config(5) for more information on patterns. This keyword may
}),
},
"Match": {
"match": {
Documentation: `Introduces a conditional block. If all of the criteria on the Match line are satisfied, the keywords on the following lines override those set in the global section of the config file, until either another Match line or the end of the file. If a keyword appears in multiple Match blocks that are satisfied, only the first instance of the keyword is applied.
The arguments to Match are one or more criteria-pattern pairs or the single token All which matches all criteria. The available criteria are User, Group, Host, LocalAddress, LocalPort, RDomain, and Address (with RDomain representing the rdomain(4) on which the connection was received).
The match patterns may consist of single entries or comma-separated lists and may use the wildcard and negation operators described in the PATTERNS section of ssh_config(5).
@ -566,15 +575,15 @@ The patterns in an Address criteria may additionally contain addresses to match
Only a subset of keywords may be used on the lines following a Match keyword. Available keywords are AcceptEnv, AllowAgentForwarding, AllowGroups, AllowStreamLocalForwarding, AllowTcpForwarding, AllowUsers, AuthenticationMethods, AuthorizedKeysCommand, AuthorizedKeysCommandUser, AuthorizedKeysFile, AuthorizedPrincipalsCommand, AuthorizedPrincipalsCommandUser, AuthorizedPrincipalsFile, Banner, CASignatureAlgorithms, ChannelTimeout, ChrootDirectory, ClientAliveCountMax, ClientAliveInterval, DenyGroups, DenyUsers, DisableForwarding, ExposeAuthInfo, ForceCommand, GatewayPorts, GSSAPIAuthentication, HostbasedAcceptedAlgorithms, HostbasedAuthentication, HostbasedUsesNameFromPacketOnly, IgnoreRhosts, Include, IPQoS, KbdInteractiveAuthentication, KerberosAuthentication, LogLevel, MaxAuthTries, MaxSessions, PasswordAuthentication, PermitEmptyPasswords, PermitListen, PermitOpen, PermitRootLogin, PermitTTY, PermitTunnel, PermitUserRC, PubkeyAcceptedAlgorithms, PubkeyAuthentication, PubkeyAuthOptions, RekeyLimit, RevokedKeys, RDomain, SetEnv, StreamLocalBindMask, StreamLocalBindUnlink, TrustedUserCAKeys, UnusedConnectionTimeout, X11DisplayOffset, X11Forwarding and X11UseLocalhost.`,
Value: docvalues.StringValue{},
},
"MaxAuthTries": {
"maxauthtries": {
Documentation: `Specifies the maximum number of authentication attempts permitted per connection. Once the number of failures reaches half this value, additional failures are logged. The default is 6.`,
Value: docvalues.NumberValue{Min: &ZERO},
},
"MaxSessions": {
"maxsessions": {
Documentation: `Specifies the maximum number of open shell, login or subsystem (e.g. sftp) sessions permitted per network connection. Multiple sessions may be established by clients that support connection multiplexing. Setting MaxSessions to 1 will effectively disable session multiplexing, whereas setting it to 0 will prevent all shell, login and subsystem sessions while still permitting forwarding. The default is 10.`,
Value: docvalues.NumberValue{Min: &ZERO},
},
"MaxStartups": {
"maxstartups": {
Documentation: `Specifies the maximum number of concurrent unauthenticated connections to the SSH daemon. Additional connections will be dropped until authentication succeeds or the LoginGraceTime expires for a connection. The default is 10:30:100.
Alternatively, random early drop can be enabled by specifying the three colon separated values start:rate:full (e.g. "10:30:60"). sshd(8) will refuse connection attempts with a probability of rate/100 (30%) if there are currently start (10) unauthenticated connections. The probability increases linearly and all connection attempts are refused if the number of unauthenticated connections reaches full (60).`,
// TODO: Add custom value `SeapartorValue` that takes an array of values and separators
@ -582,27 +591,28 @@ Only a subset of keywords may be used on the lines following a Match keyword. Av
Regex: *regexp.MustCompile(`^(\d+):(\d+):(\d+)$`),
},
},
"ModuliFile": {
"modulifile": {
Documentation: `Specifies the moduli(5) file that contains the Diffie- Hellman groups used for the “diffie-hellman-group-exchange-sha1” and “diffie-hellman-group-exchange-sha256” key exchange methods. The default is /etc/moduli.`,
Value: docvalues.PathValue{
RequiredType: docvalues.PathTypeFile,
},
},
"PasswordAuthentication": {
"passwordauthentication": {
Documentation: `Specifies whether password authentication is allowed. The default is yes.`,
Value: booleanEnumValue,
},
"PermitEmptyPasswords": {
"permitemptypasswords": {
Documentation: `When password authentication is allowed, it specifies whether the server allows login to accounts with empty password strings. The default is no.`,
Value: booleanEnumValue,
},
"PermitListen": {
"permitlisten": {
Documentation: `Specifies the addresses/ports on which a remote TCP port forwarding may listen. The listen specification must be one of the following forms:
PermitListen port PermitListen host:port
Multiple permissions may be specified by separating them with whitespace. An argument of any can be used to remove all restrictions and permit any listen requests. An argument of none can be used to prohibit all listen requests. The host name may contain wildcards as described in the PATTERNS section in ssh_config(5). The wildcard * can also be used in place of a port number to allow all ports. By default all port forwarding listen requests are permitted. Note that the GatewayPorts option may further restrict which addresses may be listened on. Note also that ssh(1) will request a listen host of localhost if no listen host was specifically requested, and this name is treated differently to explicit localhost addresses of 127.0.0.1 and ::1.`,
Value: docvalues.ArrayValue{
Separator: " ",
DuplicatesExtractor: &docvalues.SimpleDuplicatesExtractor,
RespectQuotes: true,
SubValue: docvalues.KeyValueAssignmentValue{
ValueIsOptional: true,
Key: docvalues.IPAddressValue{
@ -630,13 +640,14 @@ Only a subset of keywords may be used on the lines following a Match keyword. Av
},
},
},
"PermitOpen": {
"permitopen": {
Documentation: `Specifies the destinations to which TCP port forwarding is permitted. The forwarding specification must be one of the following forms:
PermitOpen host:port PermitOpen IPv4_addr:port PermitOpen [IPv6_addr]:port
Multiple forwards may be specified by separating them with whitespace. An argument of any can be used to remove all restrictions and permit any forwarding requests. An argument of none can be used to prohibit all forwarding requests. The wildcard * can be used for host or port to allow all hosts or ports respectively. Otherwise, no pattern matching or address lookups are performed on supplied names. By default all port forwarding requests are permitted.`,
Value: docvalues.ArrayValue{
Separator: " ",
DuplicatesExtractor: &docvalues.SimpleDuplicatesExtractor,
RespectQuotes: true,
SubValue: docvalues.KeyValueAssignmentValue{
ValueIsOptional: true,
Key: docvalues.OrValue{
@ -677,7 +688,7 @@ Only a subset of keywords may be used on the lines following a Match keyword. Av
},
},
},
"PermitRootLogin": {
"permitrootlogin": {
Documentation: `Specifies whether root can log in using ssh(1). The argument must be yes, prohibit-password, forced-commands-only, or no. The default is prohibit-password.
If this option is set to prohibit-password (or its deprecated alias, without-password), password and keyboard-interactive authentication are disabled for root.
If this option is set to forced-commands-only, root login with public key authentication will be allowed, but only if the command option has been specified (which may be useful for taking remote backups even if root login is normally not allowed). All other authentication methods are disabled for root.
@ -692,11 +703,11 @@ Only a subset of keywords may be used on the lines following a Match keyword. Av
},
},
},
"PermitTTY": {
"permittty": {
Documentation: `Specifies whether pty(4) allocation is permitted. The default is yes.`,
Value: booleanEnumValue,
},
"PermitTunnel": {
"permittunnel": {
Documentation: `Specifies whether tun(4) device forwarding is allowed. The argument must be yes, point-to-point (layer 3), ethernet (layer 2), or no. Specifying yes permits both point-to-point and ethernet. The default is no.
Independent of this setting, the permissions of the selected tun(4) device must allow access to the user.`,
Value: docvalues.EnumValue{
@ -709,7 +720,7 @@ Only a subset of keywords may be used on the lines following a Match keyword. Av
},
},
},
"PermitUserEnvironment": {
"permituserenvironment": {
Documentation: `Specifies whether ~/.ssh/environment and environment= options in ~/.ssh/authorized_keys are processed by sshd(8). Valid options are yes, no or a pattern-list specifying which environment variable names to accept (for example "LANG,LC_*"). The default is no. Enabling environment processing may enable users to bypass access restrictions in some configurations using mechanisms such as LD_PRELOAD.`,
Value: docvalues.OrValue{
Values: []docvalues.DeprecatedValue{
@ -722,16 +733,17 @@ Only a subset of keywords may be used on the lines following a Match keyword. Av
docvalues.ArrayValue{
SubValue: docvalues.StringValue{},
Separator: ",",
RespectQuotes: true,
DuplicatesExtractor: &docvalues.DuplicatesAllowedExtractor,
},
},
},
},
"PermitUserRC": {
"permituserrc": {
Documentation: `Specifies whether any ~/.ssh/rc file is executed. The default is yes.`,
Value: booleanEnumValue,
},
"PerSourceMaxStartups": {
"persourcemaxstartups": {
Documentation: `Specifies the number of unauthenticated connections allowed from a given source address, or “none” if there is no limit. This limit is applied in addition to MaxStartups, whichever is lower. The default is none.`,
Value: docvalues.OrValue{
Values: []docvalues.DeprecatedValue{
@ -749,7 +761,7 @@ Only a subset of keywords may be used on the lines following a Match keyword. Av
},
},
},
"PerSourceNetBlockSize": {
"persourcenetblocksize": {
Documentation: `Specifies the number of bits of source address that are grouped together for the purposes of applying PerSourceMaxStartups limits. Values for IPv4 and optionally IPv6 may be specified, separated by a colon. The default is 32:128, which means each address is considered individually.`,
Value: docvalues.KeyValueAssignmentValue{
Separator: ":",
@ -758,24 +770,24 @@ Only a subset of keywords may be used on the lines following a Match keyword. Av
Value: docvalues.NumberValue{Min: &ZERO},
},
},
"PidFile": {
"pidfile": {
Documentation: `Specifies the file that contains the process ID of the SSH daemon, or none to not write one. The default is /var/run/sshd.pid.`,
Value: docvalues.StringValue{},
},
"Port": {
"port": {
Documentation: `Specifies the port number that sshd(8) listens on. The default is 22. Multiple options of this type are permitted. See also ListenAddress.`,
Value: docvalues.NumberValue{Min: &ZERO, Max: &MAX_PORT},
},
"PrintLastLog": {
"printlastlog": {
Documentation: `Specifies whether sshd(8) should print the date and time of the last user login when a user logs in interactively. The default is yes.`,
Value: booleanEnumValue,
},
"PrintMotd": {
"printmotd": {
Documentation: `Specifies whether sshd(8) should print /etc/motd when a user logs in interactively. (On some systems it is also printed by the shell, /etc/profile, or equivalent.) The default is yes.`,
Value: booleanEnumValue,
},
"PubkeyAcceptedAlgorithms": {
"pubkeyacceptedalgorithms": {
Documentation: `Specifies the signature algorithms that will be accepted for public key authentication as a list of comma- separated patterns. Alternately if the specified list begins with a + character, then the specified algorithms will be appended to the default set instead of replacing them. If the specified list begins with a - character, then the specified algorithms (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a ^ character, then the specified algorithms will be placed at the head of the default set. The default for this option is:
ssh-ed25519-cert-v01@openssh.com, ecdsa-sha2-nistp256-cert-v01@openssh.com, ecdsa-sha2-nistp384-cert-v01@openssh.com, ecdsa-sha2-nistp521-cert-v01@openssh.com, sk-ssh-ed25519-cert-v01@openssh.com, sk-ecdsa-sha2-nistp256-cert-v01@openssh.com, rsa-sha2-512-cert-v01@openssh.com, rsa-sha2-256-cert-v01@openssh.com, ssh-ed25519, ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521, sk-ssh-ed25519@openssh.com, sk-ecdsa-sha2-nistp256@openssh.com, rsa-sha2-512,rsa-sha2-256
The list of available signature algorithms may also be obtained using "ssh -Q PubkeyAcceptedAlgorithms".`,
@ -787,13 +799,15 @@ Only a subset of keywords may be used on the lines following a Match keyword. Av
},
},
},
"PubkeyAuthOptions": {
"pubkeyauthoptions": {
Documentation: `Sets one or more public key authentication options. The supported keywords are: none (the default; indicating no additional options are enabled), touch-required and verify-required.
The touch-required option causes public key authentication using a FIDO authenticator algorithm (i.e. ecdsa-sk or ed25519-sk) to always require the signature to attest that a physically present user explicitly confirmed the authentication (usually by touching the authenticator). By default, sshd(8) requires user presence unless overridden with an authorized_keys option. The touch-required flag disables this override.
The verify-required option requires a FIDO key signature attest that the user was verified, e.g. via a PIN.
Neither the touch-required or verify-required options have any effect for other, non-FIDO, public key types.`,
Value: docvalues.ArrayValue{
Separator: ",",
Separator: ",",
DuplicatesExtractor: &docvalues.SimpleDuplicatesExtractor,
RespectQuotes: true,
SubValue: docvalues.EnumValue{
EnforceValues: true,
Values: []docvalues.EnumString{
@ -804,11 +818,11 @@ Only a subset of keywords may be used on the lines following a Match keyword. Av
},
},
},
"PubkeyAuthentication": {
"pubkeyauthentication": {
Documentation: `Specifies whether public key authentication is allowed. The default is yes.`,
Value: booleanEnumValue,
},
"RekeyLimit": {
"rekeylimit": {
Documentation: `Specifies the maximum amount of data that may be transmitted or received before the session key is renegotiated, optionally followed by a maximum amount of time that may pass before the session key is renegotiated. The first argument is specified in bytes and may have a suffix of K, M, or G to indicate Kilobytes, Megabytes, or Gigabytes, respectively. The default is between 1G and 4G, depending on the cipher. The optional second value is specified in seconds and may use any of the units documented in the “TIME FORMATS” section. The default value for RekeyLimit is default none, which means that rekeying is performed after the cipher's default amount of data has been sent or received and no time based rekeying is done.`,
Value: docvalues.KeyValueAssignmentValue{
Separator: " ",
@ -817,15 +831,15 @@ Only a subset of keywords may be used on the lines following a Match keyword. Av
Value: docvalues.TimeFormatValue{},
},
},
"RequiredRSASize": {
"requiredrsasize": {
Documentation: `Specifies the minimum RSA key size (in bits) that sshd(8) will accept. User and host-based authentication keys smaller than this limit will be refused. The default is 1024 bits. Note that this limit may only be raised from the default.`,
Value: docvalues.NumberValue{Min: &ZERO},
},
"RevokedKeys": {
"revokedkeys": {
Documentation: `Specifies revoked public keys file, or none to not use one. Keys listed in this file will be refused for public key authentication. Note that if this file is not readable, then public key authentication will be refused for all users. Keys may be specified as a text file, listing one public key per line, or as an OpenSSH Key Revocation List (KRL) as generated by ssh-keygen(1). For more information on KRLs, see the KEY REVOCATION LISTS section in ssh-keygen(1).`,
Value: docvalues.StringValue{},
},
"RDomain": {
"rdomain": {
Documentation: `Specifies an explicit routing domain that is applied after authentication has completed. The user session, as well as any forwarded or listening IP sockets, will be bound to this rdomain(4). If the routing domain is set to %D, then the domain in which the incoming connection was received will be applied.`,
Value: docvalues.OrValue{
Values: []docvalues.DeprecatedValue{
@ -842,18 +856,19 @@ Only a subset of keywords may be used on the lines following a Match keyword. Av
},
},
},
"SecurityKeyProvider": {
"securitykeyprovider": {
Documentation: `Specifies a path to a library that will be used when loading FIDO authenticator-hosted keys, overriding the default of using the built-in USB HID support.`,
Value: docvalues.PathValue{
RequiredType: docvalues.PathTypeFile,
},
},
"SetEnv": {
"setenv": {
Documentation: `Specifies one or more environment variables to set in child sessions started by sshd(8) as “NAME=VALUE”. The environment value may be quoted (e.g. if it contains whitespace characters). Environment variables set by SetEnv override the default environment and any variables specified by the user via AcceptEnv or PermitUserEnvironment.`,
Value: docvalues.ArrayValue{
Separator: " ",
DuplicatesExtractor: &setEnvExtractor,
RespectQuotes: true,
SubValue: docvalues.KeyValueAssignmentValue{
ValueIsOptional: false,
Separator: "=",
@ -862,28 +877,28 @@ Only a subset of keywords may be used on the lines following a Match keyword. Av
},
},
},
"StreamLocalBindMask": {
"streamlocalbindmask": {
Documentation: `Sets the octal file creation mode mask (umask) used when creating a Unix-domain socket file for local or remote port forwarding. This option is only used for port forwarding to a Unix-domain socket file.
The default value is 0177, which creates a Unix-domain socket file that is readable and writable only by the owner. Note that not all operating systems honor the file mode on Unix-domain socket files.`,
Value: docvalues.NumberValue{Min: &ZERO, Max: &MAX_FILE_MODE},
},
"StreamLocalBindUnlink": {
"streamlocalbindunlink": {
Documentation: `Specifies whether to remove an existing Unix-domain socket file for local or remote port forwarding before creating a new one. If the socket file already exists and StreamLocalBindUnlink is not enabled, sshd will be unable to forward the port to the Unix-domain socket file. This option is only used for port forwarding to a Unix-domain socket file.
The argument must be yes or no. The default is no.`,
Value: booleanEnumValue,
},
"StrictModes": {
"strictmodes": {
Documentation: `Specifies whether sshd(8) should check file modes and ownership of the user's files and home directory before accepting login. This is normally desirable because novices sometimes accidentally leave their directory or files world-writable. The default is yes. Note that this does not apply to ChrootDirectory, whose permissions and ownership are checked unconditionally.`,
Value: booleanEnumValue,
},
"Subsystem": {
"subsystem": {
Documentation: `Configures an external subsystem (e.g. file transfer daemon). Arguments should be a subsystem name and a command (with optional arguments) to execute upon subsystem request.
The command sftp-server implements the SFTP file transfer subsystem.
Alternately the name internal-sftp implements an in- process SFTP server. This may simplify configurations using ChrootDirectory to force a different filesystem root on clients. It accepts the same command line arguments as sftp-server and even though it is in- process, settings such as LogLevel or SyslogFacility do not apply to it and must be set explicitly via command line arguments.
By default no subsystems are defined.`,
Value: docvalues.StringValue{},
},
"SyslogFacility": {
"syslogfacility": {
Documentation: `Gives the facility code that is used when logging messages from sshd(8). The possible values are: DAEMON, USER, AUTH, LOCAL0, LOCAL1, LOCAL2, LOCAL3, LOCAL4, LOCAL5, LOCAL6, LOCAL7. The default is AUTH.`,
Value: docvalues.EnumValue{
EnforceValues: true,
@ -902,35 +917,35 @@ Only a subset of keywords may be used on the lines following a Match keyword. Av
},
},
},
"TCPKeepAlive": {
"tcpkeepalive": {
Documentation: `Specifies whether the system should send TCP keepalive messages to the other side. If they are sent, death of the connection or crash of one of the machines will be properly noticed. However, this means that connections will die if the route is down temporarily, and some people find it annoying. On the other hand, if TCP keepalives are not sent, sessions may hang indefinitely on the server, leaving "ghost" users and consuming server resources.
The default is yes (to send TCP keepalive messages), and the server will notice if the network goes down or the client host crashes. This avoids infinitely hanging sessions.
To disable TCP keepalive messages, the value should be set to no.`,
Value: booleanEnumValue,
},
"TrustedUserCAKeys": {
"trustedusercakeys": {
Documentation: `Specifies a file containing public keys of certificate authorities that are trusted to sign user certificates for authentication, or none to not use one. Keys are listed one per line; empty lines and comments starting with # are allowed. If a certificate is presented for authentication and has its signing CA key listed in this file, then it may be used for authentication for any user listed in the certificate's principals list. Note that certificates that lack a list of principals will not be permitted for authentication using TrustedUserCAKeys. For more details on certificates, see the CERTIFICATES section in ssh-keygen(1).`,
Value: docvalues.StringValue{},
},
"UnusedConnectionTimeout": {
"unusedconnectiontimeout": {
Documentation: `Specifies whether and how quickly sshd(8) should close client connections with no open channels. Open channels include active shell, command execution or subsystem sessions, connected network, socket, agent or X11 forwardings. Forwarding listeners, such as those from the ssh(1) -R flag, are not considered as open channels and do not prevent the timeout. The timeout value is specified in seconds or may use any of the units documented in the TIME FORMATS section.
Note that this timeout starts when the client connection completes user authentication but before the client has an opportunity to open any channels. Caution should be used when using short timeout values, as they may not provide sufficient time for the client to request and open its channels before terminating the connection.
The default none is to never expire connections for having no open channels. This option may be useful in conjunction with ChannelTimeout.`,
Value: docvalues.TimeFormatValue{},
},
"UseDNS": {
"usedns": {
Documentation: `Specifies whether sshd(8) should look up the remote host name, and to check that the resolved host name for the remote IP address maps back to the very same IP address.
If this option is set to no (the default) then only addresses and not host names may be used in ~/.ssh/authorized_keys from and sshd_config Match Host directives.`,
Value: booleanEnumValue,
},
"UsePAM": {
"usepam": {
Documentation: `Enables the Pluggable Authentication Module interface. If set to yes this will enable PAM authentication using KbdInteractiveAuthentication and PasswordAuthentication in addition to PAM account and session module processing for all authentication types.
Because PAM keyboard-interactive authentication usually serves an equivalent role to password authentication, you should disable either PasswordAuthentication or KbdInteractiveAuthentication.
If UsePAM is enabled, you will not be able to run sshd(8) as a non-root user. The default is no.`,
Value: booleanEnumValue,
},
"VersionAddendum": {
"versionaddendum": {
Documentation: `Optionally specifies additional text to append to the SSH protocol banner sent by the server upon connection. The default is none.`,
Value: docvalues.OrValue{
Values: []docvalues.DeprecatedValue{
@ -944,21 +959,21 @@ Only a subset of keywords may be used on the lines following a Match keyword. Av
},
},
},
"X11DisplayOffset": {
"x11displayoffset": {
Documentation: `Specifies the first display number available for sshd(8)'s X11 forwarding. This prevents sshd from interfering with real X11 servers. The default is 10.`,
Value: docvalues.NumberValue{Min: &ZERO},
},
"X11Forwarding": {
"x11forwarding": {
Documentation: `Specifies whether X11 forwarding is permitted. The argument must be yes or no. The default is no.
When X11 forwarding is enabled, there may be additional exposure to the server and to client displays if the sshd(8) proxy display is configured to listen on the wildcard address (see X11UseLocalhost), though this is not the default. Additionally, the authentication spoofing and authentication data verification and substitution occur on the client side. The security risk of using X11 forwarding is that the client's X11 display server may be exposed to attack when the SSH client requests forwarding (see the warnings for ForwardX11 in ssh_config(5)). A system administrator may have a stance in which they want to protect clients that may expose themselves to attack by unwittingly requesting X11 forwarding, which can warrant a no setting.
Note that disabling X11 forwarding does not prevent users from forwarding X11 traffic, as users can always install their own forwarders.`,
Value: booleanEnumValue,
},
"X11UseLocalhost": {
"x11uselocalhost": {
Documentation: `Specifies whether sshd(8) should bind the X11 forwarding server to the loopback address or to the wildcard address. By default, sshd binds the forwarding server to the loopback address and sets the hostname part of the DISPLAY environment variable to localhost. This prevents remote hosts from connecting to the proxy display. However, some older X11 clients may not function with this configuration. X11UseLocalhost may be set to no to specify that the forwarding server should be bound to the wildcard address. The argument must be yes or no. The default is yes.`,
Value: booleanEnumValue,
},
"XAuthLocation": {
"xauthlocation": {
Documentation: `Specifies the full pathname of the xauth(1) program, or none to not use one. The default is /usr/X11R6/bin/xauth.`,
Value: docvalues.StringValue{},
},

View File

@ -0,0 +1,102 @@
package fields
var FieldsNameFormattedMap = map[NormalizedOptionName]string{
"acceptenv": "AcceptEnv",
"addressfamily": "AddressFamily",
"allowagentforwarding": "AllowAgentForwarding",
"allowgroups": "AllowGroups",
"allowstreamlocalforwarding": "AllowStreamLocalForwarding",
"allowtcpforwarding": "AllowTcpForwarding",
"allowusers": "AllowUsers",
"authenticationmethods": "AuthenticationMethods",
"authorizedkeyscommand": "AuthorizedKeysCommand",
"authorizedkeyscommanduser": "AuthorizedKeysCommandUser",
"authorizedkeysfile": "AuthorizedKeysFile",
"authorizedprincipalscommand": "AuthorizedPrincipalsCommand",
"authorizedprincipalscommanduser": "AuthorizedPrincipalsCommandUser",
"authorizedprincipalsfile": "AuthorizedPrincipalsFile",
"banner": "Banner",
"casignaturealgorithms": "CASignatureAlgorithms",
"channeltimeout": "ChannelTimeout",
"chrootdirectory": "ChrootDirectory",
"ciphers": "Ciphers",
"clientalivecountmax": "ClientAliveCountMax",
"clientaliveinterval": "ClientAliveInterval",
"compression": "Compression",
"denygroups": "DenyGroups",
"denyusers": "DenyUsers",
"disableforwarding": "DisableForwarding",
"exposeauthinfo": "ExposeAuthInfo",
"fingerprinthash": "FingerprintHash",
"forcecommand": "ForceCommand",
"gatewayports": "GatewayPorts",
"gssapiauthentication": "GSSAPIAuthentication",
"gssapicleanupcredentials": "GSSAPICleanupCredentials",
"gssapistrictacceptorcheck": "GSSAPIStrictAcceptorCheck",
"hostbasedacceptedalgorithms": "HostbasedAcceptedAlgorithms",
"hostbasedauthentication": "HostbasedAuthentication",
"hostbasedusesnamefrompacketonly": "HostbasedUsesNameFromPacketOnly",
"hostcertificate": "HostCertificate",
"hostkey": "HostKey",
"hostkeyagent": "HostKeyAgent",
"hostkeyalgorithms": "HostKeyAlgorithms",
"ignorerhosts": "IgnoreRhosts",
"ignoreuserknownhosts": "IgnoreUserKnownHosts",
"include": "Include",
"ipqos": "IPQoS",
"kbdinteractiveauthentication": "KbdInteractiveAuthentication",
"kerberosauthentication": "KerberosAuthentication",
"kerberosgetafstoken": "KerberosGetAFSToken",
"kerberosorlocalpasswd": "KerberosOrLocalPasswd",
"kerberosticketcleanup": "KerberosTicketCleanup",
"kexalgorithms": "KexAlgorithms",
"listenaddress": "ListenAddress",
"logingracetime": "LoginGraceTime",
"loglevel": "LogLevel",
"logverbose": "LogVerbose",
"macs": "MACs",
"match": "Match",
"maxauthtries": "MaxAuthTries",
"maxsessions": "MaxSessions",
"maxstartups": "MaxStartups",
"modulifile": "ModuliFile",
"passwordauthentication": "PasswordAuthentication",
"permitemptypasswords": "PermitEmptyPasswords",
"permitlisten": "PermitListen",
"permitopen": "PermitOpen",
"permitrootlogin": "PermitRootLogin",
"permittty": "PermitTTY",
"permittunnel": "PermitTunnel",
"permituserenvironment": "PermitUserEnvironment",
"permituserrc": "PermitUserRC",
"persourcemaxstartups": "PerSourceMaxStartups",
"persourcenetblocksize": "PerSourceNetBlockSize",
"pidfile": "PidFile",
"port": "Port",
"printlastlog": "PrintLastLog",
"printmotd": "PrintMotd",
"pubkeyacceptedalgorithms": "PubkeyAcceptedAlgorithms",
"pubkeyauthoptions": "PubkeyAuthOptions",
"pubkeyauthentication": "PubkeyAuthentication",
"rekeylimit": "RekeyLimit",
"requiredrsasize": "RequiredRSASize",
"revokedkeys": "RevokedKeys",
"rdomain": "RDomain",
"securitykeyprovider": "SecurityKeyProvider",
"setenv": "SetEnv",
"streamlocalbindmask": "StreamLocalBindMask",
"streamlocalbindunlink": "StreamLocalBindUnlink",
"strictmodes": "StrictModes",
"subsystem": "Subsystem",
"syslogfacility": "SyslogFacility",
"tcpkeepalive": "TCPKeepAlive",
"trustedusercakeys": "TrustedUserCAKeys",
"unusedconnectiontimeout": "UnusedConnectionTimeout",
"usedns": "UseDNS",
"usepam": "UsePAM",
"versionaddendum": "VersionAddendum",
"x11displayoffset": "X11DisplayOffset",
"x11forwarding": "X11Forwarding",
"x11uselocalhost": "X11UseLocalhost",
"xauthlocation": "XAuthLocation",
}

View File

@ -5,66 +5,66 @@ import (
matchparser "config-lsp/handlers/sshd_config/match-parser"
)
var MatchAllowedOptions = map[string]struct{}{
"AcceptEnv": {},
"AllowAgentForwarding": {},
"AllowGroups": {},
"AllowStreamLocalForwarding": {},
"AllowTcpForwarding": {},
"AllowUsers": {},
"AuthenticationMethods": {},
"AuthorizedKeysCommand": {},
"AuthorizedKeysCommandUser": {},
"AuthorizedKeysFile": {},
"AuthorizedPrincipalsCommand": {},
"AuthorizedPrincipalsCommandUser": {},
"AuthorizedPrincipalsFile": {},
"Banner": {},
"CASignatureAlgorithms": {},
"ChannelTimeout": {},
"ChrootDirectory": {},
"ClientAliveCountMax": {},
"ClientAliveInterval": {},
"DenyGroups": {},
"DenyUsers": {},
"DisableForwarding": {},
"ExposeAuthInfo": {},
"ForceCommand": {},
"GatewayPorts": {},
"GSSAPIAuthentication": {},
"HostbasedAcceptedAlgorithms": {},
"HostbasedAuthentication": {},
"HostbasedUsesNameFromPacketOnly": {},
"IgnoreRhosts": {},
"Include": {},
"IPQoS": {},
"KbdInteractiveAuthentication": {},
"KerberosAuthentication": {},
"LogLevel": {},
"MaxAuthTries": {},
"MaxSessions": {},
"PasswordAuthentication": {},
"PermitEmptyPasswords": {},
"PermitListen": {},
"PermitOpen": {},
"PermitRootLogin": {},
"PermitTTY": {},
"PermitTunnel": {},
"PermitUserRC": {},
"PubkeyAcceptedAlgorithms": {},
"PubkeyAuthentication": {},
"PubkeyAuthOptions": {},
"RekeyLimit": {},
"RevokedKeys": {},
"RDomain": {},
"SetEnv": {},
"StreamLocalBindMask": {},
"StreamLocalBindUnlink": {},
"TrustedUserCAKeys": {},
"UnusedConnectionTimeout": {},
"X11DisplayOffset": {},
"X11Forwarding": {},
"X11UseLocalhos": {},
var MatchAllowedOptions = map[NormalizedOptionName]struct{}{
"acceptenv": {},
"allowagentforwarding": {},
"allowgroups": {},
"allowstreamlocalforwarding": {},
"allowtcpforwarding": {},
"allowusers": {},
"authenticationmethods": {},
"authorizedkeyscommand": {},
"authorizedkeyscommanduser": {},
"authorizedkeysfile": {},
"authorizedprincipalscommand": {},
"authorizedprincipalscommanduser": {},
"authorizedprincipalsfile": {},
"banner": {},
"casignaturealgorithms": {},
"channeltimeout": {},
"chrootdirectory": {},
"clientalivecountmax": {},
"clientaliveinterval": {},
"denygroups": {},
"denyusers": {},
"disableforwarding": {},
"exposeauthinfo": {},
"forcecommand": {},
"gatewayports": {},
"gssapiauthentication": {},
"hostbasedacceptedalgorithms": {},
"hostbasedauthentication": {},
"hostbasedusesnamefrompacketonly": {},
"ignorerhosts": {},
"include": {},
"ipqos": {},
"kbdinteractiveauthentication": {},
"kerberosauthentication": {},
"loglevel": {},
"maxauthtries": {},
"maxsessions": {},
"passwordauthentication": {},
"permitemptypasswords": {},
"permitlisten": {},
"permitopen": {},
"permitrootlogin": {},
"permittty": {},
"permittunnel": {},
"permituserrc": {},
"pubkeyacceptedalgorithms": {},
"pubkeyauthentication": {},
"pubkeyauthoptions": {},
"rekeylimit": {},
"revokedkeys": {},
"rdomain": {},
"setenv": {},
"streamlocalbindmask": {},
"streamlocalbindunlink": {},
"trustedusercakeys": {},
"unusedconnectiontimeout": {},
"x11displayoffset": {},
"x11forwarding": {},
"x11uselocalhos": {},
}
var MatchUserField = docvalues.UserValue("", false)

View File

@ -1,11 +1,11 @@
package fields
var AllowedDuplicateOptions = map[string]struct{}{
"AllowGroups": {},
"AllowUsers": {},
"DenyGroups": {},
"DenyUsers": {},
"ListenAddress": {},
"Match": {},
"Port": {},
var AllowedDuplicateOptions = map[NormalizedOptionName]struct{}{
"allowgroups": {},
"allowusers": {},
"denygroups": {},
"denyusers": {},
"listenaddress": {},
"match": {},
"port": {},
}

View File

@ -0,0 +1,72 @@
package fields
var AvailableTokens = map[string]string{
"%%": "A literal %.",
"%C": "Identifies the connection endpoints, containing four space-separated values: client address, client port number, server address, and server port number.",
"%D": "The routing domain in which the incoming connection was received.",
"%F": "The fingerprint of the CA key.",
"%f": "The fingerprint of the key or certificate.",
"%h": "The home directory of the user.",
"%i": "The key ID in the certificate.",
"%K": "The base64-encoded CA key.",
"%k": "The base64-encoded key or certificate for authentication.",
"%s": "The serial number of the certificate.",
"%T": "The type of the CA key.",
"%t": "The key or certificate type.",
"%U": "The numeric user ID of the target user.",
"%u": "The username.",
}
// A map of <option name> to <list of supported tokens>
// This is derived from the TOKENS section of ssh_config
var OptionsTokensMap = map[NormalizedOptionName][]string{
"authorizedkeyscommand": {
"%%",
"%C",
"%D",
"%f",
"%h",
"%k",
"%t",
"%U",
"%u",
},
"authorizedkeysfile": {
"%%",
"%h",
"%U",
"%u",
},
"authorizedprincipalscommand": {
"%%",
"%C",
"%D",
"%F",
"%f",
"%h",
"%i",
"%K",
"%k",
"%s",
"%T",
"%t",
"%U",
"%u",
},
"authorizedprincipalsfile": {
"%%",
"%h",
"%U",
"%u",
},
"chrootdirectory": {
"%%",
"%h",
"%U",
"%u",
},
// Routing domain is missing in the fields as it's not documented
"routingdomain": {
"%D",
},
}

View File

@ -34,6 +34,7 @@ func prefixPlusMinusCaret(values []docvalues.EnumString) docvalues.PrefixWithMea
SubValue: docvalues.ArrayValue{
Separator: ",",
DuplicatesExtractor: &docvalues.SimpleDuplicatesExtractor,
RespectQuotes: true,
SubValue: docvalues.EnumValue{
Values: values,
},

View File

@ -11,6 +11,8 @@ import (
protocol "github.com/tliron/glsp/protocol_3_16"
)
var matchOption = fields.CreateNormalizedName("Match")
func GetRootCompletions(
d *sshdconfig.SSHDDocument,
parentMatchBlock *ast.SSHDMatchBlock,
@ -18,7 +20,7 @@ func GetRootCompletions(
) ([]protocol.CompletionItem, error) {
kind := protocol.CompletionItemKindField
availableOptions := make(map[string]docvalues.DocumentationValue, 0)
availableOptions := make(map[fields.NormalizedOptionName]docvalues.DocumentationValue, 0)
for key, option := range fields.Options {
var exists = false
@ -43,7 +45,8 @@ func GetRootCompletions(
return utils.MapMapToSlice(
availableOptions,
func(name string, doc docvalues.DocumentationValue) protocol.CompletionItem {
func(normalizedName fields.NormalizedOptionName, doc docvalues.DocumentationValue) protocol.CompletionItem {
name := fields.FieldsNameFormattedMap[normalizedName]
completion := &protocol.CompletionItem{
Label: name,
Kind: &kind,
@ -68,14 +71,15 @@ func GetOptionCompletions(
entry *ast.SSHDOption,
matchBlock *ast.SSHDMatchBlock,
cursor common.CursorPosition,
) ([]protocol.CompletionItem, error) {
option, found := fields.Options[entry.Key.Key]
) []protocol.CompletionItem {
key := entry.Key.Key
option, found := fields.Options[key]
if !found {
return nil, nil
return nil
}
if entry.Key.Key == "Match" {
if entry.Key.Key == matchOption {
return getMatchCompletions(
d,
cursor,
@ -84,18 +88,48 @@ func GetOptionCompletions(
}
if entry.OptionValue == nil {
return option.DeprecatedFetchCompletions("", 0), nil
return option.DeprecatedFetchCompletions("", 0)
}
// token completions
completions := getTokenCompletions(entry, cursor)
// Hello wo|rld
line := entry.OptionValue.Value.Raw
// NEW: docvalues index
return option.DeprecatedFetchCompletions(
completions = append(completions, option.DeprecatedFetchCompletions(
line,
common.DeprecatedImprovedCursorToIndex(
cursor,
line,
entry.OptionValue.Start.Character,
),
), nil
)...)
return completions
}
func getTokenCompletions(
entry *ast.SSHDOption,
cursor common.CursorPosition,
) []protocol.CompletionItem {
completions := make([]protocol.CompletionItem, 0)
index := common.CursorToCharacterIndex(uint32(cursor))
if entry.Value.Raw[index] == '%' {
if tokens, found := fields.OptionsTokensMap[entry.Key.Key]; found {
for _, token := range tokens {
description := fields.AvailableTokens[token]
kind := protocol.CompletionItemKindConstant
completions = append(completions, protocol.CompletionItem{
Label: token,
Kind: &kind,
Documentation: description,
})
}
}
}
return completions
}

View File

@ -5,6 +5,7 @@ import (
sshdconfig "config-lsp/handlers/sshd_config"
"config-lsp/handlers/sshd_config/fields"
"config-lsp/handlers/sshd_config/match-parser"
protocol "github.com/tliron/glsp/protocol_3_16"
)
@ -12,21 +13,21 @@ func getMatchCompletions(
d *sshdconfig.SSHDDocument,
cursor common.CursorPosition,
match *matchparser.Match,
) ([]protocol.CompletionItem, error) {
) []protocol.CompletionItem {
if match == nil || len(match.Entries) == 0 {
completions := getMatchCriteriaCompletions()
completions = append(completions, getMatchAllKeywordCompletion())
return completions, nil
return completions
}
entry := match.GetEntryAtPosition(cursor)
if entry == nil || entry.Criteria.ContainsPosition(cursor) {
return getMatchCriteriaCompletions(), nil
return getMatchCriteriaCompletions()
}
return getMatchValueCompletions(entry, cursor), nil
return getMatchValueCompletions(entry, cursor)
}
func getMatchCriteriaCompletions() []protocol.CompletionItem {

View File

@ -3,6 +3,7 @@ package handlers
import (
"config-lsp/common/formatting"
"config-lsp/handlers/sshd_config/ast"
"config-lsp/handlers/sshd_config/fields"
"config-lsp/handlers/sshd_config/match-parser"
"config-lsp/utils"
"fmt"
@ -29,7 +30,11 @@ func formatSSHDOption(
var key string
if option.Key != nil {
key = option.Key.Key
if formattedName, found := fields.FieldsNameFormattedMap[option.Key.Key]; found {
key = formattedName
} else {
key = string(option.Key.Key)
}
} else {
key = ""
}

View File

@ -17,22 +17,24 @@ func GetHoverInfoForOption(
index common.IndexPosition,
) (*protocol.Hover, error) {
var docValue *docvalues.DocumentationValue
key := option.Key.Key
// Either root level or in the line of a match block
if matchBlock == nil || matchBlock.Start.Line == line {
val := fields.Options[option.Key.Key]
val := fields.Options[key]
docValue = &val
} else {
if _, found := fields.MatchAllowedOptions[option.Key.Key]; found {
val := fields.Options[option.Key.Key]
if _, found := fields.MatchAllowedOptions[key]; found {
val := fields.Options[key]
docValue = &val
}
}
if option.Key.ContainsPosition(index) {
if docValue != nil {
name := fields.FieldsNameFormattedMap[key]
contents := []string{
"## " + option.Key.Key,
"## " + name,
"",
}
contents = append(contents, docValue.Documentation)

View File

@ -0,0 +1,101 @@
package handlers
import (
"config-lsp/common"
"config-lsp/handlers/sshd_config/ast"
protocol "github.com/tliron/glsp/protocol_3_16"
)
func GetOptionSignatureHelp(
option *ast.SSHDOption,
cursor common.CursorPosition,
) *protocol.SignatureHelp {
var index uint32
if option == nil || option.Key == nil || (option.OptionValue == nil || option.Key.ContainsPosition(cursor)) {
index = 0
} else {
index = 1
}
signature := uint32(0)
return &protocol.SignatureHelp{
ActiveSignature: &signature,
Signatures: []protocol.SignatureInformation{
{
Label: "<option> <value>",
ActiveParameter: &index,
Parameters: []protocol.ParameterInformation{
{
Label: []uint32{
0,
uint32(len("<option>") + 1),
},
Documentation: "The option name",
},
{
Label: []uint32{
uint32(len("<option>")),
uint32(len("<option>") + len("<value>") + 1),
},
Documentation: "The value for the option",
},
},
},
},
}
}
func GetMatchSignatureHelp(
match *ast.SSHDMatchBlock,
cursor common.CursorPosition,
) *protocol.SignatureHelp {
var index uint32
if match.MatchOption.Key.ContainsPosition(cursor) {
index = 0
} else {
entry := match.MatchValue.GetEntryAtPosition(cursor)
if entry == nil || entry.Criteria.ContainsPosition(cursor) {
index = 1
} else {
index = 2
}
}
signature := uint32(0)
return &protocol.SignatureHelp{
ActiveSignature: &signature,
Signatures: []protocol.SignatureInformation{
{
Label: "Match <criteria> <values>",
ActiveParameter: &index,
Parameters: []protocol.ParameterInformation{
{
Label: []uint32{
0,
uint32(len("Match") + 1),
},
Documentation: "The \"Match\" keyword",
},
{
Label: []uint32{
uint32(len("Match ")),
uint32(len("Match ") + len("<criteria>")),
},
Documentation: "The criteria name",
},
{
Label: []uint32{
uint32(len("Host <criteria> ")),
uint32(len("Host <criteria> ") + len("<values>") + 1),
},
Documentation: "Values for the criteria",
},
},
},
},
}
}

View File

@ -3,6 +3,7 @@ package indexes
import (
"config-lsp/common"
"config-lsp/handlers/sshd_config/ast"
"config-lsp/handlers/sshd_config/fields"
)
type ValidPath string
@ -33,7 +34,7 @@ type SSHDIndexIncludeLine struct {
type SSHDIndexes struct {
// This is a map of `Option name` to a list of options with that name
AllOptionsPerName map[string](map[*ast.SSHDMatchBlock]([]*ast.SSHDOption))
AllOptionsPerName map[fields.NormalizedOptionName](map[*ast.SSHDMatchBlock]([]*ast.SSHDOption))
Includes map[uint32]*SSHDIndexIncludeLine
}

View File

@ -11,10 +11,12 @@ import (
var whitespacePattern = regexp.MustCompile(`\S+`)
var includeOption = fields.CreateNormalizedName("Include")
func CreateIndexes(config ast.SSHDConfig) (*SSHDIndexes, []common.LSPError) {
errs := make([]common.LSPError, 0)
indexes := &SSHDIndexes{
AllOptionsPerName: make(map[string](map[*ast.SSHDMatchBlock]([]*ast.SSHDOption))),
AllOptionsPerName: make(map[fields.NormalizedOptionName](map[*ast.SSHDMatchBlock]([]*ast.SSHDOption))),
Includes: make(map[uint32]*SSHDIndexIncludeLine),
}
@ -42,7 +44,7 @@ func CreateIndexes(config ast.SSHDConfig) (*SSHDIndexes, []common.LSPError) {
}
// Add Includes
for matchBlock, options := range indexes.AllOptionsPerName["Include"] {
for matchBlock, options := range indexes.AllOptionsPerName[includeOption] {
includeOption := options[0]
rawValue := includeOption.OptionValue.Value.Value
pathIndexes := whitespacePattern.FindAllStringIndex(rawValue, -1)
@ -89,10 +91,11 @@ func addOption(
matchBlock *ast.SSHDMatchBlock,
) []common.LSPError {
var errs []common.LSPError
key := option.Key.Key
if optionsMap, found := i.AllOptionsPerName[option.Key.Key]; found {
if optionsMap, found := i.AllOptionsPerName[key]; found {
if options, found := optionsMap[matchBlock]; found {
if _, duplicatesAllowed := fields.AllowedDuplicateOptions[option.Key.Key]; !duplicatesAllowed {
if _, duplicatesAllowed := fields.AllowedDuplicateOptions[key]; !duplicatesAllowed {
firstDefinedOption := options[0]
errs = append(errs, common.LSPError{
Range: option.Key.LocationRange,
@ -103,18 +106,18 @@ func addOption(
)),
})
} else {
i.AllOptionsPerName[option.Key.Key][matchBlock] = append(
i.AllOptionsPerName[option.Key.Key][matchBlock],
i.AllOptionsPerName[key][matchBlock] = append(
i.AllOptionsPerName[key][matchBlock],
option,
)
}
} else {
i.AllOptionsPerName[option.Key.Key][matchBlock] = []*ast.SSHDOption{
i.AllOptionsPerName[key][matchBlock] = []*ast.SSHDOption{
option,
}
}
} else {
i.AllOptionsPerName[option.Key.Key] = map[*ast.SSHDMatchBlock]([]*ast.SSHDOption){
i.AllOptionsPerName[key] = map[*ast.SSHDMatchBlock]([]*ast.SSHDOption){
matchBlock: {
option,
},

View File

@ -34,7 +34,7 @@ Match Address 192.168.0.1/24
}
firstMatchBlock := config.FindMatchBlock(uint32(6))
opts := indexes.AllOptionsPerName["PermitRootLogin"]
opts := indexes.AllOptionsPerName["permitrootlogin"]
if !(len(opts) == 2 &&
len(opts[nil]) == 1 &&
opts[nil][0].Value.Value == "PermitRootLogin yes" &&
@ -42,7 +42,7 @@ Match Address 192.168.0.1/24
len(opts[firstMatchBlock]) == 1 &&
opts[firstMatchBlock][0].Value.Value == "\tPermitRootLogin no" &&
opts[firstMatchBlock][0].Start.Line == 6 &&
opts[firstMatchBlock][0].Key.Key == "PermitRootLogin") {
opts[firstMatchBlock][0].Key.Key == "permitrootlogin") {
t.Errorf("Expected 3 PermitRootLogin options, but got %v", opts)
}
}

View File

@ -43,7 +43,7 @@ func TextDocumentCompletion(context *glsp.Context, params *protocol.CompletionPa
entry,
matchBlock,
cursor,
)
), nil
}
return nil, nil

View File

@ -1,10 +1,43 @@
package lsp
import (
"config-lsp/common"
"config-lsp/handlers/sshd_config"
"config-lsp/handlers/sshd_config/fields"
"config-lsp/handlers/sshd_config/handlers"
"github.com/tliron/glsp"
protocol "github.com/tliron/glsp/protocol_3_16"
)
var matchOption = fields.CreateNormalizedName("Match")
func TextDocumentSignatureHelp(context *glsp.Context, params *protocol.SignatureHelpParams) (*protocol.SignatureHelp, error) {
return nil, nil
document := sshdconfig.DocumentParserMap[params.TextDocument.URI]
line := uint32(params.Position.Line)
cursor := common.LSPCharacterAsCursorPosition(params.Position.Character)
if _, found := document.Config.CommentLines[line]; found {
// Comment
return nil, nil
}
option, block := document.Config.FindOption(line)
if option != nil {
if option.Key != nil {
switch option.Key.Key {
case matchOption:
return handlers.GetMatchSignatureHelp(
block,
cursor,
), nil
}
}
return handlers.GetOptionSignatureHelp(option, cursor), nil
} else {
return handlers.GetOptionSignatureHelp(option, cursor), nil
}
}

View File

@ -2,6 +2,8 @@ package main
import (
roothandler "config-lsp/root-handler"
"fmt"
"os"
"github.com/tliron/commonlog"
@ -11,6 +13,13 @@ import (
)
func main() {
if len(os.Args) > 1 && (os.Args[1] == "--version" || os.Args[1] == "version") {
fmt.Println(roothandler.Version)
os.Exit(0)
return
}
// This increases logging verbosity (optional)
commonlog.Configure(1, nil)

View File

@ -0,0 +1,5 @@
package roothandler
// The comment below at the end of the line is required for the CI:CD to work.
// Do not remove it
var Version = "0.1.2" // CI:CD-VERSION

View File

@ -1,6 +1,8 @@
package roothandler
import (
"config-lsp/root-handler/lsp"
"config-lsp/root-handler/shared"
"github.com/tliron/glsp"
protocol "github.com/tliron/glsp/protocol_3_16"
@ -9,30 +11,29 @@ import (
const lsName = "config-lsp"
var version string = "0.0.1"
var lspHandler protocol.Handler
// The root handler which handles all the LSP requests and then forwards them to the appropriate handler
func SetUpRootHandler() {
rootHandler = NewRootHandler()
shared.Handler = shared.NewRootHandler()
lspHandler = protocol.Handler{
Initialize: initialize,
Initialized: initialized,
Shutdown: shutdown,
SetTrace: setTrace,
TextDocumentDidOpen: TextDocumentDidOpen,
TextDocumentDidChange: TextDocumentDidChange,
TextDocumentCompletion: TextDocumentCompletion,
TextDocumentHover: TextDocumentHover,
TextDocumentDidClose: TextDocumentDidClose,
TextDocumentCodeAction: TextDocumentCodeAction,
TextDocumentDefinition: TextDocumentDefinition,
WorkspaceExecuteCommand: WorkspaceExecuteCommand,
TextDocumentRename: TextDocumentRename,
TextDocumentPrepareRename: TextDocumentPrepareRename,
TextDocumentSignatureHelp: TextDocumentSignatureHelp,
TextDocumentRangeFormatting: TextDocumentRangeFormattingFunc,
TextDocumentDidOpen: lsp.TextDocumentDidOpen,
TextDocumentDidChange: lsp.TextDocumentDidChange,
TextDocumentCompletion: lsp.TextDocumentCompletion,
TextDocumentHover: lsp.TextDocumentHover,
TextDocumentDidClose: lsp.TextDocumentDidClose,
TextDocumentCodeAction: lsp.TextDocumentCodeAction,
TextDocumentDefinition: lsp.TextDocumentDefinition,
WorkspaceExecuteCommand: lsp.WorkspaceExecuteCommand,
TextDocumentRename: lsp.TextDocumentRename,
TextDocumentPrepareRename: lsp.TextDocumentPrepareRename,
TextDocumentSignatureHelp: lsp.TextDocumentSignatureHelp,
TextDocumentRangeFormatting: lsp.TextDocumentRangeFormattingFunc,
}
server := server.NewServer(&lspHandler, lsName, false)
@ -70,7 +71,7 @@ func initialize(context *glsp.Context, params *protocol.InitializeParams) (any,
Capabilities: capabilities,
ServerInfo: &protocol.InitializeResultServerInfo{
Name: lsName,
Version: &version,
Version: &Version,
},
}, nil
}

View File

@ -1,138 +0,0 @@
package roothandler
import (
"config-lsp/common"
"config-lsp/utils"
"fmt"
"regexp"
"strings"
protocol "github.com/tliron/glsp/protocol_3_16"
)
type SupportedLanguage string
const (
LanguageSSHConfig SupportedLanguage = "ssh_config"
LanguageSSHDConfig SupportedLanguage = "sshd_config"
LanguageFstab SupportedLanguage = "fstab"
LanguageWireguard SupportedLanguage = "languagewireguard"
LanguageHosts SupportedLanguage = "hosts"
LanguageAliases SupportedLanguage = "aliases"
)
var AllSupportedLanguages = []string{
string(LanguageSSHConfig),
string(LanguageSSHDConfig),
string(LanguageFstab),
string(LanguageWireguard),
string(LanguageHosts),
string(LanguageAliases),
}
type FatalFileNotReadableError struct {
FileURI protocol.DocumentUri
Err error
}
func (e FatalFileNotReadableError) Error() string {
return fmt.Sprintf("Fatal error! config-lsp was unable to read the file (%s); error: %s", e.FileURI, e.Err.Error())
}
type UnsupportedLanguageError struct {
SuggestedLanguage string
}
func (e UnsupportedLanguageError) Error() string {
return fmt.Sprintf("Language '%s' is not supported. Choose one of: %s", e.SuggestedLanguage, strings.Join(AllSupportedLanguages, ", "))
}
type LanguageUndetectableError struct{}
func (e LanguageUndetectableError) Error() string {
return "Please add: '#?lsp.language=<language>' to the top of the file. config-lsp was unable to detect the appropriate language for this file."
}
var valueToLanguageMap = map[string]SupportedLanguage{
"sshd_config": LanguageSSHDConfig,
"sshdconfig": LanguageSSHDConfig,
"ssh_config": LanguageSSHConfig,
"sshconfig": LanguageSSHConfig,
".ssh/config": LanguageSSHConfig,
"~/.ssh/config": LanguageSSHConfig,
"fstab": LanguageFstab,
"etc/fstab": LanguageFstab,
"wireguard": LanguageWireguard,
"wg": LanguageWireguard,
"languagewireguard": LanguageWireguard,
"host": LanguageHosts,
"hosts": LanguageHosts,
"etc/hosts": LanguageHosts,
"aliases": LanguageAliases,
"etc/aliases": LanguageAliases,
}
var typeOverwriteRegex = regexp.MustCompile(`#\?\s*lsp\.language\s*=\s*(\w+)\s*`)
var wireguardPattern = regexp.MustCompile(`/wg\d+\.conf$`)
var undetectableError = common.ParseError{
Line: 0,
Err: LanguageUndetectableError{},
}
func DetectLanguage(
content string,
advertisedLanguage string,
uri protocol.DocumentUri,
) (SupportedLanguage, error) {
if match := typeOverwriteRegex.FindStringSubmatch(content); match != nil {
suggestedLanguage := strings.ToLower(match[1])
foundLanguage, ok := valueToLanguageMap[suggestedLanguage]
if ok {
return foundLanguage, nil
}
matchIndex := strings.Index(content, match[0])
contentUntilMatch := content[:matchIndex]
return "", common.ParseError{
Line: uint32(utils.CountCharacterOccurrences(contentUntilMatch, '\n')),
Err: UnsupportedLanguageError{
SuggestedLanguage: suggestedLanguage,
},
}
}
if language, ok := valueToLanguageMap[advertisedLanguage]; ok {
return language, nil
}
switch uri {
case "file:///etc/ssh/sshd_config":
case "file:///etc/ssh/ssh_config":
return LanguageSSHDConfig, nil
case "file:///etc/fstab":
return LanguageFstab, nil
case "file:///etc/hosts":
return LanguageHosts, nil
case "file:///etc/aliases":
return LanguageAliases, nil
}
if strings.HasPrefix(uri, "file:///etc/wireguard/") || wireguardPattern.MatchString(uri) {
return LanguageWireguard, nil
}
if strings.HasSuffix(uri, ".ssh/config") {
return LanguageSSHConfig, nil
}
return "", undetectableError
}

View File

@ -1,40 +1,36 @@
package roothandler
package lsp
import (
aliases "config-lsp/handlers/aliases/lsp"
hosts "config-lsp/handlers/hosts/lsp"
sshconfig "config-lsp/handlers/ssh_config/lsp"
wireguard "config-lsp/handlers/wireguard/lsp"
"config-lsp/root-handler/shared"
utils "config-lsp/root-handler/utils"
"github.com/tliron/glsp"
protocol "github.com/tliron/glsp/protocol_3_16"
)
func TextDocumentCodeAction(context *glsp.Context, params *protocol.CodeActionParams) (any, error) {
language := rootHandler.GetLanguageForDocument(params.TextDocument.URI)
language := shared.Handler.GetLanguageForDocument(params.TextDocument.URI)
if language == nil {
showParseError(
context,
params.TextDocument.URI,
undetectableError,
)
return nil, nil
return utils.FetchAddLanguageActions(params.TextDocument.URI)
}
switch *language {
case LanguageFstab:
case shared.LanguageFstab:
return nil, nil
case LanguageHosts:
case shared.LanguageHosts:
return hosts.TextDocumentCodeAction(context, params)
case LanguageSSHDConfig:
case shared.LanguageSSHDConfig:
return nil, nil
case LanguageSSHConfig:
case shared.LanguageSSHConfig:
return sshconfig.TextDocumentCodeAction(context, params)
case LanguageWireguard:
case shared.LanguageWireguard:
return wireguard.TextDocumentCodeAction(context, params)
case LanguageAliases:
case shared.LanguageAliases:
return aliases.TextDocumentCodeAction(context, params)
}

View File

@ -1,4 +1,4 @@
package roothandler
package lsp
import (
aliases "config-lsp/handlers/aliases/lsp"
@ -7,36 +7,30 @@ import (
sshconfig "config-lsp/handlers/ssh_config/lsp"
sshdconfig "config-lsp/handlers/sshd_config/lsp"
wireguard "config-lsp/handlers/wireguard/lsp"
"config-lsp/root-handler/shared"
"github.com/tliron/glsp"
protocol "github.com/tliron/glsp/protocol_3_16"
)
func TextDocumentCompletion(context *glsp.Context, params *protocol.CompletionParams) (any, error) {
language := rootHandler.GetLanguageForDocument(params.TextDocument.URI)
language := shared.Handler.GetLanguageForDocument(params.TextDocument.URI)
if language == nil {
showParseError(
context,
params.TextDocument.URI,
undetectableError,
)
return nil, undetectableError.Err
return nil, nil
}
switch *language {
case LanguageFstab:
case shared.LanguageFstab:
return fstab.TextDocumentCompletion(context, params)
case LanguageSSHDConfig:
case shared.LanguageSSHDConfig:
return sshdconfig.TextDocumentCompletion(context, params)
case LanguageSSHConfig:
case shared.LanguageSSHConfig:
return sshconfig.TextDocumentCompletion(context, params)
case LanguageWireguard:
case shared.LanguageWireguard:
return wireguard.TextDocumentCompletion(context, params)
case LanguageHosts:
case shared.LanguageHosts:
return hosts.TextDocumentCompletion(context, params)
case LanguageAliases:
case shared.LanguageAliases:
return aliases.TextDocumentCompletion(context, params)
}

View File

@ -1,39 +1,35 @@
package roothandler
package lsp
import (
aliases "config-lsp/handlers/aliases/lsp"
sshconfig "config-lsp/handlers/ssh_config/lsp"
sshdconfig "config-lsp/handlers/sshd_config/lsp"
"config-lsp/root-handler/shared"
"config-lsp/root-handler/utils"
"github.com/tliron/glsp"
protocol "github.com/tliron/glsp/protocol_3_16"
)
func TextDocumentDefinition(context *glsp.Context, params *protocol.DefinitionParams) (any, error) {
language := rootHandler.GetLanguageForDocument(params.TextDocument.URI)
language := shared.Handler.GetLanguageForDocument(params.TextDocument.URI)
if language == nil {
showParseError(
context,
params.TextDocument.URI,
undetectableError,
)
return nil, undetectableError.Err
return nil, utils.LanguageUndetectableError{}
}
switch *language {
case LanguageHosts:
case shared.LanguageHosts:
return nil, nil
case LanguageSSHDConfig:
case shared.LanguageSSHDConfig:
return sshdconfig.TextDocumentDefinition(context, params)
case LanguageSSHConfig:
case shared.LanguageSSHConfig:
return sshconfig.TextDocumentDefinition(context, params)
case LanguageFstab:
case shared.LanguageFstab:
return nil, nil
case LanguageWireguard:
case shared.LanguageWireguard:
return nil, nil
case LanguageAliases:
case shared.LanguageAliases:
return aliases.TextDocumentDefinition(context, params)
}

View File

@ -1,4 +1,4 @@
package roothandler
package lsp
import (
aliases "config-lsp/handlers/aliases/lsp"
@ -7,27 +7,27 @@ import (
sshconfig "config-lsp/handlers/ssh_config/lsp"
sshdconfig "config-lsp/handlers/sshd_config/lsp"
wireguard "config-lsp/handlers/wireguard/lsp"
"config-lsp/root-handler/shared"
"github.com/tliron/glsp"
protocol "github.com/tliron/glsp/protocol_3_16"
)
func TextDocumentDidChange(context *glsp.Context, params *protocol.DidChangeTextDocumentParams) error {
language := rootHandler.GetLanguageForDocument(params.TextDocument.URI)
language := shared.Handler.GetLanguageForDocument(params.TextDocument.URI)
if language == nil {
content := params.ContentChanges[0].(protocol.TextDocumentContentChangeEventWhole).Text
newLanguage, err := initFile(
context,
content,
params.TextDocument.URI,
"",
)
content := params.ContentChanges[0].(protocol.TextDocumentContentChangeEventWhole).Text
newLanguage, err := initFile(
context,
content,
params.TextDocument.URI,
"",
)
if err != nil {
return err
}
if err != nil {
return err
}
if newLanguage != language {
language = newLanguage
params := &protocol.DidOpenTextDocumentParams{
@ -40,33 +40,33 @@ func TextDocumentDidChange(context *glsp.Context, params *protocol.DidChangeText
}
switch *language {
case LanguageFstab:
case shared.LanguageFstab:
return fstab.TextDocumentDidOpen(context, params)
case LanguageSSHDConfig:
case shared.LanguageSSHDConfig:
return sshdconfig.TextDocumentDidOpen(context, params)
case LanguageSSHConfig:
case shared.LanguageSSHConfig:
return sshconfig.TextDocumentDidOpen(context, params)
case LanguageWireguard:
case shared.LanguageWireguard:
return wireguard.TextDocumentDidOpen(context, params)
case LanguageHosts:
case shared.LanguageHosts:
return hosts.TextDocumentDidOpen(context, params)
case LanguageAliases:
case shared.LanguageAliases:
return aliases.TextDocumentDidOpen(context, params)
}
}
switch *language {
case LanguageFstab:
case shared.LanguageFstab:
return fstab.TextDocumentDidChange(context, params)
case LanguageSSHDConfig:
case shared.LanguageSSHDConfig:
return sshdconfig.TextDocumentDidChange(context, params)
case LanguageSSHConfig:
case shared.LanguageSSHConfig:
return sshconfig.TextDocumentDidChange(context, params)
case LanguageWireguard:
case shared.LanguageWireguard:
return wireguard.TextDocumentDidChange(context, params)
case LanguageHosts:
case shared.LanguageHosts:
return hosts.TextDocumentDidChange(context, params)
case LanguageAliases:
case shared.LanguageAliases:
return aliases.TextDocumentDidChange(context, params)
}

View File

@ -1,4 +1,4 @@
package roothandler
package lsp
import (
aliases "config-lsp/handlers/aliases/lsp"
@ -7,39 +7,34 @@ import (
sshconfig "config-lsp/handlers/ssh_config/lsp"
sshdconfig "config-lsp/handlers/sshd_config/lsp"
wireguard "config-lsp/handlers/wireguard/lsp"
"config-lsp/root-handler/shared"
"github.com/tliron/glsp"
protocol "github.com/tliron/glsp/protocol_3_16"
)
func TextDocumentDidClose(context *glsp.Context, params *protocol.DidCloseTextDocumentParams) error {
language := rootHandler.GetLanguageForDocument(params.TextDocument.URI)
language := shared.Handler.GetLanguageForDocument(params.TextDocument.URI)
if language == nil {
showParseError(
context,
params.TextDocument.URI,
undetectableError,
)
return undetectableError.Err
return nil
}
delete(openedFiles, params.TextDocument.URI)
rootHandler.RemoveDocument(params.TextDocument.URI)
delete(shared.OpenedFiles, params.TextDocument.URI)
delete(shared.LanguagesOverwrites, params.TextDocument.URI)
shared.Handler.RemoveDocument(params.TextDocument.URI)
switch *language {
case LanguageSSHDConfig:
case shared.LanguageSSHDConfig:
return sshdconfig.TextDocumentDidClose(context, params)
case LanguageSSHConfig:
case shared.LanguageSSHConfig:
return sshconfig.TextDocumentDidClose(context, params)
case LanguageFstab:
case shared.LanguageFstab:
return fstab.TextDocumentDidClose(context, params)
case LanguageWireguard:
case shared.LanguageWireguard:
return wireguard.TextDocumentDidClose(context, params)
case LanguageHosts:
case shared.LanguageHosts:
return hosts.TextDocumentDidClose(context, params)
case LanguageAliases:
case shared.LanguageAliases:
return aliases.TextDocumentDidClose(context, params)
default:
}

View File

@ -1,7 +1,9 @@
package roothandler
package lsp
import (
"config-lsp/common"
"config-lsp/root-handler/shared"
"config-lsp/root-handler/utils"
"fmt"
aliases "config-lsp/handlers/aliases/lsp"
@ -32,60 +34,43 @@ func TextDocumentDidOpen(context *glsp.Context, params *protocol.DidOpenTextDocu
}
switch *language {
case LanguageFstab:
case shared.LanguageFstab:
return fstab.TextDocumentDidOpen(context, params)
case LanguageSSHDConfig:
case shared.LanguageSSHDConfig:
return sshdconfig.TextDocumentDidOpen(context, params)
case LanguageSSHConfig:
case shared.LanguageSSHConfig:
return sshconfig.TextDocumentDidOpen(context, params)
case LanguageWireguard:
case shared.LanguageWireguard:
return wireguard.TextDocumentDidOpen(context, params)
case LanguageHosts:
case shared.LanguageHosts:
return hosts.TextDocumentDidOpen(context, params)
case LanguageAliases:
case shared.LanguageAliases:
return aliases.TextDocumentDidOpen(context, params)
}
panic(fmt.Sprintf("unexpected roothandler.SupportedLanguage: %#v", language))
}
func showParseError(
context *glsp.Context,
uri protocol.DocumentUri,
err common.ParseError,
) {
context.Notify(
"window/showMessage",
protocol.ShowMessageParams{
Type: protocol.MessageTypeError,
Message: err.Err.Error(),
},
)
}
func initFile(
context *glsp.Context,
content string,
uri protocol.DocumentUri,
advertisedLanguage string,
) (*SupportedLanguage, error) {
language, err := DetectLanguage(content, advertisedLanguage, uri)
) (*shared.SupportedLanguage, error) {
language, err := utils.DetectLanguage(content, advertisedLanguage, uri)
if err != nil {
parseError := err.(common.ParseError)
showParseError(
context,
uri,
parseError,
)
utils.NotifyLanguageUndetectable(context, uri)
return nil, parseError.Err
return nil, utils.LanguageUndetectableError{}
} else {
utils.NotifyDetectedLanguage(context, uri, language)
}
openedFiles[uri] = struct{}{}
shared.OpenedFiles[uri] = struct{}{}
// Everything okay, now we can handle the file
rootHandler.AddDocument(uri, language)
shared.Handler.AddDocument(uri, language)
return &language, nil
}

View File

@ -1,4 +1,4 @@
package roothandler
package lsp
import (
aliases "config-lsp/handlers/aliases/lsp"
@ -7,36 +7,30 @@ import (
sshconfig "config-lsp/handlers/ssh_config/lsp"
sshdconfig "config-lsp/handlers/sshd_config/lsp"
wireguard "config-lsp/handlers/wireguard/lsp"
"config-lsp/root-handler/shared"
"github.com/tliron/glsp"
protocol "github.com/tliron/glsp/protocol_3_16"
)
func TextDocumentHover(context *glsp.Context, params *protocol.HoverParams) (*protocol.Hover, error) {
language := rootHandler.GetLanguageForDocument(params.TextDocument.URI)
language := shared.Handler.GetLanguageForDocument(params.TextDocument.URI)
if language == nil {
showParseError(
context,
params.TextDocument.URI,
undetectableError,
)
return nil, undetectableError.Err
return nil, nil
}
switch *language {
case LanguageHosts:
case shared.LanguageHosts:
return hosts.TextDocumentHover(context, params)
case LanguageSSHDConfig:
case shared.LanguageSSHDConfig:
return sshdconfig.TextDocumentHover(context, params)
case LanguageSSHConfig:
case shared.LanguageSSHConfig:
return sshconfig.TextDocumentHover(context, params)
case LanguageFstab:
case shared.LanguageFstab:
return fstab.TextDocumentHover(context, params)
case LanguageWireguard:
case shared.LanguageWireguard:
return wireguard.TextDocumentHover(context, params)
case LanguageAliases:
case shared.LanguageAliases:
return aliases.TextDocumentHover(context, params)
}

View File

@ -1,8 +1,10 @@
package roothandler
package lsp
import (
aliases "config-lsp/handlers/aliases/lsp"
sshconfig "config-lsp/handlers/ssh_config/lsp"
"config-lsp/root-handler/shared"
"config-lsp/root-handler/utils"
"github.com/tliron/glsp"
@ -10,30 +12,24 @@ import (
)
func TextDocumentPrepareRename(context *glsp.Context, params *protocol.PrepareRenameParams) (any, error) {
language := rootHandler.GetLanguageForDocument(params.TextDocument.URI)
language := shared.Handler.GetLanguageForDocument(params.TextDocument.URI)
if language == nil {
showParseError(
context,
params.TextDocument.URI,
undetectableError,
)
return nil, undetectableError.Err
return nil, utils.LanguageUndetectableError{}
}
switch *language {
case LanguageHosts:
case shared.LanguageHosts:
return nil, nil
case LanguageSSHDConfig:
case shared.LanguageSSHDConfig:
return nil, nil
case LanguageSSHConfig:
case shared.LanguageSSHConfig:
return sshconfig.TextDocumentPrepareRename(context, params)
case LanguageFstab:
case shared.LanguageFstab:
return nil, nil
case LanguageWireguard:
case shared.LanguageWireguard:
return nil, nil
case LanguageAliases:
case shared.LanguageAliases:
return aliases.TextDocumentPrepareRename(context, params)
}

View File

@ -1,8 +1,10 @@
package roothandler
package lsp
import (
sshconfig "config-lsp/handlers/ssh_config/lsp"
sshdconfig "config-lsp/handlers/sshd_config/lsp"
"config-lsp/root-handler/shared"
"config-lsp/root-handler/utils"
"github.com/tliron/glsp"
protocol "github.com/tliron/glsp/protocol_3_16"
@ -12,30 +14,24 @@ func TextDocumentRangeFormattingFunc(
context *glsp.Context,
params *protocol.DocumentRangeFormattingParams,
) ([]protocol.TextEdit, error) {
language := rootHandler.GetLanguageForDocument(params.TextDocument.URI)
language := shared.Handler.GetLanguageForDocument(params.TextDocument.URI)
if language == nil {
showParseError(
context,
params.TextDocument.URI,
undetectableError,
)
return nil, undetectableError.Err
return nil, utils.LanguageUndetectableError{}
}
switch *language {
case LanguageHosts:
case shared.LanguageHosts:
return nil, nil
case LanguageSSHDConfig:
case shared.LanguageSSHDConfig:
return sshdconfig.TextDocumentRangeFormatting(context, params)
case LanguageSSHConfig:
case shared.LanguageSSHConfig:
return sshconfig.TextDocumentRangeFormatting(context, params)
case LanguageFstab:
case shared.LanguageFstab:
return nil, nil
case LanguageWireguard:
case shared.LanguageWireguard:
return nil, nil
case LanguageAliases:
case shared.LanguageAliases:
return nil, nil
}

View File

@ -1,38 +1,34 @@
package roothandler
package lsp
import (
aliases "config-lsp/handlers/aliases/lsp"
sshconfig "config-lsp/handlers/ssh_config/lsp"
"config-lsp/root-handler/shared"
"config-lsp/root-handler/utils"
"github.com/tliron/glsp"
protocol "github.com/tliron/glsp/protocol_3_16"
)
func TextDocumentRename(context *glsp.Context, params *protocol.RenameParams) (*protocol.WorkspaceEdit, error) {
language := rootHandler.GetLanguageForDocument(params.TextDocument.URI)
language := shared.Handler.GetLanguageForDocument(params.TextDocument.URI)
if language == nil {
showParseError(
context,
params.TextDocument.URI,
undetectableError,
)
return nil, undetectableError.Err
return nil, utils.LanguageUndetectableError{}
}
switch *language {
case LanguageHosts:
case shared.LanguageHosts:
return nil, nil
case LanguageSSHDConfig:
case shared.LanguageSSHDConfig:
return nil, nil
case LanguageSSHConfig:
case shared.LanguageSSHConfig:
return sshconfig.TextDocumentRename(context, params)
case LanguageFstab:
case shared.LanguageFstab:
return nil, nil
case LanguageWireguard:
case shared.LanguageWireguard:
return nil, nil
case LanguageAliases:
case shared.LanguageAliases:
return aliases.TextDocumentRename(context, params)
}

View File

@ -1,38 +1,33 @@
package roothandler
package lsp
import (
aliases "config-lsp/handlers/aliases/lsp"
sshconfig "config-lsp/handlers/ssh_config/lsp"
sshdconfig "config-lsp/handlers/sshd_config/lsp"
"config-lsp/root-handler/shared"
"github.com/tliron/glsp"
protocol "github.com/tliron/glsp/protocol_3_16"
)
func TextDocumentSignatureHelp(context *glsp.Context, params *protocol.SignatureHelpParams) (*protocol.SignatureHelp, error) {
language := rootHandler.GetLanguageForDocument(params.TextDocument.URI)
language := shared.Handler.GetLanguageForDocument(params.TextDocument.URI)
if language == nil {
showParseError(
context,
params.TextDocument.URI,
undetectableError,
)
return nil, undetectableError.Err
return nil, nil
}
switch *language {
case LanguageHosts:
case shared.LanguageHosts:
return nil, nil
case LanguageSSHDConfig:
case shared.LanguageSSHDConfig:
return sshdconfig.TextDocumentSignatureHelp(context, params)
case LanguageSSHConfig:
case shared.LanguageSSHConfig:
return sshconfig.TextDocumentSignatureHelp(context, params)
case shared.LanguageFstab:
return nil, nil
case LanguageFstab:
case shared.LanguageWireguard:
return nil, nil
case LanguageWireguard:
return nil, nil
case LanguageAliases:
case shared.LanguageAliases:
return aliases.TextDocumentSignatureHelp(context, params)
}

View File

@ -1,4 +1,4 @@
package roothandler
package lsp
import (
aliases "config-lsp/handlers/aliases/lsp"

View File

@ -1,5 +0,0 @@
package roothandler
import protocol "github.com/tliron/glsp/protocol_3_16"
var openedFiles = make(map[protocol.DocumentUri]struct{})

View File

@ -0,0 +1,21 @@
package shared
type SupportedLanguage string
const (
LanguageSSHConfig SupportedLanguage = "ssh_config"
LanguageSSHDConfig SupportedLanguage = "sshd_config"
LanguageFstab SupportedLanguage = "fstab"
LanguageWireguard SupportedLanguage = "languagewireguard"
LanguageHosts SupportedLanguage = "hosts"
LanguageAliases SupportedLanguage = "aliases"
)
var AllSupportedLanguages = []string{
string(LanguageSSHConfig),
string(LanguageSSHDConfig),
string(LanguageFstab),
string(LanguageWireguard),
string(LanguageHosts),
string(LanguageAliases),
}

View File

@ -0,0 +1,16 @@
package shared
import (
protocol "github.com/tliron/glsp/protocol_3_16"
)
type LanguageOverwrite struct {
Language SupportedLanguage
// The start of the overwrite
Raw string
Line uint32
Character uint32
}
var LanguagesOverwrites = map[protocol.DocumentUri]LanguageOverwrite{}

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