waveterm/wavesrv/pkg/sstore/sstore.go

1563 lines
48 KiB
Go
Raw Normal View History

2023-10-17 06:31:13 +02:00
// Copyright 2023, Command Line Inc.
// SPDX-License-Identifier: Apache-2.0
2022-06-13 20:11:56 +02:00
package sstore
import (
2022-07-01 21:17:19 +02:00
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"database/sql/driver"
"fmt"
2022-07-01 23:07:13 +02:00
"log"
2022-08-17 00:08:28 +02:00
"os"
"os/user"
2022-07-01 02:02:19 +02:00
"path"
"strings"
2022-06-21 06:57:23 +02:00
"sync"
2022-06-13 20:11:56 +02:00
"time"
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
"github.com/sawka/txwrap"
2023-10-16 22:30:10 +02:00
"github.com/wavetermdev/waveterm/waveshell/pkg/base"
"github.com/wavetermdev/waveterm/waveshell/pkg/packet"
zsh support (#227) adds zsh support to waveterm. big change, lots going on here. lots of other improvements and bug fixes added while debugging and building out the feature. Commits: * refactor shexec parser.go into new package shellenv. separate out bash specific parsing from generic functions * checkpoint * work on refactoring shexec. created two new packages shellapi (for bash/zsh specific stuff), and shellutil (shared between shellapi and shexec) * more refactoring * create shellapi interface to abstract bash specific functionality * more refactoring, move bash shell state parsing to shellapi * move makeRcFile to shellapi. remove all of the 'client' options CLI options from waveshell * get shellType passed through to server/single paths for waveshell * add a local shelltype detector * mock out a zshapi * move shelltype through more of the code * get a command to run via zsh * zsh can now switch directories. poc, needs cleanup * working on ShellState encoding differences between zsh/bash. Working on parsing zsh decls. move utilfn package into waveshell (shouldn't have been in wavesrv) * switch to use []byte for vardecl serialization + diffs * progress on zsh environment. still have issues reconciling init environment with trap environment * fix typeset argument parsing * parse promptvars, more zsh specific ignores * fix bug with promptvar not getting set (wrong check in FeState func) * add sdk (issue #188) to list of rtnstate commands * more zsh compatibility -- working with a larger ohmyzsh environment. ignore more variables, handle exit trap better. unique path/fpath. add a processtype variable to base. * must return a value * zsh alias parsing/restoring. diff changes (and rtnstate changes). introduces linediff v1. * force zmodload of zsh/parameter * starting work on zsh functions * need a v1 of mapdiff as well (to handle null chars) * pack/unpack of ints was wrong (one used int and one use uint). turned out we only ever encoded '0' so it worked. that also means it is safe to change unpack to unpackUInt * reworking for binary encoding of aliases and functions (because of zsh allows any character, including nulls, in names and values) * fixes, working on functions, issue with line endings * zsh functions. lots of ugliness here around dealing with line dicipline and cooked stty. new runcommand function to grab output from a non-tty fd. note that we still to run the actual command in a stty to get the proper output. * write uuid tempdir, cleanup with tmprcfilename code * hack in some simple zsh function declaration finding code for rtnstate. create function diff for rtnstate that supports zsh * make sure key order is constant so shell hashes are consistent * fix problems with state diffs to support new zsh formats. add diff/apply code to shellapi (moved from shellenv), that is now specific to zsh or bash * add log packet and new shellstate packets * switch to shellstate map that's also keyed by shelltype * add shelltype to remoteinstance * remove shell argument from waveshell * added new shelltype statemap to remote.go (msh), deal with fallout * move shellstate out of init packet, and move to an explicit reinit call. try to initialize all of the active shell states * change dont always store init state (only store on demand). initialize shell states on demand (if not already initialized). allow reset to change shells * add shellpref field to remote table. use to drive the default shell choice for new tabs * show shelltag on cmdinput, pass through ri and remote (defaultshellstate) * bump mshell version to v0.4 * better version validation for shellstate. also relax compatibility requirements for diffing states (shelltype + major version need to match) * better error handling, check shellstate compatibility during run (on waveshell server) * add extra separator for bash shellstate processing to deal with spurious output from rc files * special migration for v30 -- flag invalid bash shell states and show special button in UI to fix * format * remove zsh-decls (unused) * remove test code * remove debug print * fix typo
2024-01-17 01:11:04 +01:00
"github.com/wavetermdev/waveterm/waveshell/pkg/shellenv"
2023-10-16 22:30:10 +02:00
"github.com/wavetermdev/waveterm/wavesrv/pkg/dbutil"
"github.com/wavetermdev/waveterm/wavesrv/pkg/scbase"
"github.com/wavetermdev/waveterm/wavesrv/pkg/scbus"
Use ssh library: add user input (#281) * feat: create backend for user input requests This is the first part of a change that allows the backend to request user input from the frontend. Essentially, the backend will send a request for the user to answer some query, and the frontend will send that answer back. It is blocking, so it needs to be used within a goroutine. There is some placeholder code in the frontend that will be updated in future commits. Similarly, there is some debug code in the backend remote.go file. * feat: create frontend for user input requests This is part of a change to allow the backend to request user input from the frontend. This adds a component specifically for handling this logic. It is only a starting point, and does not work perfectly yet. * refactor: update user input backend/interface This updates the user input backend to fix a few potential bugs. It also refactors the user input request and response types to better handle markdown and errors while making it more convenient to work with. A couple frontend changes were made to keep everything compatible. * fix: add props to user input request modal There was a second place that the modals were created that I previously missed. This fixes that second casel * feat: complete user input modal This rounds out the most immediate concerns for the new user input modal. The frontend now includes a timer to show how much time is left and will close itself once it reaches zero. Css formatting has been cleaned up to be more reasonable. There is still some test code present on the back end. This will be removed once actuall examples of the new modal are in place. * feat: create first pass known_hosts detection Manually integrating with golang's ssh library means that the code must authenticate known_hosts on its own. This is a first pass at creating a system that parses the known hosts files and denys a connection if there is a mismatch. This needs to be updated with a means to add keys to the known-hosts file if the user requests it. * feat: allow writing to known_hosts first pass As a follow-up to the previous change, we now allow the user to respond to interactive queries in order to determine if an unknown known hosts key can be added to a known_hosts file if it is missing. This needs to be refined further, but it gets the basic functionality there. * feat: add user input for kbd-interactive auth This adds a modal so the user can respond to prompts provided using the keyboard interactive authentication method. * feat: add interactive password authentication This makes the ssh password authentication interactive with its own user input modal. Unfortunately, this method does not allow trying a default first. This will need to be expanded in the future to accomodate that. * fix: allow automatic and interactive auth together Previously, it was impossible to use to separate methods of the same type to try ssh authentication. This made it impossible to make an auto attempt before a manual one. This change restricts that by combining them into one method where the auto attempt is tried once first and cannot be tried again. Following that, interactive authentication can be tried separately. It also lowers the time limit on kbd interactive authentication to 15 seconds due to limitations on the library we are using. * fix: set number of retries to one in ssh Number of retries means number of attempts after the fact, not number of total attempts. It has been adjusted from 2 to 1 to reflect this. * refactor: change argument order in GetUserInput This is a simple change to move the context to the first argument of GetUserInput to match the convention used elsewhere in the code. * fix: set number of retries to two again I was wrong in my previous analysis. The number given is the total number of tries. This is confusing when keyboard authentication and password authentication are both available which usually doesn't happen. * feat: create naive ui for ssh key passphrases This isn't quite as reactive as the other methods, but it does attempt to use publickey without a passphrase, then attempt to use the password as the passphrase, and finally prompting the user for a passphrase. The problem with this approach is that if multiple keys are used and they all have passphrases, they need to all be checked up front. In practice, this will not happen often, but it is something to be aware of. * fix: add the userinput.tsx changes These were missed in the previous commit. Adding them now.
2024-02-09 04:16:56 +01:00
"github.com/wavetermdev/waveterm/wavesrv/pkg/scpacket"
_ "github.com/mattn/go-sqlite3"
2022-06-13 20:11:56 +02:00
)
Use ssh library: add user input (#281) * feat: create backend for user input requests This is the first part of a change that allows the backend to request user input from the frontend. Essentially, the backend will send a request for the user to answer some query, and the frontend will send that answer back. It is blocking, so it needs to be used within a goroutine. There is some placeholder code in the frontend that will be updated in future commits. Similarly, there is some debug code in the backend remote.go file. * feat: create frontend for user input requests This is part of a change to allow the backend to request user input from the frontend. This adds a component specifically for handling this logic. It is only a starting point, and does not work perfectly yet. * refactor: update user input backend/interface This updates the user input backend to fix a few potential bugs. It also refactors the user input request and response types to better handle markdown and errors while making it more convenient to work with. A couple frontend changes were made to keep everything compatible. * fix: add props to user input request modal There was a second place that the modals were created that I previously missed. This fixes that second casel * feat: complete user input modal This rounds out the most immediate concerns for the new user input modal. The frontend now includes a timer to show how much time is left and will close itself once it reaches zero. Css formatting has been cleaned up to be more reasonable. There is still some test code present on the back end. This will be removed once actuall examples of the new modal are in place. * feat: create first pass known_hosts detection Manually integrating with golang's ssh library means that the code must authenticate known_hosts on its own. This is a first pass at creating a system that parses the known hosts files and denys a connection if there is a mismatch. This needs to be updated with a means to add keys to the known-hosts file if the user requests it. * feat: allow writing to known_hosts first pass As a follow-up to the previous change, we now allow the user to respond to interactive queries in order to determine if an unknown known hosts key can be added to a known_hosts file if it is missing. This needs to be refined further, but it gets the basic functionality there. * feat: add user input for kbd-interactive auth This adds a modal so the user can respond to prompts provided using the keyboard interactive authentication method. * feat: add interactive password authentication This makes the ssh password authentication interactive with its own user input modal. Unfortunately, this method does not allow trying a default first. This will need to be expanded in the future to accomodate that. * fix: allow automatic and interactive auth together Previously, it was impossible to use to separate methods of the same type to try ssh authentication. This made it impossible to make an auto attempt before a manual one. This change restricts that by combining them into one method where the auto attempt is tried once first and cannot be tried again. Following that, interactive authentication can be tried separately. It also lowers the time limit on kbd interactive authentication to 15 seconds due to limitations on the library we are using. * fix: set number of retries to one in ssh Number of retries means number of attempts after the fact, not number of total attempts. It has been adjusted from 2 to 1 to reflect this. * refactor: change argument order in GetUserInput This is a simple change to move the context to the first argument of GetUserInput to match the convention used elsewhere in the code. * fix: set number of retries to two again I was wrong in my previous analysis. The number given is the total number of tries. This is confusing when keyboard authentication and password authentication are both available which usually doesn't happen. * feat: create naive ui for ssh key passphrases This isn't quite as reactive as the other methods, but it does attempt to use publickey without a passphrase, then attempt to use the password as the passphrase, and finally prompting the user for a passphrase. The problem with this approach is that if multiple keys are used and they all have passphrases, they need to all be checked up front. In practice, this will not happen often, but it is something to be aware of. * fix: add the userinput.tsx changes These were missed in the previous commit. Adding them now.
2024-02-09 04:16:56 +01:00
type RemotePtrType = scpacket.RemotePtrType
const LineNoHeight = -1
const DBFileName = "waveterm.db"
const DBWALFileName = "waveterm.db-wal"
const DBFileNameBackup = "backup.waveterm.db"
const DBWALFileNameBackup = "backup.waveterm.db-wal"
2023-04-05 08:24:08 +02:00
const MaxWebShareLineCount = 50
2023-04-05 09:25:22 +02:00
const MaxWebShareScreenCount = 3
const MaxLineStateSize = 4 * 1024 // 4k for now, can raise if needed
2022-07-01 02:02:19 +02:00
2022-07-01 21:17:19 +02:00
const DefaultSessionName = "default"
const LocalRemoteAlias = "local"
2022-07-01 21:17:19 +02:00
2022-07-01 23:07:13 +02:00
const DefaultCwd = "~"
const APITokenSentinel = "--apitoken--"
2022-07-01 23:07:13 +02:00
zsh support (#227) adds zsh support to waveterm. big change, lots going on here. lots of other improvements and bug fixes added while debugging and building out the feature. Commits: * refactor shexec parser.go into new package shellenv. separate out bash specific parsing from generic functions * checkpoint * work on refactoring shexec. created two new packages shellapi (for bash/zsh specific stuff), and shellutil (shared between shellapi and shexec) * more refactoring * create shellapi interface to abstract bash specific functionality * more refactoring, move bash shell state parsing to shellapi * move makeRcFile to shellapi. remove all of the 'client' options CLI options from waveshell * get shellType passed through to server/single paths for waveshell * add a local shelltype detector * mock out a zshapi * move shelltype through more of the code * get a command to run via zsh * zsh can now switch directories. poc, needs cleanup * working on ShellState encoding differences between zsh/bash. Working on parsing zsh decls. move utilfn package into waveshell (shouldn't have been in wavesrv) * switch to use []byte for vardecl serialization + diffs * progress on zsh environment. still have issues reconciling init environment with trap environment * fix typeset argument parsing * parse promptvars, more zsh specific ignores * fix bug with promptvar not getting set (wrong check in FeState func) * add sdk (issue #188) to list of rtnstate commands * more zsh compatibility -- working with a larger ohmyzsh environment. ignore more variables, handle exit trap better. unique path/fpath. add a processtype variable to base. * must return a value * zsh alias parsing/restoring. diff changes (and rtnstate changes). introduces linediff v1. * force zmodload of zsh/parameter * starting work on zsh functions * need a v1 of mapdiff as well (to handle null chars) * pack/unpack of ints was wrong (one used int and one use uint). turned out we only ever encoded '0' so it worked. that also means it is safe to change unpack to unpackUInt * reworking for binary encoding of aliases and functions (because of zsh allows any character, including nulls, in names and values) * fixes, working on functions, issue with line endings * zsh functions. lots of ugliness here around dealing with line dicipline and cooked stty. new runcommand function to grab output from a non-tty fd. note that we still to run the actual command in a stty to get the proper output. * write uuid tempdir, cleanup with tmprcfilename code * hack in some simple zsh function declaration finding code for rtnstate. create function diff for rtnstate that supports zsh * make sure key order is constant so shell hashes are consistent * fix problems with state diffs to support new zsh formats. add diff/apply code to shellapi (moved from shellenv), that is now specific to zsh or bash * add log packet and new shellstate packets * switch to shellstate map that's also keyed by shelltype * add shelltype to remoteinstance * remove shell argument from waveshell * added new shelltype statemap to remote.go (msh), deal with fallout * move shellstate out of init packet, and move to an explicit reinit call. try to initialize all of the active shell states * change dont always store init state (only store on demand). initialize shell states on demand (if not already initialized). allow reset to change shells * add shellpref field to remote table. use to drive the default shell choice for new tabs * show shelltag on cmdinput, pass through ri and remote (defaultshellstate) * bump mshell version to v0.4 * better version validation for shellstate. also relax compatibility requirements for diffing states (shelltype + major version need to match) * better error handling, check shellstate compatibility during run (on waveshell server) * add extra separator for bash shellstate processing to deal with spurious output from rc files * special migration for v30 -- flag invalid bash shell states and show special button in UI to fix * format * remove zsh-decls (unused) * remove test code * remove debug print * fix typo
2024-01-17 01:11:04 +01:00
// defined here and not in packet.go since this value should never
// be passed to waveshell (it should always get resolved prior to sending a run packet)
const ShellTypePref_Detect = "detect"
2023-05-04 10:01:13 +02:00
const (
LineTypeCmd = "cmd"
LineTypeText = "text"
LineTypeOpenAI = "openai"
)
const (
LineState_Source = "prompt:source"
LineState_File = "prompt:file"
LineState_Min = "wave:min"
LineState_Template = "template"
LineState_Mode = "mode"
LineState_Lang = "lang"
)
2023-03-02 09:31:19 +01:00
const (
MainViewSession = "session"
MainViewBookmarks = "bookmarks"
MainViewHistory = "history"
)
const (
CmdStatusRunning = "running"
CmdStatusDetached = "detached"
CmdStatusError = "error"
CmdStatusDone = "done"
CmdStatusHangup = "hangup"
CmdStatusUnknown = "unknown" // used for history items where we don't have a status
)
2023-05-04 10:01:13 +02:00
const (
CmdRendererOpenAI = "openai"
)
const (
OpenAIRoleSystem = "system"
OpenAIRoleUser = "user"
OpenAIRoleAssistant = "assistant"
)
const (
RemoteAuthTypeNone = "none"
RemoteAuthTypePassword = "password"
RemoteAuthTypeKey = "key"
RemoteAuthTypeKeyPassword = "key+password"
)
ssh config import (#156) * create migrations for required database change This is a first attempt that does not appear to be working properly. It requires review. * fix errors in db migrations The previous commit had an extra json call that broke the update and did not remove the imported interies during a downgrade. * change migrations to use column instead of json It makes more sense to associate the source of a config with the remote type than the sshopts type. This change makes that clear in the database structure. * ensure adding a remote manually tags correctly Using the usual way of adding a remote should result in a sshconfigsrc of "waveterm-manual". This will be important for filtering out remotes installed manually and remotes installed via import * create basic structure for parsing ssh config This entails creating a new command, making it possible to query only the imported remotes from the database, and implementing the logic to handle all of the updates needed. This needs improvements in a few areas: - the /etc/ssh/config needs to be parsed as well - the logic for editing exisiting imported remotes needs to be written - error handling needs to be improved - update packet responses need to be provided * add sshkey support and implement editing We now search for the ssh identity keyfile and add it if it is found. Additionally, the logic to edit previously imported ssh hosts has been added. * combine hosts from user and system ssh config We now check both the user ~/.ssh/config as well as the /etc/ssh/config for hosts. This loops through each file starting with the user one. For each host, it selects the first pattern without a wildcard and chooses that to be the alias. If any future hosts are found to have the same alias, they are skipped. Errors are raised if neither config file can be opened or no aliases were found. * improve logging and error reporting Error reporting is now shortcircuited in cases of individual remotes in order to allow the other remotes to continue. These errors are now printed to logs instead. * allow imports to edit ssh port Previously, ssh ports could not be edited after the fact. Unfortunately, this can cause problems since the port can be changed in an ssh config file. To address this, we allow imports to change the port if a host with the same canonical name had previously been imported. * fix response to parse command * fix error handline for alias parsing Small mistake of checking for equality instead of inequality * fix the ability to overwrite hostName with alias if ssh_config does not find Hostname, it won't output an error. Now we compare against the result instead of looking for an error. * fix the error catching for User and Port This fixes the same problem where parsing the config doesn't give an error in the case when nothing is found. As before, this checks for a blank result instead. * remove unused code * remove repeated canonical name check The logic that checks for an existing canonical name already exists in the AddRemote function, so it is not needed here. Secondly, we now only allow edits of previously created remotes if they have not been archived. If they have, the usual logic for creating a new remote takes precedence. Lastly, there is no need to archive a remote that has already been archived so an additional check has been added. * allow archives to preserve the SSHConfigSrc * add log message for archiving of imported remotes * create variables for string variants Matches existing code style * add cleanup for opened files * move migration 25 to migration 26 (already merged a migration 25) * fix RemoteRuntimeState in ModelUpdate by moving type to sstore.go. Fix some bugs in remote:parse. Fix key/identityfile, return value, and remote editing (should go through msh). remote sudo. add info messages around parse status * fix issue with archiving the sshconfigsrc A bug in RemoteType's FromMap caused the loss of sshconfigsrc during the conversion. This has been corrected and the schema has been updated. * fix order of archiving removed imported remotes Previously, if the canonical name changed, the code would try to create a new remote before archiving the old one. This did not work if the alias didn't change. Now we archive first and add a new remote after. * fix ability to change port when importing config Importing from sshconfig needs to allow the port to change. This was not happening because of a bug that has been corrected. * always use host in place of hostname Since host is the key actually searched for in the ssh config file, searching for user@hostName may not actually work. To avoid this, we now always use user@host instead. * automatically determine ConnectMode This aims to select a connection mode based off what is provided in the ssh config file. It aims for auto connections when possible but will fall back to manual if we can't easily support it * remove sshkeysource migration number confilict Previously had conflicting migration numbers of 26. The change not in the main branch has been moved to 27 to remove the conflict. * move sshkeysource migration to migration 28 * add WaveOptions flag parsing for ssh config This is currently being used to allow users to force manual connect mode if desired. It will also be used to force skipping options in the future but that is not complete in this commit. * implement ignore flag for ssh config parsing The ignore flag will now archive an imported remote if it previously existed and not create a new remote in its place. * fix discovery of identity file Previously, a ~ in the identity file's path was not expanded to the home dir. Because of this, files with a ~ were previously identified as invalid files. By expanding it during the search, this is no longer the case. * disable frontend edit button for imported remotes Imported Remotes should not be editable in waveterm by users. This edit makes it clear that the button will not work for those cases. Further edits may be needed to explain why it doesn't work and what to do instead. * add backend rejection of updating imported remote As before, we don't want manual editing of an imported remote inside the app. This ensures that it can't happen on the backend. * create tooltips for sshconfig edit/delete buttons For remotes that are imported, edits are not allowed. This adds a tooltip that explains what to do instead. Deleting remotes that are imported is allowed, but they will come back if the user imports again. The tooltip explains a way to avoid this. * add logo after name for imported remotes In the connections screen, there previously was not a way to tell imported connections from manually created connections. This change adds a logo after the imported ones to differentiate them. * small formatting updates * add import tooltip to connection modal Added the logo for an imported config to the connection modal. It also provides a short description when it the mouse hovers over it. * add button to import ssh config Make the command into a button for a simple gui interface. Also ran prettier to clean up some syntax. * remove strict casing on WaveOptions WaveOptions was previously very specific about the casing of the ignore and connectmode subcommands. With this update, the casing is automatically converted to lowercase and can be ignored. * add status dot before name in connections screen * add space and tooltip to connection imported icon * re-prettier
2023-12-28 20:09:41 +01:00
const (
SSHConfigSrcTypeManual = "waveterm-manual"
SSHConfigSrcTypeImport = "sshconfig-import"
)
const (
ShareModeLocal = "local"
ShareModeWeb = "web"
)
const (
ConnectModeStartup = "startup"
ConnectModeAuto = "auto"
ConnectModeManual = "manual"
)
const (
RemoteTypeSsh = "ssh"
RemoteTypeOpenAI = "openai"
)
2022-10-11 10:11:04 +02:00
const (
ScreenFocusInput = "input"
ScreenFocusCmd = "cmd"
2022-10-11 10:11:04 +02:00
)
2023-03-21 03:20:57 +01:00
const (
CmdStoreTypeSession = "session"
CmdStoreTypeScreen = "screen"
)
const (
UpdateType_ScreenNew = "screen:new"
UpdateType_ScreenDel = "screen:del"
UpdateType_ScreenSelectedLine = "screen:selectedline"
UpdateType_ScreenName = "screen:sharename"
UpdateType_LineNew = "line:new"
UpdateType_LineDel = "line:del"
UpdateType_LineRenderer = "line:renderer"
2023-03-31 09:32:38 +02:00
UpdateType_LineContentHeight = "line:contentheight"
UpdateType_LineState = "line:state"
UpdateType_CmdStatus = "cmd:status"
UpdateType_CmdTermOpts = "cmd:termopts"
2023-07-31 02:16:43 +02:00
UpdateType_CmdExitCode = "cmd:exitcode"
UpdateType_CmdDurationMs = "cmd:durationms"
UpdateType_CmdRtnState = "cmd:rtnstate"
UpdateType_PtyPos = "pty:pos"
)
2023-01-17 08:36:52 +01:00
const MaxTzNameLen = 50
2022-07-01 21:17:19 +02:00
var globalDBLock = &sync.Mutex{}
var globalDB *sqlx.DB
var globalDBErr error
2023-07-31 02:16:43 +02:00
func lineIdFromCK(ck base.CommandKey) string {
return ck.GetCmdId()
}
func GetDBName() string {
scHome := scbase.GetWaveHomeDir()
2022-07-01 02:02:19 +02:00
return path.Join(scHome, DBFileName)
}
2022-06-13 20:11:56 +02:00
func GetDBWALName() string {
scHome := scbase.GetWaveHomeDir()
return path.Join(scHome, DBWALFileName)
}
func GetDBBackupName() string {
scHome := scbase.GetWaveHomeDir()
return path.Join(scHome, DBFileNameBackup)
}
func GetDBWALBackupName() string {
scHome := scbase.GetWaveHomeDir()
return path.Join(scHome, DBWALFileNameBackup)
}
func IsValidConnectMode(mode string) bool {
2022-09-14 02:11:36 +02:00
return mode == ConnectModeStartup || mode == ConnectModeAuto || mode == ConnectModeManual
}
func GetDB(ctx context.Context) (*sqlx.DB, error) {
if txwrap.IsTxWrapContext(ctx) {
return nil, fmt.Errorf("cannot call GetDB from within a running transaction")
}
2022-07-01 21:17:19 +02:00
globalDBLock.Lock()
defer globalDBLock.Unlock()
if globalDB == nil && globalDBErr == nil {
dbName := GetDBName()
globalDB, globalDBErr = sqlx.Open("sqlite3", fmt.Sprintf("file:%s?cache=shared&mode=rwc&_journal_mode=WAL&_busy_timeout=5000", dbName))
if globalDBErr != nil {
globalDBErr = fmt.Errorf("opening db[%s]: %w", dbName, globalDBErr)
log.Printf("[db] error: %v\n", globalDBErr)
} else {
log.Printf("[db] successfully opened db %s\n", dbName)
}
}
2022-07-01 21:17:19 +02:00
return globalDB, globalDBErr
}
func CloseDB() {
globalDBLock.Lock()
defer globalDBLock.Unlock()
if globalDB == nil {
return
}
err := globalDB.Close()
if err != nil {
log.Printf("[db] error closing database: %v\n", err)
}
globalDB = nil
}
2023-03-26 22:21:58 +02:00
type CmdPtr struct {
ScreenId string
2023-07-31 02:16:43 +02:00
LineId string
2023-03-26 22:21:58 +02:00
}
2022-09-25 09:26:33 +02:00
type ClientWinSizeType struct {
Width int `json:"width"`
Height int `json:"height"`
Top int `json:"top"`
Left int `json:"left"`
FullScreen bool `json:"fullscreen,omitempty"`
}
2023-01-17 08:36:52 +01:00
type ActivityUpdate struct {
FgMinutes int
ActiveMinutes int
OpenMinutes int
NumCommands int
ClickShared int
HistoryView int
BookmarksView int
NumConns int
WebShareLimit int
ReinitBashErrors int
ReinitZshErrors int
BuildTime string
2023-01-17 08:36:52 +01:00
}
type ActivityType struct {
Day string `json:"day"`
Uploaded bool `json:"-"`
TData TelemetryData `json:"tdata"`
TzName string `json:"tzname"`
TzOffset int `json:"tzoffset"`
ClientVersion string `json:"clientversion"`
ClientArch string `json:"clientarch"`
2023-02-24 00:17:47 +01:00
BuildTime string `json:"buildtime"`
DefaultShell string `json:"defaultshell"`
2023-02-24 00:17:47 +01:00
OSRelease string `json:"osrelease"`
}
type TelemetryData struct {
NumCommands int `json:"numcommands"`
ActiveMinutes int `json:"activeminutes"`
FgMinutes int `json:"fgminutes"`
OpenMinutes int `json:"openminutes"`
ClickShared int `json:"clickshared,omitempty"`
HistoryView int `json:"historyview,omitempty"`
BookmarksView int `json:"bookmarksview,omitempty"`
NumConns int `json:"numconns"`
WebShareLimit int `json:"websharelimit,omitempty"`
ReinitBashErrors int `json:"reinitbasherrors,omitempty"`
ReinitZshErrors int `json:"reinitzsherrors,omitempty"`
}
func (tdata TelemetryData) Value() (driver.Value, error) {
return quickValueJson(tdata)
}
func (tdata *TelemetryData) Scan(val interface{}) error {
return quickScanJson(tdata, val)
2023-01-17 08:36:52 +01:00
}
type SidebarValueType struct {
Collapsed bool `json:"collapsed"`
Width int `json:"width"`
}
type ClientOptsType struct {
NoTelemetry bool `json:"notelemetry,omitempty"`
NoReleaseCheck bool `json:"noreleasecheck,omitempty"`
AcceptedTos int64 `json:"acceptedtos,omitempty"`
ConfirmFlags map[string]bool `json:"confirmflags,omitempty"`
MainSidebar *SidebarValueType `json:"mainsidebar,omitempty"`
GlobalShortcut string `json:"globalshortcut,omitempty"`
GlobalShortcutEnabled bool `json:"globalshortcutenabled,omitempty"`
}
type FeOptsType struct {
TermFontSize int `json:"termfontsize,omitempty"`
TermFontFamily string `json:"termfontfamily,omitempty"`
Theme string `json:"theme,omitempty"`
}
type ReleaseInfoType struct {
LatestVersion string `json:"latestversion,omitempty"`
}
type ClientData struct {
ClientId string `json:"clientid"`
UserId string `json:"userid"`
UserPrivateKeyBytes []byte `json:"-"`
UserPublicKeyBytes []byte `json:"-"`
UserPrivateKey *ecdsa.PrivateKey `json:"-" dbmap:"-"`
UserPublicKey *ecdsa.PublicKey `json:"-" dbmap:"-"`
ActiveSessionId string `json:"activesessionid"`
WinSize ClientWinSizeType `json:"winsize"`
ClientOpts ClientOptsType `json:"clientopts"`
FeOpts FeOptsType `json:"feopts"`
CmdStoreType string `json:"cmdstoretype"`
DBVersion int `json:"dbversion" dbmap:"-"`
OpenAIOpts *OpenAIOptsType `json:"openaiopts,omitempty" dbmap:"openaiopts"`
ReleaseInfo ReleaseInfoType `json:"releaseinfo"`
}
func (ClientData) UseDBMap() {}
2022-09-22 07:02:38 +02:00
func (cdata *ClientData) Clean() *ClientData {
if cdata == nil {
return nil
}
rtn := *cdata
if rtn.OpenAIOpts != nil {
rtn.OpenAIOpts = &OpenAIOptsType{
Model: cdata.OpenAIOpts.Model,
MaxTokens: cdata.OpenAIOpts.MaxTokens,
MaxChoices: cdata.OpenAIOpts.MaxChoices,
// omit API Token
}
if cdata.OpenAIOpts.APIToken != "" {
rtn.OpenAIOpts.APIToken = APITokenSentinel
}
}
return &rtn
}
func (ClientData) GetType() string {
return "clientdata"
}
2022-06-21 06:57:23 +02:00
type SessionType struct {
SessionId string `json:"sessionid"`
Name string `json:"name"`
SessionIdx int64 `json:"sessionidx"`
ActiveScreenId string `json:"activescreenid"`
ShareMode string `json:"sharemode"`
NotifyNum int64 `json:"notifynum"`
2022-12-25 22:03:11 +01:00
Archived bool `json:"archived,omitempty"`
2022-12-25 22:21:48 +01:00
ArchivedTs int64 `json:"archivedts,omitempty"`
Remotes []*RemoteInstance `json:"remotes"`
2022-07-15 03:39:40 +02:00
// only for updates
Remove bool `json:"remove,omitempty"`
}
func (SessionType) GetType() string {
return "session"
}
func MakeSessionUpdateForRemote(sessionId string, ri *RemoteInstance) SessionType {
return SessionType{
SessionId: sessionId,
Remotes: []*RemoteInstance{ri},
}
2022-07-12 23:27:16 +02:00
}
type SessionTombstoneType struct {
SessionId string `json:"sessionid"`
Name string `json:"name"`
DeletedTs int64 `json:"deletedts"`
}
func (SessionTombstoneType) UseDBMap() {}
func (SessionTombstoneType) GetType() string {
return "sessiontombstone"
}
2022-09-20 23:15:20 +02:00
type SessionStatsType struct {
2022-12-25 22:03:11 +01:00
SessionId string `json:"sessionid"`
NumScreens int `json:"numscreens"`
NumArchivedScreens int `json:"numarchivedscreens"`
NumLines int `json:"numlines"`
NumCmds int `json:"numcmds"`
DiskStats SessionDiskSizeType `json:"diskstats"`
2022-09-20 23:15:20 +02:00
}
func (h *HistoryItemType) ToMap() map[string]interface{} {
rtn := make(map[string]interface{})
rtn["historyid"] = h.HistoryId
rtn["ts"] = h.Ts
rtn["userid"] = h.UserId
rtn["sessionid"] = h.SessionId
rtn["screenid"] = h.ScreenId
rtn["lineid"] = h.LineId
2023-03-18 19:49:00 +01:00
rtn["linenum"] = h.LineNum
rtn["haderror"] = h.HadError
rtn["cmdstr"] = h.CmdStr
rtn["remoteownerid"] = h.Remote.OwnerId
rtn["remoteid"] = h.Remote.RemoteId
rtn["remotename"] = h.Remote.Name
rtn["ismetacmd"] = h.IsMetaCmd
rtn["exitcode"] = h.ExitCode
rtn["durationms"] = h.DurationMs
rtn["festate"] = quickJson(h.FeState)
rtn["tags"] = quickJson(h.Tags)
rtn["status"] = h.Status
return rtn
}
func (h *HistoryItemType) FromMap(m map[string]interface{}) bool {
quickSetStr(&h.HistoryId, m, "historyid")
quickSetInt64(&h.Ts, m, "ts")
quickSetStr(&h.UserId, m, "userid")
quickSetStr(&h.SessionId, m, "sessionid")
quickSetStr(&h.ScreenId, m, "screenid")
quickSetStr(&h.LineId, m, "lineid")
quickSetBool(&h.HadError, m, "haderror")
quickSetStr(&h.CmdStr, m, "cmdstr")
quickSetStr(&h.Remote.OwnerId, m, "remoteownerid")
quickSetStr(&h.Remote.RemoteId, m, "remoteid")
quickSetStr(&h.Remote.Name, m, "remotename")
quickSetBool(&h.IsMetaCmd, m, "ismetacmd")
2022-08-30 04:18:02 +02:00
quickSetStr(&h.HistoryNum, m, "historynum")
quickSetInt64(&h.LineNum, m, "linenum")
dbutil.QuickSetNullableInt64(&h.ExitCode, m, "exitcode")
dbutil.QuickSetNullableInt64(&h.DurationMs, m, "durationms")
quickSetJson(&h.FeState, m, "festate")
quickSetJson(&h.Tags, m, "tags")
quickSetStr(&h.Status, m, "status")
return true
}
type ScreenOptsType struct {
2022-08-27 06:44:18 +02:00
TabColor string `json:"tabcolor,omitempty"`
TabIcon string `json:"tabicon,omitempty"`
PTerm string `json:"pterm,omitempty"`
}
type ScreenLinesType struct {
ScreenId string `json:"screenid"`
Lines []*LineType `json:"lines" dbmap:"-"`
Cmds []*CmdType `json:"cmds" dbmap:"-"`
}
func (ScreenLinesType) UseDBMap() {}
func (ScreenLinesType) GetType() string {
return "screenlines"
}
type ScreenWebShareOpts struct {
2023-04-05 07:28:52 +02:00
ShareName string `json:"sharename"`
ViewKey string `json:"viewkey"`
}
2023-07-26 19:10:27 +02:00
type ScreenCreateOpts struct {
BaseScreenId string
CopyRemote bool
CopyCwd bool
CopyEnv bool
}
func (sco ScreenCreateOpts) HasCopy() bool {
return sco.CopyRemote || sco.CopyCwd || sco.CopyEnv
}
2023-12-18 08:46:53 +01:00
type ScreenSidebarOptsType struct {
Open bool `json:"open,omitempty"`
Width string `json:"width,omitempty"`
// this used to be more complicated (sections with types). simplified for this release
SidebarLineId string `json:"sidebarlineid,omitempty"`
}
type ScreenViewOptsType struct {
Sidebar *ScreenSidebarOptsType `json:"sidebar,omitempty"`
}
2022-07-12 23:27:16 +02:00
type ScreenType struct {
2023-12-18 08:46:53 +01:00
SessionId string `json:"sessionid"`
ScreenId string `json:"screenid"`
Name string `json:"name"`
ScreenIdx int64 `json:"screenidx"`
ScreenOpts ScreenOptsType `json:"screenopts"`
ScreenViewOpts ScreenViewOptsType `json:"screenviewopts"`
OwnerId string `json:"ownerid"`
ShareMode string `json:"sharemode"`
WebShareOpts *ScreenWebShareOpts `json:"webshareopts,omitempty"`
CurRemote RemotePtrType `json:"curremote"`
NextLineNum int64 `json:"nextlinenum"`
SelectedLine int64 `json:"selectedline"`
Anchor ScreenAnchorType `json:"anchor"`
FocusType string `json:"focustype"`
Archived bool `json:"archived,omitempty"`
ArchivedTs int64 `json:"archivedts,omitempty"`
2022-07-15 03:39:40 +02:00
// only for updates
Remove bool `json:"remove,omitempty"`
2022-07-12 23:27:16 +02:00
}
func (s *ScreenType) ToMap() map[string]interface{} {
rtn := make(map[string]interface{})
rtn["sessionid"] = s.SessionId
rtn["screenid"] = s.ScreenId
rtn["name"] = s.Name
rtn["screenidx"] = s.ScreenIdx
rtn["screenopts"] = quickJson(s.ScreenOpts)
2023-12-18 08:46:53 +01:00
rtn["screenviewopts"] = quickJson(s.ScreenViewOpts)
rtn["ownerid"] = s.OwnerId
rtn["sharemode"] = s.ShareMode
rtn["webshareopts"] = quickNullableJson(s.WebShareOpts)
rtn["curremoteownerid"] = s.CurRemote.OwnerId
rtn["curremoteid"] = s.CurRemote.RemoteId
rtn["curremotename"] = s.CurRemote.Name
rtn["nextlinenum"] = s.NextLineNum
rtn["selectedline"] = s.SelectedLine
rtn["anchor"] = quickJson(s.Anchor)
rtn["focustype"] = s.FocusType
rtn["archived"] = s.Archived
rtn["archivedts"] = s.ArchivedTs
return rtn
}
func (s *ScreenType) FromMap(m map[string]interface{}) bool {
quickSetStr(&s.SessionId, m, "sessionid")
quickSetStr(&s.ScreenId, m, "screenid")
quickSetStr(&s.Name, m, "name")
quickSetInt64(&s.ScreenIdx, m, "screenidx")
quickSetJson(&s.ScreenOpts, m, "screenopts")
2023-12-18 08:46:53 +01:00
quickSetJson(&s.ScreenViewOpts, m, "screenviewopts")
quickSetStr(&s.OwnerId, m, "ownerid")
quickSetStr(&s.ShareMode, m, "sharemode")
quickSetNullableJson(&s.WebShareOpts, m, "webshareopts")
quickSetStr(&s.CurRemote.OwnerId, m, "curremoteownerid")
quickSetStr(&s.CurRemote.RemoteId, m, "curremoteid")
quickSetStr(&s.CurRemote.Name, m, "curremotename")
quickSetInt64(&s.NextLineNum, m, "nextlinenum")
quickSetInt64(&s.SelectedLine, m, "selectedline")
quickSetJson(&s.Anchor, m, "anchor")
quickSetStr(&s.FocusType, m, "focustype")
quickSetBool(&s.Archived, m, "archived")
quickSetInt64(&s.ArchivedTs, m, "archivedts")
return true
}
func (ScreenType) GetType() string {
return "screen"
}
func AddScreenUpdate(update *scbus.ModelUpdatePacketType, newScreen *ScreenType) {
if newScreen == nil {
return
}
screenUpdates := scbus.GetUpdateItems[ScreenType](update)
for _, screenUpdate := range screenUpdates {
if screenUpdate.ScreenId == newScreen.ScreenId {
screenUpdate = newScreen
return
}
}
update.AddUpdate(newScreen)
}
type ScreenTombstoneType struct {
ScreenId string `json:"screenid"`
SessionId string `json:"sessionid"`
Name string `json:"name"`
DeletedTs int64 `json:"deletedts"`
ScreenOpts ScreenOptsType `json:"screenopts"`
}
func (ScreenTombstoneType) UseDBMap() {}
func (ScreenTombstoneType) GetType() string {
return "screentombstone"
}
const (
LayoutFull = "full"
)
2022-07-12 23:27:16 +02:00
type LayoutType struct {
Type string `json:"type"`
Parent string `json:"parent,omitempty"`
ZIndex int64 `json:"zindex,omitempty"`
Float bool `json:"float,omitempty"`
Top string `json:"top,omitempty"`
Bottom string `json:"bottom,omitempty"`
Left string `json:"left,omitempty"`
Right string `json:"right,omitempty"`
Width string `json:"width,omitempty"`
Height string `json:"height,omitempty"`
2022-07-12 23:27:16 +02:00
}
func (l *LayoutType) Scan(val interface{}) error {
return quickScanJson(l, val)
}
func (l LayoutType) Value() (driver.Value, error) {
2022-07-12 23:27:16 +02:00
return quickValueJson(l)
}
type ScreenAnchorType struct {
2022-10-11 10:11:04 +02:00
AnchorLine int `json:"anchorline,omitempty"`
AnchorOffset int `json:"anchoroffset,omitempty"`
}
2022-07-12 22:50:44 +02:00
type HistoryItemType struct {
HistoryId string `json:"historyid"`
Ts int64 `json:"ts"`
UserId string `json:"userid"`
SessionId string `json:"sessionid"`
ScreenId string `json:"screenid"`
LineId string `json:"lineid"`
HadError bool `json:"haderror"`
CmdStr string `json:"cmdstr"`
Remote RemotePtrType `json:"remote"`
IsMetaCmd bool `json:"ismetacmd"`
ExitCode *int64 `json:"exitcode,omitempty"`
DurationMs *int64 `json:"durationms,omitempty"`
FeState FeStateType `json:"festate,omitempty"`
Tags map[string]bool `json:"tags,omitempty"`
LineNum int64 `json:"linenum" dbmap:"-"`
Status string `json:"status"`
2022-08-11 21:07:41 +02:00
// only for updates
Remove bool `json:"remove" dbmap:"-"`
// transient (string because of different history orderings)
HistoryNum string `json:"historynum" dbmap:"-"`
}
2022-08-30 04:18:02 +02:00
type HistoryQueryOpts struct {
2023-03-02 09:31:19 +01:00
Offset int
MaxItems int
FromTs int64
SearchText string
SessionId string
RemoteId string
2023-03-15 00:37:22 +01:00
ScreenId string
NoMeta bool
RawOffset int
2023-03-06 22:54:38 +01:00
FilterFn func(*HistoryItemType) bool
}
type HistoryQueryResult struct {
MaxItems int
Items []*HistoryItemType
Offset int // the offset shown to user
2023-03-06 22:54:38 +01:00
RawOffset int // internal offset
HasMore bool
NextRawOffset int // internal offset used by pager for next query
2023-03-06 22:54:38 +01:00
prevItems int // holds number of items skipped by RawOffset
2022-08-30 04:18:02 +02:00
}
2022-07-07 09:10:37 +02:00
type TermOpts struct {
Rows int64 `json:"rows"`
Cols int64 `json:"cols"`
FlexRows bool `json:"flexrows,omitempty"`
MaxPtySize int64 `json:"maxptysize,omitempty"`
2022-07-07 09:10:37 +02:00
}
func (opts *TermOpts) Scan(val interface{}) error {
2022-07-12 23:27:16 +02:00
return quickScanJson(opts, val)
2022-07-07 09:10:37 +02:00
}
func (opts TermOpts) Value() (driver.Value, error) {
2022-07-12 23:27:16 +02:00
return quickValueJson(opts)
2022-07-07 09:10:37 +02:00
}
type ShellStatePtr struct {
BaseHash string
DiffHashArr []string
}
func (ssptr *ShellStatePtr) IsEmpty() bool {
if ssptr == nil || ssptr.BaseHash == "" {
return true
}
return false
}
type RemoteInstance struct {
RIId string `json:"riid"`
Name string `json:"name"`
SessionId string `json:"sessionid"`
ScreenId string `json:"screenid"`
RemoteOwnerId string `json:"remoteownerid"`
RemoteId string `json:"remoteid"`
FeState map[string]string `json:"festate"`
zsh support (#227) adds zsh support to waveterm. big change, lots going on here. lots of other improvements and bug fixes added while debugging and building out the feature. Commits: * refactor shexec parser.go into new package shellenv. separate out bash specific parsing from generic functions * checkpoint * work on refactoring shexec. created two new packages shellapi (for bash/zsh specific stuff), and shellutil (shared between shellapi and shexec) * more refactoring * create shellapi interface to abstract bash specific functionality * more refactoring, move bash shell state parsing to shellapi * move makeRcFile to shellapi. remove all of the 'client' options CLI options from waveshell * get shellType passed through to server/single paths for waveshell * add a local shelltype detector * mock out a zshapi * move shelltype through more of the code * get a command to run via zsh * zsh can now switch directories. poc, needs cleanup * working on ShellState encoding differences between zsh/bash. Working on parsing zsh decls. move utilfn package into waveshell (shouldn't have been in wavesrv) * switch to use []byte for vardecl serialization + diffs * progress on zsh environment. still have issues reconciling init environment with trap environment * fix typeset argument parsing * parse promptvars, more zsh specific ignores * fix bug with promptvar not getting set (wrong check in FeState func) * add sdk (issue #188) to list of rtnstate commands * more zsh compatibility -- working with a larger ohmyzsh environment. ignore more variables, handle exit trap better. unique path/fpath. add a processtype variable to base. * must return a value * zsh alias parsing/restoring. diff changes (and rtnstate changes). introduces linediff v1. * force zmodload of zsh/parameter * starting work on zsh functions * need a v1 of mapdiff as well (to handle null chars) * pack/unpack of ints was wrong (one used int and one use uint). turned out we only ever encoded '0' so it worked. that also means it is safe to change unpack to unpackUInt * reworking for binary encoding of aliases and functions (because of zsh allows any character, including nulls, in names and values) * fixes, working on functions, issue with line endings * zsh functions. lots of ugliness here around dealing with line dicipline and cooked stty. new runcommand function to grab output from a non-tty fd. note that we still to run the actual command in a stty to get the proper output. * write uuid tempdir, cleanup with tmprcfilename code * hack in some simple zsh function declaration finding code for rtnstate. create function diff for rtnstate that supports zsh * make sure key order is constant so shell hashes are consistent * fix problems with state diffs to support new zsh formats. add diff/apply code to shellapi (moved from shellenv), that is now specific to zsh or bash * add log packet and new shellstate packets * switch to shellstate map that's also keyed by shelltype * add shelltype to remoteinstance * remove shell argument from waveshell * added new shelltype statemap to remote.go (msh), deal with fallout * move shellstate out of init packet, and move to an explicit reinit call. try to initialize all of the active shell states * change dont always store init state (only store on demand). initialize shell states on demand (if not already initialized). allow reset to change shells * add shellpref field to remote table. use to drive the default shell choice for new tabs * show shelltag on cmdinput, pass through ri and remote (defaultshellstate) * bump mshell version to v0.4 * better version validation for shellstate. also relax compatibility requirements for diffing states (shelltype + major version need to match) * better error handling, check shellstate compatibility during run (on waveshell server) * add extra separator for bash shellstate processing to deal with spurious output from rc files * special migration for v30 -- flag invalid bash shell states and show special button in UI to fix * format * remove zsh-decls (unused) * remove test code * remove debug print * fix typo
2024-01-17 01:11:04 +01:00
ShellType string `json:"shelltype"`
StateBaseHash string `json:"-"`
StateDiffHashArr []string `json:"-"`
2022-08-11 03:33:32 +02:00
// only for updates
Remove bool `json:"remove,omitempty"`
2022-06-21 06:57:23 +02:00
}
2022-11-28 09:13:00 +01:00
type StateBase struct {
BaseHash string
Version string
Ts int64
Data []byte
}
type StateDiff struct {
DiffHash string
Ts int64
BaseHash string
DiffHashArr []string
Data []byte
}
func (sd *StateDiff) FromMap(m map[string]interface{}) bool {
2022-11-28 09:13:00 +01:00
quickSetStr(&sd.DiffHash, m, "diffhash")
quickSetInt64(&sd.Ts, m, "ts")
quickSetStr(&sd.BaseHash, m, "basehash")
quickSetJsonArr(&sd.DiffHashArr, m, "diffhasharr")
quickSetBytes(&sd.Data, m, "data")
return true
2022-11-28 09:13:00 +01:00
}
func (sd *StateDiff) ToMap() map[string]interface{} {
rtn := make(map[string]interface{})
2022-11-28 09:13:00 +01:00
rtn["diffhash"] = sd.DiffHash
rtn["ts"] = sd.Ts
rtn["basehash"] = sd.BaseHash
rtn["diffhasharr"] = quickJsonArr(sd.DiffHashArr)
rtn["data"] = sd.Data
return rtn
}
func FeStateFromShellState(state *packet.ShellState) map[string]string {
2022-11-28 09:13:00 +01:00
if state == nil {
return nil
}
rtn := make(map[string]string)
rtn["cwd"] = state.Cwd
zsh support (#227) adds zsh support to waveterm. big change, lots going on here. lots of other improvements and bug fixes added while debugging and building out the feature. Commits: * refactor shexec parser.go into new package shellenv. separate out bash specific parsing from generic functions * checkpoint * work on refactoring shexec. created two new packages shellapi (for bash/zsh specific stuff), and shellutil (shared between shellapi and shexec) * more refactoring * create shellapi interface to abstract bash specific functionality * more refactoring, move bash shell state parsing to shellapi * move makeRcFile to shellapi. remove all of the 'client' options CLI options from waveshell * get shellType passed through to server/single paths for waveshell * add a local shelltype detector * mock out a zshapi * move shelltype through more of the code * get a command to run via zsh * zsh can now switch directories. poc, needs cleanup * working on ShellState encoding differences between zsh/bash. Working on parsing zsh decls. move utilfn package into waveshell (shouldn't have been in wavesrv) * switch to use []byte for vardecl serialization + diffs * progress on zsh environment. still have issues reconciling init environment with trap environment * fix typeset argument parsing * parse promptvars, more zsh specific ignores * fix bug with promptvar not getting set (wrong check in FeState func) * add sdk (issue #188) to list of rtnstate commands * more zsh compatibility -- working with a larger ohmyzsh environment. ignore more variables, handle exit trap better. unique path/fpath. add a processtype variable to base. * must return a value * zsh alias parsing/restoring. diff changes (and rtnstate changes). introduces linediff v1. * force zmodload of zsh/parameter * starting work on zsh functions * need a v1 of mapdiff as well (to handle null chars) * pack/unpack of ints was wrong (one used int and one use uint). turned out we only ever encoded '0' so it worked. that also means it is safe to change unpack to unpackUInt * reworking for binary encoding of aliases and functions (because of zsh allows any character, including nulls, in names and values) * fixes, working on functions, issue with line endings * zsh functions. lots of ugliness here around dealing with line dicipline and cooked stty. new runcommand function to grab output from a non-tty fd. note that we still to run the actual command in a stty to get the proper output. * write uuid tempdir, cleanup with tmprcfilename code * hack in some simple zsh function declaration finding code for rtnstate. create function diff for rtnstate that supports zsh * make sure key order is constant so shell hashes are consistent * fix problems with state diffs to support new zsh formats. add diff/apply code to shellapi (moved from shellenv), that is now specific to zsh or bash * add log packet and new shellstate packets * switch to shellstate map that's also keyed by shelltype * add shelltype to remoteinstance * remove shell argument from waveshell * added new shelltype statemap to remote.go (msh), deal with fallout * move shellstate out of init packet, and move to an explicit reinit call. try to initialize all of the active shell states * change dont always store init state (only store on demand). initialize shell states on demand (if not already initialized). allow reset to change shells * add shellpref field to remote table. use to drive the default shell choice for new tabs * show shelltag on cmdinput, pass through ri and remote (defaultshellstate) * bump mshell version to v0.4 * better version validation for shellstate. also relax compatibility requirements for diffing states (shelltype + major version need to match) * better error handling, check shellstate compatibility during run (on waveshell server) * add extra separator for bash shellstate processing to deal with spurious output from rc files * special migration for v30 -- flag invalid bash shell states and show special button in UI to fix * format * remove zsh-decls (unused) * remove test code * remove debug print * fix typo
2024-01-17 01:11:04 +01:00
envMap := shellenv.EnvMapFromState(state)
if envMap["VIRTUAL_ENV"] != "" {
rtn["VIRTUAL_ENV"] = envMap["VIRTUAL_ENV"]
}
if envMap["CONDA_DEFAULT_ENV"] != "" {
rtn["CONDA_DEFAULT_ENV"] = envMap["CONDA_DEFAULT_ENV"]
}
for key, val := range envMap {
zsh support (#227) adds zsh support to waveterm. big change, lots going on here. lots of other improvements and bug fixes added while debugging and building out the feature. Commits: * refactor shexec parser.go into new package shellenv. separate out bash specific parsing from generic functions * checkpoint * work on refactoring shexec. created two new packages shellapi (for bash/zsh specific stuff), and shellutil (shared between shellapi and shexec) * more refactoring * create shellapi interface to abstract bash specific functionality * more refactoring, move bash shell state parsing to shellapi * move makeRcFile to shellapi. remove all of the 'client' options CLI options from waveshell * get shellType passed through to server/single paths for waveshell * add a local shelltype detector * mock out a zshapi * move shelltype through more of the code * get a command to run via zsh * zsh can now switch directories. poc, needs cleanup * working on ShellState encoding differences between zsh/bash. Working on parsing zsh decls. move utilfn package into waveshell (shouldn't have been in wavesrv) * switch to use []byte for vardecl serialization + diffs * progress on zsh environment. still have issues reconciling init environment with trap environment * fix typeset argument parsing * parse promptvars, more zsh specific ignores * fix bug with promptvar not getting set (wrong check in FeState func) * add sdk (issue #188) to list of rtnstate commands * more zsh compatibility -- working with a larger ohmyzsh environment. ignore more variables, handle exit trap better. unique path/fpath. add a processtype variable to base. * must return a value * zsh alias parsing/restoring. diff changes (and rtnstate changes). introduces linediff v1. * force zmodload of zsh/parameter * starting work on zsh functions * need a v1 of mapdiff as well (to handle null chars) * pack/unpack of ints was wrong (one used int and one use uint). turned out we only ever encoded '0' so it worked. that also means it is safe to change unpack to unpackUInt * reworking for binary encoding of aliases and functions (because of zsh allows any character, including nulls, in names and values) * fixes, working on functions, issue with line endings * zsh functions. lots of ugliness here around dealing with line dicipline and cooked stty. new runcommand function to grab output from a non-tty fd. note that we still to run the actual command in a stty to get the proper output. * write uuid tempdir, cleanup with tmprcfilename code * hack in some simple zsh function declaration finding code for rtnstate. create function diff for rtnstate that supports zsh * make sure key order is constant so shell hashes are consistent * fix problems with state diffs to support new zsh formats. add diff/apply code to shellapi (moved from shellenv), that is now specific to zsh or bash * add log packet and new shellstate packets * switch to shellstate map that's also keyed by shelltype * add shelltype to remoteinstance * remove shell argument from waveshell * added new shelltype statemap to remote.go (msh), deal with fallout * move shellstate out of init packet, and move to an explicit reinit call. try to initialize all of the active shell states * change dont always store init state (only store on demand). initialize shell states on demand (if not already initialized). allow reset to change shells * add shellpref field to remote table. use to drive the default shell choice for new tabs * show shelltag on cmdinput, pass through ri and remote (defaultshellstate) * bump mshell version to v0.4 * better version validation for shellstate. also relax compatibility requirements for diffing states (shelltype + major version need to match) * better error handling, check shellstate compatibility during run (on waveshell server) * add extra separator for bash shellstate processing to deal with spurious output from rc files * special migration for v30 -- flag invalid bash shell states and show special button in UI to fix * format * remove zsh-decls (unused) * remove test code * remove debug print * fix typo
2024-01-17 01:11:04 +01:00
if strings.HasPrefix(key, "PROMPTVAR_") && envMap[key] != "" {
rtn[key] = val
}
}
zsh support (#227) adds zsh support to waveterm. big change, lots going on here. lots of other improvements and bug fixes added while debugging and building out the feature. Commits: * refactor shexec parser.go into new package shellenv. separate out bash specific parsing from generic functions * checkpoint * work on refactoring shexec. created two new packages shellapi (for bash/zsh specific stuff), and shellutil (shared between shellapi and shexec) * more refactoring * create shellapi interface to abstract bash specific functionality * more refactoring, move bash shell state parsing to shellapi * move makeRcFile to shellapi. remove all of the 'client' options CLI options from waveshell * get shellType passed through to server/single paths for waveshell * add a local shelltype detector * mock out a zshapi * move shelltype through more of the code * get a command to run via zsh * zsh can now switch directories. poc, needs cleanup * working on ShellState encoding differences between zsh/bash. Working on parsing zsh decls. move utilfn package into waveshell (shouldn't have been in wavesrv) * switch to use []byte for vardecl serialization + diffs * progress on zsh environment. still have issues reconciling init environment with trap environment * fix typeset argument parsing * parse promptvars, more zsh specific ignores * fix bug with promptvar not getting set (wrong check in FeState func) * add sdk (issue #188) to list of rtnstate commands * more zsh compatibility -- working with a larger ohmyzsh environment. ignore more variables, handle exit trap better. unique path/fpath. add a processtype variable to base. * must return a value * zsh alias parsing/restoring. diff changes (and rtnstate changes). introduces linediff v1. * force zmodload of zsh/parameter * starting work on zsh functions * need a v1 of mapdiff as well (to handle null chars) * pack/unpack of ints was wrong (one used int and one use uint). turned out we only ever encoded '0' so it worked. that also means it is safe to change unpack to unpackUInt * reworking for binary encoding of aliases and functions (because of zsh allows any character, including nulls, in names and values) * fixes, working on functions, issue with line endings * zsh functions. lots of ugliness here around dealing with line dicipline and cooked stty. new runcommand function to grab output from a non-tty fd. note that we still to run the actual command in a stty to get the proper output. * write uuid tempdir, cleanup with tmprcfilename code * hack in some simple zsh function declaration finding code for rtnstate. create function diff for rtnstate that supports zsh * make sure key order is constant so shell hashes are consistent * fix problems with state diffs to support new zsh formats. add diff/apply code to shellapi (moved from shellenv), that is now specific to zsh or bash * add log packet and new shellstate packets * switch to shellstate map that's also keyed by shelltype * add shelltype to remoteinstance * remove shell argument from waveshell * added new shelltype statemap to remote.go (msh), deal with fallout * move shellstate out of init packet, and move to an explicit reinit call. try to initialize all of the active shell states * change dont always store init state (only store on demand). initialize shell states on demand (if not already initialized). allow reset to change shells * add shellpref field to remote table. use to drive the default shell choice for new tabs * show shelltag on cmdinput, pass through ri and remote (defaultshellstate) * bump mshell version to v0.4 * better version validation for shellstate. also relax compatibility requirements for diffing states (shelltype + major version need to match) * better error handling, check shellstate compatibility during run (on waveshell server) * add extra separator for bash shellstate processing to deal with spurious output from rc files * special migration for v30 -- flag invalid bash shell states and show special button in UI to fix * format * remove zsh-decls (unused) * remove test code * remove debug print * fix typo
2024-01-17 01:11:04 +01:00
_, _, err := packet.ParseShellStateVersion(state.Version)
if err != nil {
rtn["invalidstate"] = "1"
}
return rtn
2022-11-28 09:13:00 +01:00
}
func (ri *RemoteInstance) FromMap(m map[string]interface{}) bool {
quickSetStr(&ri.RIId, m, "riid")
quickSetStr(&ri.Name, m, "name")
quickSetStr(&ri.SessionId, m, "sessionid")
2023-03-15 00:37:22 +01:00
quickSetStr(&ri.ScreenId, m, "screenid")
quickSetStr(&ri.RemoteOwnerId, m, "remoteownerid")
quickSetStr(&ri.RemoteId, m, "remoteid")
2022-11-28 09:13:00 +01:00
quickSetJson(&ri.FeState, m, "festate")
quickSetStr(&ri.StateBaseHash, m, "statebasehash")
quickSetJsonArr(&ri.StateDiffHashArr, m, "statediffhasharr")
zsh support (#227) adds zsh support to waveterm. big change, lots going on here. lots of other improvements and bug fixes added while debugging and building out the feature. Commits: * refactor shexec parser.go into new package shellenv. separate out bash specific parsing from generic functions * checkpoint * work on refactoring shexec. created two new packages shellapi (for bash/zsh specific stuff), and shellutil (shared between shellapi and shexec) * more refactoring * create shellapi interface to abstract bash specific functionality * more refactoring, move bash shell state parsing to shellapi * move makeRcFile to shellapi. remove all of the 'client' options CLI options from waveshell * get shellType passed through to server/single paths for waveshell * add a local shelltype detector * mock out a zshapi * move shelltype through more of the code * get a command to run via zsh * zsh can now switch directories. poc, needs cleanup * working on ShellState encoding differences between zsh/bash. Working on parsing zsh decls. move utilfn package into waveshell (shouldn't have been in wavesrv) * switch to use []byte for vardecl serialization + diffs * progress on zsh environment. still have issues reconciling init environment with trap environment * fix typeset argument parsing * parse promptvars, more zsh specific ignores * fix bug with promptvar not getting set (wrong check in FeState func) * add sdk (issue #188) to list of rtnstate commands * more zsh compatibility -- working with a larger ohmyzsh environment. ignore more variables, handle exit trap better. unique path/fpath. add a processtype variable to base. * must return a value * zsh alias parsing/restoring. diff changes (and rtnstate changes). introduces linediff v1. * force zmodload of zsh/parameter * starting work on zsh functions * need a v1 of mapdiff as well (to handle null chars) * pack/unpack of ints was wrong (one used int and one use uint). turned out we only ever encoded '0' so it worked. that also means it is safe to change unpack to unpackUInt * reworking for binary encoding of aliases and functions (because of zsh allows any character, including nulls, in names and values) * fixes, working on functions, issue with line endings * zsh functions. lots of ugliness here around dealing with line dicipline and cooked stty. new runcommand function to grab output from a non-tty fd. note that we still to run the actual command in a stty to get the proper output. * write uuid tempdir, cleanup with tmprcfilename code * hack in some simple zsh function declaration finding code for rtnstate. create function diff for rtnstate that supports zsh * make sure key order is constant so shell hashes are consistent * fix problems with state diffs to support new zsh formats. add diff/apply code to shellapi (moved from shellenv), that is now specific to zsh or bash * add log packet and new shellstate packets * switch to shellstate map that's also keyed by shelltype * add shelltype to remoteinstance * remove shell argument from waveshell * added new shelltype statemap to remote.go (msh), deal with fallout * move shellstate out of init packet, and move to an explicit reinit call. try to initialize all of the active shell states * change dont always store init state (only store on demand). initialize shell states on demand (if not already initialized). allow reset to change shells * add shellpref field to remote table. use to drive the default shell choice for new tabs * show shelltag on cmdinput, pass through ri and remote (defaultshellstate) * bump mshell version to v0.4 * better version validation for shellstate. also relax compatibility requirements for diffing states (shelltype + major version need to match) * better error handling, check shellstate compatibility during run (on waveshell server) * add extra separator for bash shellstate processing to deal with spurious output from rc files * special migration for v30 -- flag invalid bash shell states and show special button in UI to fix * format * remove zsh-decls (unused) * remove test code * remove debug print * fix typo
2024-01-17 01:11:04 +01:00
quickSetStr(&ri.ShellType, m, "shelltype")
return true
}
2022-11-28 09:13:00 +01:00
func (ri *RemoteInstance) ToMap() map[string]interface{} {
rtn := make(map[string]interface{})
rtn["riid"] = ri.RIId
rtn["name"] = ri.Name
rtn["sessionid"] = ri.SessionId
2023-03-15 00:37:22 +01:00
rtn["screenid"] = ri.ScreenId
2022-11-28 09:13:00 +01:00
rtn["remoteownerid"] = ri.RemoteOwnerId
rtn["remoteid"] = ri.RemoteId
rtn["festate"] = quickJson(ri.FeState)
rtn["statebasehash"] = ri.StateBaseHash
rtn["statediffhasharr"] = quickJsonArr(ri.StateDiffHashArr)
zsh support (#227) adds zsh support to waveterm. big change, lots going on here. lots of other improvements and bug fixes added while debugging and building out the feature. Commits: * refactor shexec parser.go into new package shellenv. separate out bash specific parsing from generic functions * checkpoint * work on refactoring shexec. created two new packages shellapi (for bash/zsh specific stuff), and shellutil (shared between shellapi and shexec) * more refactoring * create shellapi interface to abstract bash specific functionality * more refactoring, move bash shell state parsing to shellapi * move makeRcFile to shellapi. remove all of the 'client' options CLI options from waveshell * get shellType passed through to server/single paths for waveshell * add a local shelltype detector * mock out a zshapi * move shelltype through more of the code * get a command to run via zsh * zsh can now switch directories. poc, needs cleanup * working on ShellState encoding differences between zsh/bash. Working on parsing zsh decls. move utilfn package into waveshell (shouldn't have been in wavesrv) * switch to use []byte for vardecl serialization + diffs * progress on zsh environment. still have issues reconciling init environment with trap environment * fix typeset argument parsing * parse promptvars, more zsh specific ignores * fix bug with promptvar not getting set (wrong check in FeState func) * add sdk (issue #188) to list of rtnstate commands * more zsh compatibility -- working with a larger ohmyzsh environment. ignore more variables, handle exit trap better. unique path/fpath. add a processtype variable to base. * must return a value * zsh alias parsing/restoring. diff changes (and rtnstate changes). introduces linediff v1. * force zmodload of zsh/parameter * starting work on zsh functions * need a v1 of mapdiff as well (to handle null chars) * pack/unpack of ints was wrong (one used int and one use uint). turned out we only ever encoded '0' so it worked. that also means it is safe to change unpack to unpackUInt * reworking for binary encoding of aliases and functions (because of zsh allows any character, including nulls, in names and values) * fixes, working on functions, issue with line endings * zsh functions. lots of ugliness here around dealing with line dicipline and cooked stty. new runcommand function to grab output from a non-tty fd. note that we still to run the actual command in a stty to get the proper output. * write uuid tempdir, cleanup with tmprcfilename code * hack in some simple zsh function declaration finding code for rtnstate. create function diff for rtnstate that supports zsh * make sure key order is constant so shell hashes are consistent * fix problems with state diffs to support new zsh formats. add diff/apply code to shellapi (moved from shellenv), that is now specific to zsh or bash * add log packet and new shellstate packets * switch to shellstate map that's also keyed by shelltype * add shelltype to remoteinstance * remove shell argument from waveshell * added new shelltype statemap to remote.go (msh), deal with fallout * move shellstate out of init packet, and move to an explicit reinit call. try to initialize all of the active shell states * change dont always store init state (only store on demand). initialize shell states on demand (if not already initialized). allow reset to change shells * add shellpref field to remote table. use to drive the default shell choice for new tabs * show shelltag on cmdinput, pass through ri and remote (defaultshellstate) * bump mshell version to v0.4 * better version validation for shellstate. also relax compatibility requirements for diffing states (shelltype + major version need to match) * better error handling, check shellstate compatibility during run (on waveshell server) * add extra separator for bash shellstate processing to deal with spurious output from rc files * special migration for v30 -- flag invalid bash shell states and show special button in UI to fix * format * remove zsh-decls (unused) * remove test code * remove debug print * fix typo
2024-01-17 01:11:04 +01:00
rtn["shelltype"] = ri.ShellType
2022-11-28 09:13:00 +01:00
return rtn
}
type ScreenUpdateType struct {
UpdateId int64 `json:"updateid"`
ScreenId string `json:"screenid"`
LineId string `json:"lineid"`
UpdateType string `json:"updatetype"`
UpdateTs int64 `json:"updatets"`
}
func (ScreenUpdateType) UseDBMap() {}
2022-06-13 20:11:56 +02:00
type LineType struct {
ScreenId string `json:"screenid"`
UserId string `json:"userid"`
LineId string `json:"lineid"`
Ts int64 `json:"ts"`
LineNum int64 `json:"linenum"`
LineNumTemp bool `json:"linenumtemp,omitempty"`
LineLocal bool `json:"linelocal"`
LineType string `json:"linetype"`
LineState map[string]any `json:"linestate"`
Renderer string `json:"renderer,omitempty"`
Text string `json:"text,omitempty"`
Ephemeral bool `json:"ephemeral,omitempty"`
ContentHeight int64 `json:"contentheight,omitempty"`
Star bool `json:"star,omitempty"`
Archived bool `json:"archived,omitempty"`
Remove bool `json:"remove,omitempty"`
}
func (LineType) UseDBMap() {}
2023-05-04 10:01:13 +02:00
type OpenAIUsage struct {
PromptTokens int `json:"prompt_tokens"`
CompletionTokens int `json:"completion_tokens"`
TotalTokens int `json:"total_tokens"`
}
type OpenAIChoiceType struct {
Text string `json:"text"`
Index int `json:"index"`
FinishReason string `json:"finish_reason"`
}
type OpenAIResponse struct {
Model string `json:"model"`
Created int64 `json:"created"`
Usage *OpenAIUsage `json:"usage,omitempty"`
Choices []OpenAIChoiceType `json:"choices,omitempty"`
}
2023-03-02 09:31:19 +01:00
type PlaybookType struct {
PlaybookId string `json:"playbookid"`
PlaybookName string `json:"playbookname"`
Description string `json:"description"`
EntryIds []string `json:"entryids"`
// this is not persisted to DB, just for transport to FE
Entries []*PlaybookEntry `json:"entries"`
}
func (p *PlaybookType) ToMap() map[string]interface{} {
rtn := make(map[string]interface{})
rtn["playbookid"] = p.PlaybookId
rtn["playbookname"] = p.PlaybookName
rtn["description"] = p.Description
rtn["entryids"] = quickJsonArr(p.EntryIds)
return rtn
}
func (p *PlaybookType) FromMap(m map[string]interface{}) bool {
2023-03-02 09:31:19 +01:00
quickSetStr(&p.PlaybookId, m, "playbookid")
quickSetStr(&p.PlaybookName, m, "playbookname")
quickSetStr(&p.Description, m, "description")
quickSetJsonArr(&p.Entries, m, "entries")
return true
2023-03-02 09:31:19 +01:00
}
// reorders p.Entries to match p.EntryIds
func (p *PlaybookType) OrderEntries() {
if len(p.Entries) == 0 {
return
}
m := make(map[string]*PlaybookEntry)
for _, entry := range p.Entries {
m[entry.EntryId] = entry
}
newList := make([]*PlaybookEntry, 0, len(p.EntryIds))
for _, entryId := range p.EntryIds {
entry := m[entryId]
if entry != nil {
newList = append(newList, entry)
}
}
p.Entries = newList
}
// removes from p.EntryIds (not from p.Entries)
func (p *PlaybookType) RemoveEntry(entryIdToRemove string) {
if len(p.EntryIds) == 0 {
return
}
newList := make([]string, 0, len(p.EntryIds)-1)
for _, entryId := range p.EntryIds {
if entryId == entryIdToRemove {
continue
}
newList = append(newList, entryId)
}
p.EntryIds = newList
}
type PlaybookEntry struct {
PlaybookId string `json:"playbookid"`
EntryId string `json:"entryid"`
Alias string `json:"alias"`
CmdStr string `json:"cmdstr"`
UpdatedTs int64 `json:"updatedts"`
CreatedTs int64 `json:"createdts"`
Description string `json:"description"`
Remove bool `json:"remove,omitempty"`
}
2023-02-21 06:39:29 +01:00
type BookmarkType struct {
BookmarkId string `json:"bookmarkid"`
CreatedTs int64 `json:"createdts"`
CmdStr string `json:"cmdstr"`
Alias string `json:"alias,omitempty"`
Tags []string `json:"tags"`
Description string `json:"description"`
OrderIdx int64 `json:"orderidx"`
Remove bool `json:"remove,omitempty"`
2023-02-21 06:39:29 +01:00
}
func (bm *BookmarkType) GetSimpleKey() string {
return bm.BookmarkId
}
2023-02-21 06:39:29 +01:00
func (bm *BookmarkType) ToMap() map[string]interface{} {
rtn := make(map[string]interface{})
rtn["bookmarkid"] = bm.BookmarkId
rtn["createdts"] = bm.CreatedTs
rtn["cmdstr"] = bm.CmdStr
rtn["alias"] = bm.Alias
rtn["description"] = bm.Description
rtn["tags"] = quickJsonArr(bm.Tags)
return rtn
}
func (bm *BookmarkType) FromMap(m map[string]interface{}) bool {
2023-02-21 06:39:29 +01:00
quickSetStr(&bm.BookmarkId, m, "bookmarkid")
quickSetInt64(&bm.CreatedTs, m, "createdts")
quickSetStr(&bm.Alias, m, "alias")
quickSetStr(&bm.CmdStr, m, "cmdstr")
quickSetStr(&bm.Description, m, "description")
quickSetJsonArr(&bm.Tags, m, "tags")
return true
2023-02-21 06:39:29 +01:00
}
type ResolveItem struct {
2022-12-24 00:56:29 +01:00
Name string
Num int
Id string
Hidden bool
}
type SSHOpts struct {
2022-10-01 01:23:40 +02:00
Local bool `json:"local,omitempty"`
IsSudo bool `json:"issudo,omitempty"`
SSHHost string `json:"sshhost"`
SSHUser string `json:"sshuser"`
2022-10-01 01:23:40 +02:00
SSHOptsStr string `json:"sshopts,omitempty"`
SSHIdentity string `json:"sshidentity,omitempty"`
SSHPort int `json:"sshport,omitempty"`
2022-10-01 02:22:28 +02:00
SSHPassword string `json:"sshpassword,omitempty"`
}
func (opts SSHOpts) GetAuthType() string {
if opts.SSHPassword != "" && opts.SSHIdentity != "" {
return RemoteAuthTypeKeyPassword
}
if opts.SSHIdentity != "" {
return RemoteAuthTypeKey
}
if opts.SSHPassword != "" {
return RemoteAuthTypePassword
}
return RemoteAuthTypeNone
}
type RemoteOptsType struct {
Color string `json:"color"`
}
type OpenAIOptsType struct {
2023-05-04 10:01:13 +02:00
Model string `json:"model"`
APIToken string `json:"apitoken"`
BaseURL string `json:"baseurl,omitempty"`
2023-05-04 10:01:13 +02:00
MaxTokens int `json:"maxtokens,omitempty"`
MaxChoices int `json:"maxchoices,omitempty"`
}
ssh config import (#156) * create migrations for required database change This is a first attempt that does not appear to be working properly. It requires review. * fix errors in db migrations The previous commit had an extra json call that broke the update and did not remove the imported interies during a downgrade. * change migrations to use column instead of json It makes more sense to associate the source of a config with the remote type than the sshopts type. This change makes that clear in the database structure. * ensure adding a remote manually tags correctly Using the usual way of adding a remote should result in a sshconfigsrc of "waveterm-manual". This will be important for filtering out remotes installed manually and remotes installed via import * create basic structure for parsing ssh config This entails creating a new command, making it possible to query only the imported remotes from the database, and implementing the logic to handle all of the updates needed. This needs improvements in a few areas: - the /etc/ssh/config needs to be parsed as well - the logic for editing exisiting imported remotes needs to be written - error handling needs to be improved - update packet responses need to be provided * add sshkey support and implement editing We now search for the ssh identity keyfile and add it if it is found. Additionally, the logic to edit previously imported ssh hosts has been added. * combine hosts from user and system ssh config We now check both the user ~/.ssh/config as well as the /etc/ssh/config for hosts. This loops through each file starting with the user one. For each host, it selects the first pattern without a wildcard and chooses that to be the alias. If any future hosts are found to have the same alias, they are skipped. Errors are raised if neither config file can be opened or no aliases were found. * improve logging and error reporting Error reporting is now shortcircuited in cases of individual remotes in order to allow the other remotes to continue. These errors are now printed to logs instead. * allow imports to edit ssh port Previously, ssh ports could not be edited after the fact. Unfortunately, this can cause problems since the port can be changed in an ssh config file. To address this, we allow imports to change the port if a host with the same canonical name had previously been imported. * fix response to parse command * fix error handline for alias parsing Small mistake of checking for equality instead of inequality * fix the ability to overwrite hostName with alias if ssh_config does not find Hostname, it won't output an error. Now we compare against the result instead of looking for an error. * fix the error catching for User and Port This fixes the same problem where parsing the config doesn't give an error in the case when nothing is found. As before, this checks for a blank result instead. * remove unused code * remove repeated canonical name check The logic that checks for an existing canonical name already exists in the AddRemote function, so it is not needed here. Secondly, we now only allow edits of previously created remotes if they have not been archived. If they have, the usual logic for creating a new remote takes precedence. Lastly, there is no need to archive a remote that has already been archived so an additional check has been added. * allow archives to preserve the SSHConfigSrc * add log message for archiving of imported remotes * create variables for string variants Matches existing code style * add cleanup for opened files * move migration 25 to migration 26 (already merged a migration 25) * fix RemoteRuntimeState in ModelUpdate by moving type to sstore.go. Fix some bugs in remote:parse. Fix key/identityfile, return value, and remote editing (should go through msh). remote sudo. add info messages around parse status * fix issue with archiving the sshconfigsrc A bug in RemoteType's FromMap caused the loss of sshconfigsrc during the conversion. This has been corrected and the schema has been updated. * fix order of archiving removed imported remotes Previously, if the canonical name changed, the code would try to create a new remote before archiving the old one. This did not work if the alias didn't change. Now we archive first and add a new remote after. * fix ability to change port when importing config Importing from sshconfig needs to allow the port to change. This was not happening because of a bug that has been corrected. * always use host in place of hostname Since host is the key actually searched for in the ssh config file, searching for user@hostName may not actually work. To avoid this, we now always use user@host instead. * automatically determine ConnectMode This aims to select a connection mode based off what is provided in the ssh config file. It aims for auto connections when possible but will fall back to manual if we can't easily support it * remove sshkeysource migration number confilict Previously had conflicting migration numbers of 26. The change not in the main branch has been moved to 27 to remove the conflict. * move sshkeysource migration to migration 28 * add WaveOptions flag parsing for ssh config This is currently being used to allow users to force manual connect mode if desired. It will also be used to force skipping options in the future but that is not complete in this commit. * implement ignore flag for ssh config parsing The ignore flag will now archive an imported remote if it previously existed and not create a new remote in its place. * fix discovery of identity file Previously, a ~ in the identity file's path was not expanded to the home dir. Because of this, files with a ~ were previously identified as invalid files. By expanding it during the search, this is no longer the case. * disable frontend edit button for imported remotes Imported Remotes should not be editable in waveterm by users. This edit makes it clear that the button will not work for those cases. Further edits may be needed to explain why it doesn't work and what to do instead. * add backend rejection of updating imported remote As before, we don't want manual editing of an imported remote inside the app. This ensures that it can't happen on the backend. * create tooltips for sshconfig edit/delete buttons For remotes that are imported, edits are not allowed. This adds a tooltip that explains what to do instead. Deleting remotes that are imported is allowed, but they will come back if the user imports again. The tooltip explains a way to avoid this. * add logo after name for imported remotes In the connections screen, there previously was not a way to tell imported connections from manually created connections. This change adds a logo after the imported ones to differentiate them. * small formatting updates * add import tooltip to connection modal Added the logo for an imported config to the connection modal. It also provides a short description when it the mouse hovers over it. * add button to import ssh config Make the command into a button for a simple gui interface. Also ran prettier to clean up some syntax. * remove strict casing on WaveOptions WaveOptions was previously very specific about the casing of the ignore and connectmode subcommands. With this update, the casing is automatically converted to lowercase and can be ignored. * add status dot before name in connections screen * add space and tooltip to connection imported icon * re-prettier
2023-12-28 20:09:41 +01:00
const (
RemoteStatus_Connected = "connected"
RemoteStatus_Connecting = "connecting"
RemoteStatus_Disconnected = "disconnected"
RemoteStatus_Error = "error"
)
type RemoteRuntimeState struct {
RemoteType string `json:"remotetype"`
RemoteId string `json:"remoteid"`
RemoteAlias string `json:"remotealias,omitempty"`
RemoteCanonicalName string `json:"remotecanonicalname"`
RemoteVars map[string]string `json:"remotevars"`
DefaultFeState map[string]string `json:"defaultfestate"`
Status string `json:"status"`
ConnectTimeout int `json:"connecttimeout,omitempty"`
Ssh Fixes and Improvements (#293) * feat: parse multiple identity files in ssh While this does not make it possible to discover multiple identity files in every case, it does make it possible to parse them individually and check for user input if it's required for each one. * chore: remove unnecessary print in updatebus.go * chore: remove unnecessary print in sshclient.go * chore: remove old publicKey auth check With the new callback in place, we no longer need this, so it has been removed. * refactor: move logic for wave and config options The logic for making decisions between details made available from wave and details made available from ssh_config was spread out. This change condenses it into one function for gathering those details and one for picking between them. It also adds a few new keywords but the logic for those hasn't been implemented yet. * feat: allow attempting auth methods in any order While waveterm does not provide the control over which order to attempt yet, it is possible to provide that information in the ssh_config. This change allows that order to take precedence in a case where it is set. * feat: add batch mode support BatchMode turns off user input to enter passwords for ssh. Because we save passwords, we can still attempt these methods but we disable the user interactive prompts in this case. * fix: fix auth ordering and identity files The last few commits introduced a few bugs that are fixed here. The first is that the auth ordering is parsed as a single string and not a list. This is fixed by manually splitting the string into a list. The second is that the copy of identity files was not long enough to copy the contents of the original. This is now updated to use the length of the original in its construction. * deactivate timer while connecting to new ssh The new ssh setup handles timers differently from the old one due to the possibility of asking for user input multiple times. This limited the user input to entirely be done within 15 seconds. This removes that restriction which will allow those timers to increase. It does not impact the legacy ssh systems or the local connections on the new system. * merge branch 'main' into 'ssh--auth-control' This was mostly straightforward, but it appears that a previous commit to main broke the user input modals by deleting a function. This adds that back in addition to the merge. * fix: allow 60 second timeouts for ssh inputs With the previous change, it is now possible to extend the timeout for manual inputs. 60 seconds should be a reasonable starting point. * fix: change size of dummy key to 2048 This fixes the CodeQL scan issue for using a weak key.
2024-02-16 00:58:50 +01:00
CountdownActive bool `json:"countdownactive"`
ssh config import (#156) * create migrations for required database change This is a first attempt that does not appear to be working properly. It requires review. * fix errors in db migrations The previous commit had an extra json call that broke the update and did not remove the imported interies during a downgrade. * change migrations to use column instead of json It makes more sense to associate the source of a config with the remote type than the sshopts type. This change makes that clear in the database structure. * ensure adding a remote manually tags correctly Using the usual way of adding a remote should result in a sshconfigsrc of "waveterm-manual". This will be important for filtering out remotes installed manually and remotes installed via import * create basic structure for parsing ssh config This entails creating a new command, making it possible to query only the imported remotes from the database, and implementing the logic to handle all of the updates needed. This needs improvements in a few areas: - the /etc/ssh/config needs to be parsed as well - the logic for editing exisiting imported remotes needs to be written - error handling needs to be improved - update packet responses need to be provided * add sshkey support and implement editing We now search for the ssh identity keyfile and add it if it is found. Additionally, the logic to edit previously imported ssh hosts has been added. * combine hosts from user and system ssh config We now check both the user ~/.ssh/config as well as the /etc/ssh/config for hosts. This loops through each file starting with the user one. For each host, it selects the first pattern without a wildcard and chooses that to be the alias. If any future hosts are found to have the same alias, they are skipped. Errors are raised if neither config file can be opened or no aliases were found. * improve logging and error reporting Error reporting is now shortcircuited in cases of individual remotes in order to allow the other remotes to continue. These errors are now printed to logs instead. * allow imports to edit ssh port Previously, ssh ports could not be edited after the fact. Unfortunately, this can cause problems since the port can be changed in an ssh config file. To address this, we allow imports to change the port if a host with the same canonical name had previously been imported. * fix response to parse command * fix error handline for alias parsing Small mistake of checking for equality instead of inequality * fix the ability to overwrite hostName with alias if ssh_config does not find Hostname, it won't output an error. Now we compare against the result instead of looking for an error. * fix the error catching for User and Port This fixes the same problem where parsing the config doesn't give an error in the case when nothing is found. As before, this checks for a blank result instead. * remove unused code * remove repeated canonical name check The logic that checks for an existing canonical name already exists in the AddRemote function, so it is not needed here. Secondly, we now only allow edits of previously created remotes if they have not been archived. If they have, the usual logic for creating a new remote takes precedence. Lastly, there is no need to archive a remote that has already been archived so an additional check has been added. * allow archives to preserve the SSHConfigSrc * add log message for archiving of imported remotes * create variables for string variants Matches existing code style * add cleanup for opened files * move migration 25 to migration 26 (already merged a migration 25) * fix RemoteRuntimeState in ModelUpdate by moving type to sstore.go. Fix some bugs in remote:parse. Fix key/identityfile, return value, and remote editing (should go through msh). remote sudo. add info messages around parse status * fix issue with archiving the sshconfigsrc A bug in RemoteType's FromMap caused the loss of sshconfigsrc during the conversion. This has been corrected and the schema has been updated. * fix order of archiving removed imported remotes Previously, if the canonical name changed, the code would try to create a new remote before archiving the old one. This did not work if the alias didn't change. Now we archive first and add a new remote after. * fix ability to change port when importing config Importing from sshconfig needs to allow the port to change. This was not happening because of a bug that has been corrected. * always use host in place of hostname Since host is the key actually searched for in the ssh config file, searching for user@hostName may not actually work. To avoid this, we now always use user@host instead. * automatically determine ConnectMode This aims to select a connection mode based off what is provided in the ssh config file. It aims for auto connections when possible but will fall back to manual if we can't easily support it * remove sshkeysource migration number confilict Previously had conflicting migration numbers of 26. The change not in the main branch has been moved to 27 to remove the conflict. * move sshkeysource migration to migration 28 * add WaveOptions flag parsing for ssh config This is currently being used to allow users to force manual connect mode if desired. It will also be used to force skipping options in the future but that is not complete in this commit. * implement ignore flag for ssh config parsing The ignore flag will now archive an imported remote if it previously existed and not create a new remote in its place. * fix discovery of identity file Previously, a ~ in the identity file's path was not expanded to the home dir. Because of this, files with a ~ were previously identified as invalid files. By expanding it during the search, this is no longer the case. * disable frontend edit button for imported remotes Imported Remotes should not be editable in waveterm by users. This edit makes it clear that the button will not work for those cases. Further edits may be needed to explain why it doesn't work and what to do instead. * add backend rejection of updating imported remote As before, we don't want manual editing of an imported remote inside the app. This ensures that it can't happen on the backend. * create tooltips for sshconfig edit/delete buttons For remotes that are imported, edits are not allowed. This adds a tooltip that explains what to do instead. Deleting remotes that are imported is allowed, but they will come back if the user imports again. The tooltip explains a way to avoid this. * add logo after name for imported remotes In the connections screen, there previously was not a way to tell imported connections from manually created connections. This change adds a logo after the imported ones to differentiate them. * small formatting updates * add import tooltip to connection modal Added the logo for an imported config to the connection modal. It also provides a short description when it the mouse hovers over it. * add button to import ssh config Make the command into a button for a simple gui interface. Also ran prettier to clean up some syntax. * remove strict casing on WaveOptions WaveOptions was previously very specific about the casing of the ignore and connectmode subcommands. With this update, the casing is automatically converted to lowercase and can be ignored. * add status dot before name in connections screen * add space and tooltip to connection imported icon * re-prettier
2023-12-28 20:09:41 +01:00
ErrorStr string `json:"errorstr,omitempty"`
InstallStatus string `json:"installstatus"`
InstallErrorStr string `json:"installerrorstr,omitempty"`
NeedsMShellUpgrade bool `json:"needsmshellupgrade,omitempty"`
NoInitPk bool `json:"noinitpk,omitempty"`
AuthType string `json:"authtype,omitempty"`
ConnectMode string `json:"connectmode"`
AutoInstall bool `json:"autoinstall"`
Archived bool `json:"archived,omitempty"`
RemoteIdx int64 `json:"remoteidx"`
SSHConfigSrc string `json:"sshconfigsrc"`
UName string `json:"uname"`
MShellVersion string `json:"mshellversion"`
WaitingForPassword bool `json:"waitingforpassword,omitempty"`
Local bool `json:"local,omitempty"`
RemoteOpts *RemoteOptsType `json:"remoteopts,omitempty"`
CanComplete bool `json:"cancomplete,omitempty"`
zsh support (#227) adds zsh support to waveterm. big change, lots going on here. lots of other improvements and bug fixes added while debugging and building out the feature. Commits: * refactor shexec parser.go into new package shellenv. separate out bash specific parsing from generic functions * checkpoint * work on refactoring shexec. created two new packages shellapi (for bash/zsh specific stuff), and shellutil (shared between shellapi and shexec) * more refactoring * create shellapi interface to abstract bash specific functionality * more refactoring, move bash shell state parsing to shellapi * move makeRcFile to shellapi. remove all of the 'client' options CLI options from waveshell * get shellType passed through to server/single paths for waveshell * add a local shelltype detector * mock out a zshapi * move shelltype through more of the code * get a command to run via zsh * zsh can now switch directories. poc, needs cleanup * working on ShellState encoding differences between zsh/bash. Working on parsing zsh decls. move utilfn package into waveshell (shouldn't have been in wavesrv) * switch to use []byte for vardecl serialization + diffs * progress on zsh environment. still have issues reconciling init environment with trap environment * fix typeset argument parsing * parse promptvars, more zsh specific ignores * fix bug with promptvar not getting set (wrong check in FeState func) * add sdk (issue #188) to list of rtnstate commands * more zsh compatibility -- working with a larger ohmyzsh environment. ignore more variables, handle exit trap better. unique path/fpath. add a processtype variable to base. * must return a value * zsh alias parsing/restoring. diff changes (and rtnstate changes). introduces linediff v1. * force zmodload of zsh/parameter * starting work on zsh functions * need a v1 of mapdiff as well (to handle null chars) * pack/unpack of ints was wrong (one used int and one use uint). turned out we only ever encoded '0' so it worked. that also means it is safe to change unpack to unpackUInt * reworking for binary encoding of aliases and functions (because of zsh allows any character, including nulls, in names and values) * fixes, working on functions, issue with line endings * zsh functions. lots of ugliness here around dealing with line dicipline and cooked stty. new runcommand function to grab output from a non-tty fd. note that we still to run the actual command in a stty to get the proper output. * write uuid tempdir, cleanup with tmprcfilename code * hack in some simple zsh function declaration finding code for rtnstate. create function diff for rtnstate that supports zsh * make sure key order is constant so shell hashes are consistent * fix problems with state diffs to support new zsh formats. add diff/apply code to shellapi (moved from shellenv), that is now specific to zsh or bash * add log packet and new shellstate packets * switch to shellstate map that's also keyed by shelltype * add shelltype to remoteinstance * remove shell argument from waveshell * added new shelltype statemap to remote.go (msh), deal with fallout * move shellstate out of init packet, and move to an explicit reinit call. try to initialize all of the active shell states * change dont always store init state (only store on demand). initialize shell states on demand (if not already initialized). allow reset to change shells * add shellpref field to remote table. use to drive the default shell choice for new tabs * show shelltag on cmdinput, pass through ri and remote (defaultshellstate) * bump mshell version to v0.4 * better version validation for shellstate. also relax compatibility requirements for diffing states (shelltype + major version need to match) * better error handling, check shellstate compatibility during run (on waveshell server) * add extra separator for bash shellstate processing to deal with spurious output from rc files * special migration for v30 -- flag invalid bash shell states and show special button in UI to fix * format * remove zsh-decls (unused) * remove test code * remove debug print * fix typo
2024-01-17 01:11:04 +01:00
ActiveShells []string `json:"activeshells,omitempty"`
ShellPref string `json:"shellpref,omitempty"`
DefaultShellType string `json:"defaultshelltype,omitempty"`
ssh config import (#156) * create migrations for required database change This is a first attempt that does not appear to be working properly. It requires review. * fix errors in db migrations The previous commit had an extra json call that broke the update and did not remove the imported interies during a downgrade. * change migrations to use column instead of json It makes more sense to associate the source of a config with the remote type than the sshopts type. This change makes that clear in the database structure. * ensure adding a remote manually tags correctly Using the usual way of adding a remote should result in a sshconfigsrc of "waveterm-manual". This will be important for filtering out remotes installed manually and remotes installed via import * create basic structure for parsing ssh config This entails creating a new command, making it possible to query only the imported remotes from the database, and implementing the logic to handle all of the updates needed. This needs improvements in a few areas: - the /etc/ssh/config needs to be parsed as well - the logic for editing exisiting imported remotes needs to be written - error handling needs to be improved - update packet responses need to be provided * add sshkey support and implement editing We now search for the ssh identity keyfile and add it if it is found. Additionally, the logic to edit previously imported ssh hosts has been added. * combine hosts from user and system ssh config We now check both the user ~/.ssh/config as well as the /etc/ssh/config for hosts. This loops through each file starting with the user one. For each host, it selects the first pattern without a wildcard and chooses that to be the alias. If any future hosts are found to have the same alias, they are skipped. Errors are raised if neither config file can be opened or no aliases were found. * improve logging and error reporting Error reporting is now shortcircuited in cases of individual remotes in order to allow the other remotes to continue. These errors are now printed to logs instead. * allow imports to edit ssh port Previously, ssh ports could not be edited after the fact. Unfortunately, this can cause problems since the port can be changed in an ssh config file. To address this, we allow imports to change the port if a host with the same canonical name had previously been imported. * fix response to parse command * fix error handline for alias parsing Small mistake of checking for equality instead of inequality * fix the ability to overwrite hostName with alias if ssh_config does not find Hostname, it won't output an error. Now we compare against the result instead of looking for an error. * fix the error catching for User and Port This fixes the same problem where parsing the config doesn't give an error in the case when nothing is found. As before, this checks for a blank result instead. * remove unused code * remove repeated canonical name check The logic that checks for an existing canonical name already exists in the AddRemote function, so it is not needed here. Secondly, we now only allow edits of previously created remotes if they have not been archived. If they have, the usual logic for creating a new remote takes precedence. Lastly, there is no need to archive a remote that has already been archived so an additional check has been added. * allow archives to preserve the SSHConfigSrc * add log message for archiving of imported remotes * create variables for string variants Matches existing code style * add cleanup for opened files * move migration 25 to migration 26 (already merged a migration 25) * fix RemoteRuntimeState in ModelUpdate by moving type to sstore.go. Fix some bugs in remote:parse. Fix key/identityfile, return value, and remote editing (should go through msh). remote sudo. add info messages around parse status * fix issue with archiving the sshconfigsrc A bug in RemoteType's FromMap caused the loss of sshconfigsrc during the conversion. This has been corrected and the schema has been updated. * fix order of archiving removed imported remotes Previously, if the canonical name changed, the code would try to create a new remote before archiving the old one. This did not work if the alias didn't change. Now we archive first and add a new remote after. * fix ability to change port when importing config Importing from sshconfig needs to allow the port to change. This was not happening because of a bug that has been corrected. * always use host in place of hostname Since host is the key actually searched for in the ssh config file, searching for user@hostName may not actually work. To avoid this, we now always use user@host instead. * automatically determine ConnectMode This aims to select a connection mode based off what is provided in the ssh config file. It aims for auto connections when possible but will fall back to manual if we can't easily support it * remove sshkeysource migration number confilict Previously had conflicting migration numbers of 26. The change not in the main branch has been moved to 27 to remove the conflict. * move sshkeysource migration to migration 28 * add WaveOptions flag parsing for ssh config This is currently being used to allow users to force manual connect mode if desired. It will also be used to force skipping options in the future but that is not complete in this commit. * implement ignore flag for ssh config parsing The ignore flag will now archive an imported remote if it previously existed and not create a new remote in its place. * fix discovery of identity file Previously, a ~ in the identity file's path was not expanded to the home dir. Because of this, files with a ~ were previously identified as invalid files. By expanding it during the search, this is no longer the case. * disable frontend edit button for imported remotes Imported Remotes should not be editable in waveterm by users. This edit makes it clear that the button will not work for those cases. Further edits may be needed to explain why it doesn't work and what to do instead. * add backend rejection of updating imported remote As before, we don't want manual editing of an imported remote inside the app. This ensures that it can't happen on the backend. * create tooltips for sshconfig edit/delete buttons For remotes that are imported, edits are not allowed. This adds a tooltip that explains what to do instead. Deleting remotes that are imported is allowed, but they will come back if the user imports again. The tooltip explains a way to avoid this. * add logo after name for imported remotes In the connections screen, there previously was not a way to tell imported connections from manually created connections. This change adds a logo after the imported ones to differentiate them. * small formatting updates * add import tooltip to connection modal Added the logo for an imported config to the connection modal. It also provides a short description when it the mouse hovers over it. * add button to import ssh config Make the command into a button for a simple gui interface. Also ran prettier to clean up some syntax. * remove strict casing on WaveOptions WaveOptions was previously very specific about the casing of the ignore and connectmode subcommands. With this update, the casing is automatically converted to lowercase and can be ignored. * add status dot before name in connections screen * add space and tooltip to connection imported icon * re-prettier
2023-12-28 20:09:41 +01:00
}
func (state RemoteRuntimeState) IsConnected() bool {
return state.Status == RemoteStatus_Connected
}
func (state RemoteRuntimeState) GetBaseDisplayName() string {
if state.RemoteAlias != "" {
return state.RemoteAlias
}
return state.RemoteCanonicalName
}
func (state RemoteRuntimeState) GetDisplayName(rptr *RemotePtrType) string {
baseDisplayName := state.GetBaseDisplayName()
if rptr == nil {
return baseDisplayName
}
return rptr.GetDisplayName(baseDisplayName)
}
func (state RemoteRuntimeState) ExpandHomeDir(pathStr string) (string, error) {
if pathStr != "~" && !strings.HasPrefix(pathStr, "~/") {
return pathStr, nil
}
homeDir := state.RemoteVars["home"]
if homeDir == "" {
return "", fmt.Errorf("remote does not have HOME set, cannot do ~ expansion")
}
if pathStr == "~" {
return homeDir, nil
}
return path.Join(homeDir, pathStr[2:]), nil
}
func (RemoteRuntimeState) GetType() string {
return "remote"
}
type RemoteType struct {
RemoteId string `json:"remoteid"`
RemoteType string `json:"remotetype"`
RemoteAlias string `json:"remotealias"`
RemoteCanonicalName string `json:"remotecanonicalname"`
RemoteOpts *RemoteOptsType `json:"remoteopts"`
LastConnectTs int64 `json:"lastconnectts"`
RemoteIdx int64 `json:"remoteidx"`
Archived bool `json:"archived"`
// SSH fields
ssh config import (#156) * create migrations for required database change This is a first attempt that does not appear to be working properly. It requires review. * fix errors in db migrations The previous commit had an extra json call that broke the update and did not remove the imported interies during a downgrade. * change migrations to use column instead of json It makes more sense to associate the source of a config with the remote type than the sshopts type. This change makes that clear in the database structure. * ensure adding a remote manually tags correctly Using the usual way of adding a remote should result in a sshconfigsrc of "waveterm-manual". This will be important for filtering out remotes installed manually and remotes installed via import * create basic structure for parsing ssh config This entails creating a new command, making it possible to query only the imported remotes from the database, and implementing the logic to handle all of the updates needed. This needs improvements in a few areas: - the /etc/ssh/config needs to be parsed as well - the logic for editing exisiting imported remotes needs to be written - error handling needs to be improved - update packet responses need to be provided * add sshkey support and implement editing We now search for the ssh identity keyfile and add it if it is found. Additionally, the logic to edit previously imported ssh hosts has been added. * combine hosts from user and system ssh config We now check both the user ~/.ssh/config as well as the /etc/ssh/config for hosts. This loops through each file starting with the user one. For each host, it selects the first pattern without a wildcard and chooses that to be the alias. If any future hosts are found to have the same alias, they are skipped. Errors are raised if neither config file can be opened or no aliases were found. * improve logging and error reporting Error reporting is now shortcircuited in cases of individual remotes in order to allow the other remotes to continue. These errors are now printed to logs instead. * allow imports to edit ssh port Previously, ssh ports could not be edited after the fact. Unfortunately, this can cause problems since the port can be changed in an ssh config file. To address this, we allow imports to change the port if a host with the same canonical name had previously been imported. * fix response to parse command * fix error handline for alias parsing Small mistake of checking for equality instead of inequality * fix the ability to overwrite hostName with alias if ssh_config does not find Hostname, it won't output an error. Now we compare against the result instead of looking for an error. * fix the error catching for User and Port This fixes the same problem where parsing the config doesn't give an error in the case when nothing is found. As before, this checks for a blank result instead. * remove unused code * remove repeated canonical name check The logic that checks for an existing canonical name already exists in the AddRemote function, so it is not needed here. Secondly, we now only allow edits of previously created remotes if they have not been archived. If they have, the usual logic for creating a new remote takes precedence. Lastly, there is no need to archive a remote that has already been archived so an additional check has been added. * allow archives to preserve the SSHConfigSrc * add log message for archiving of imported remotes * create variables for string variants Matches existing code style * add cleanup for opened files * move migration 25 to migration 26 (already merged a migration 25) * fix RemoteRuntimeState in ModelUpdate by moving type to sstore.go. Fix some bugs in remote:parse. Fix key/identityfile, return value, and remote editing (should go through msh). remote sudo. add info messages around parse status * fix issue with archiving the sshconfigsrc A bug in RemoteType's FromMap caused the loss of sshconfigsrc during the conversion. This has been corrected and the schema has been updated. * fix order of archiving removed imported remotes Previously, if the canonical name changed, the code would try to create a new remote before archiving the old one. This did not work if the alias didn't change. Now we archive first and add a new remote after. * fix ability to change port when importing config Importing from sshconfig needs to allow the port to change. This was not happening because of a bug that has been corrected. * always use host in place of hostname Since host is the key actually searched for in the ssh config file, searching for user@hostName may not actually work. To avoid this, we now always use user@host instead. * automatically determine ConnectMode This aims to select a connection mode based off what is provided in the ssh config file. It aims for auto connections when possible but will fall back to manual if we can't easily support it * remove sshkeysource migration number confilict Previously had conflicting migration numbers of 26. The change not in the main branch has been moved to 27 to remove the conflict. * move sshkeysource migration to migration 28 * add WaveOptions flag parsing for ssh config This is currently being used to allow users to force manual connect mode if desired. It will also be used to force skipping options in the future but that is not complete in this commit. * implement ignore flag for ssh config parsing The ignore flag will now archive an imported remote if it previously existed and not create a new remote in its place. * fix discovery of identity file Previously, a ~ in the identity file's path was not expanded to the home dir. Because of this, files with a ~ were previously identified as invalid files. By expanding it during the search, this is no longer the case. * disable frontend edit button for imported remotes Imported Remotes should not be editable in waveterm by users. This edit makes it clear that the button will not work for those cases. Further edits may be needed to explain why it doesn't work and what to do instead. * add backend rejection of updating imported remote As before, we don't want manual editing of an imported remote inside the app. This ensures that it can't happen on the backend. * create tooltips for sshconfig edit/delete buttons For remotes that are imported, edits are not allowed. This adds a tooltip that explains what to do instead. Deleting remotes that are imported is allowed, but they will come back if the user imports again. The tooltip explains a way to avoid this. * add logo after name for imported remotes In the connections screen, there previously was not a way to tell imported connections from manually created connections. This change adds a logo after the imported ones to differentiate them. * small formatting updates * add import tooltip to connection modal Added the logo for an imported config to the connection modal. It also provides a short description when it the mouse hovers over it. * add button to import ssh config Make the command into a button for a simple gui interface. Also ran prettier to clean up some syntax. * remove strict casing on WaveOptions WaveOptions was previously very specific about the casing of the ignore and connectmode subcommands. With this update, the casing is automatically converted to lowercase and can be ignored. * add status dot before name in connections screen * add space and tooltip to connection imported icon * re-prettier
2023-12-28 20:09:41 +01:00
Local bool `json:"local"`
RemoteUser string `json:"remoteuser"`
RemoteHost string `json:"remotehost"`
ConnectMode string `json:"connectmode"`
AutoInstall bool `json:"autoinstall"`
SSHOpts *SSHOpts `json:"sshopts"`
StateVars map[string]string `json:"statevars"`
SSHConfigSrc string `json:"sshconfigsrc"`
zsh support (#227) adds zsh support to waveterm. big change, lots going on here. lots of other improvements and bug fixes added while debugging and building out the feature. Commits: * refactor shexec parser.go into new package shellenv. separate out bash specific parsing from generic functions * checkpoint * work on refactoring shexec. created two new packages shellapi (for bash/zsh specific stuff), and shellutil (shared between shellapi and shexec) * more refactoring * create shellapi interface to abstract bash specific functionality * more refactoring, move bash shell state parsing to shellapi * move makeRcFile to shellapi. remove all of the 'client' options CLI options from waveshell * get shellType passed through to server/single paths for waveshell * add a local shelltype detector * mock out a zshapi * move shelltype through more of the code * get a command to run via zsh * zsh can now switch directories. poc, needs cleanup * working on ShellState encoding differences between zsh/bash. Working on parsing zsh decls. move utilfn package into waveshell (shouldn't have been in wavesrv) * switch to use []byte for vardecl serialization + diffs * progress on zsh environment. still have issues reconciling init environment with trap environment * fix typeset argument parsing * parse promptvars, more zsh specific ignores * fix bug with promptvar not getting set (wrong check in FeState func) * add sdk (issue #188) to list of rtnstate commands * more zsh compatibility -- working with a larger ohmyzsh environment. ignore more variables, handle exit trap better. unique path/fpath. add a processtype variable to base. * must return a value * zsh alias parsing/restoring. diff changes (and rtnstate changes). introduces linediff v1. * force zmodload of zsh/parameter * starting work on zsh functions * need a v1 of mapdiff as well (to handle null chars) * pack/unpack of ints was wrong (one used int and one use uint). turned out we only ever encoded '0' so it worked. that also means it is safe to change unpack to unpackUInt * reworking for binary encoding of aliases and functions (because of zsh allows any character, including nulls, in names and values) * fixes, working on functions, issue with line endings * zsh functions. lots of ugliness here around dealing with line dicipline and cooked stty. new runcommand function to grab output from a non-tty fd. note that we still to run the actual command in a stty to get the proper output. * write uuid tempdir, cleanup with tmprcfilename code * hack in some simple zsh function declaration finding code for rtnstate. create function diff for rtnstate that supports zsh * make sure key order is constant so shell hashes are consistent * fix problems with state diffs to support new zsh formats. add diff/apply code to shellapi (moved from shellenv), that is now specific to zsh or bash * add log packet and new shellstate packets * switch to shellstate map that's also keyed by shelltype * add shelltype to remoteinstance * remove shell argument from waveshell * added new shelltype statemap to remote.go (msh), deal with fallout * move shellstate out of init packet, and move to an explicit reinit call. try to initialize all of the active shell states * change dont always store init state (only store on demand). initialize shell states on demand (if not already initialized). allow reset to change shells * add shellpref field to remote table. use to drive the default shell choice for new tabs * show shelltag on cmdinput, pass through ri and remote (defaultshellstate) * bump mshell version to v0.4 * better version validation for shellstate. also relax compatibility requirements for diffing states (shelltype + major version need to match) * better error handling, check shellstate compatibility during run (on waveshell server) * add extra separator for bash shellstate processing to deal with spurious output from rc files * special migration for v30 -- flag invalid bash shell states and show special button in UI to fix * format * remove zsh-decls (unused) * remove test code * remove debug print * fix typo
2024-01-17 01:11:04 +01:00
ShellPref string `json:"shellpref"` // bash, zsh, or detect
zsh support (#227) adds zsh support to waveterm. big change, lots going on here. lots of other improvements and bug fixes added while debugging and building out the feature. Commits: * refactor shexec parser.go into new package shellenv. separate out bash specific parsing from generic functions * checkpoint * work on refactoring shexec. created two new packages shellapi (for bash/zsh specific stuff), and shellutil (shared between shellapi and shexec) * more refactoring * create shellapi interface to abstract bash specific functionality * more refactoring, move bash shell state parsing to shellapi * move makeRcFile to shellapi. remove all of the 'client' options CLI options from waveshell * get shellType passed through to server/single paths for waveshell * add a local shelltype detector * mock out a zshapi * move shelltype through more of the code * get a command to run via zsh * zsh can now switch directories. poc, needs cleanup * working on ShellState encoding differences between zsh/bash. Working on parsing zsh decls. move utilfn package into waveshell (shouldn't have been in wavesrv) * switch to use []byte for vardecl serialization + diffs * progress on zsh environment. still have issues reconciling init environment with trap environment * fix typeset argument parsing * parse promptvars, more zsh specific ignores * fix bug with promptvar not getting set (wrong check in FeState func) * add sdk (issue #188) to list of rtnstate commands * more zsh compatibility -- working with a larger ohmyzsh environment. ignore more variables, handle exit trap better. unique path/fpath. add a processtype variable to base. * must return a value * zsh alias parsing/restoring. diff changes (and rtnstate changes). introduces linediff v1. * force zmodload of zsh/parameter * starting work on zsh functions * need a v1 of mapdiff as well (to handle null chars) * pack/unpack of ints was wrong (one used int and one use uint). turned out we only ever encoded '0' so it worked. that also means it is safe to change unpack to unpackUInt * reworking for binary encoding of aliases and functions (because of zsh allows any character, including nulls, in names and values) * fixes, working on functions, issue with line endings * zsh functions. lots of ugliness here around dealing with line dicipline and cooked stty. new runcommand function to grab output from a non-tty fd. note that we still to run the actual command in a stty to get the proper output. * write uuid tempdir, cleanup with tmprcfilename code * hack in some simple zsh function declaration finding code for rtnstate. create function diff for rtnstate that supports zsh * make sure key order is constant so shell hashes are consistent * fix problems with state diffs to support new zsh formats. add diff/apply code to shellapi (moved from shellenv), that is now specific to zsh or bash * add log packet and new shellstate packets * switch to shellstate map that's also keyed by shelltype * add shelltype to remoteinstance * remove shell argument from waveshell * added new shelltype statemap to remote.go (msh), deal with fallout * move shellstate out of init packet, and move to an explicit reinit call. try to initialize all of the active shell states * change dont always store init state (only store on demand). initialize shell states on demand (if not already initialized). allow reset to change shells * add shellpref field to remote table. use to drive the default shell choice for new tabs * show shelltag on cmdinput, pass through ri and remote (defaultshellstate) * bump mshell version to v0.4 * better version validation for shellstate. also relax compatibility requirements for diffing states (shelltype + major version need to match) * better error handling, check shellstate compatibility during run (on waveshell server) * add extra separator for bash shellstate processing to deal with spurious output from rc files * special migration for v30 -- flag invalid bash shell states and show special button in UI to fix * format * remove zsh-decls (unused) * remove test code * remove debug print * fix typo
2024-01-17 01:11:04 +01:00
// OpenAI fields (unused)
OpenAIOpts *OpenAIOptsType `json:"openaiopts,omitempty"`
}
func (r *RemoteType) IsLocal() bool {
return r.Local && !r.IsSudo()
}
func (r *RemoteType) IsSudo() bool {
return r.SSHOpts != nil && r.SSHOpts.IsSudo
2022-08-17 00:08:28 +02:00
}
func (r *RemoteType) GetName() string {
if r.RemoteAlias != "" {
return r.RemoteAlias
}
2022-09-14 02:11:36 +02:00
return r.RemoteCanonicalName
}
type CmdType struct {
2023-07-31 02:16:43 +02:00
ScreenId string `json:"screenid"`
LineId string `json:"lineid"`
Remote RemotePtrType `json:"remote"`
CmdStr string `json:"cmdstr"`
RawCmdStr string `json:"rawcmdstr"`
FeState map[string]string `json:"festate"`
StatePtr ShellStatePtr `json:"state"`
TermOpts TermOpts `json:"termopts"`
OrigTermOpts TermOpts `json:"origtermopts"`
Status string `json:"status"`
CmdPid int `json:"cmdpid"`
RemotePid int `json:"remotepid"`
RestartTs int64 `json:"restartts,omitempty"`
2023-07-31 02:16:43 +02:00
DoneTs int64 `json:"donets"`
ExitCode int `json:"exitcode"`
DurationMs int `json:"durationms"`
RunOut []packet.PacketType `json:"runout,omitempty"`
RtnState bool `json:"rtnstate,omitempty"`
RtnStatePtr ShellStatePtr `json:"rtnstateptr,omitempty"`
Remove bool `json:"remove,omitempty"` // not persisted to DB
Restarted bool `json:"restarted,omitempty"` // not persisted to DB
2022-07-07 09:10:37 +02:00
}
func (CmdType) GetType() string {
return "cmd"
}
func (r *RemoteType) ToMap() map[string]interface{} {
rtn := make(map[string]interface{})
rtn["remoteid"] = r.RemoteId
rtn["remotetype"] = r.RemoteType
2022-08-17 00:08:28 +02:00
rtn["remotealias"] = r.RemoteAlias
rtn["remotecanonicalname"] = r.RemoteCanonicalName
rtn["remoteuser"] = r.RemoteUser
rtn["remotehost"] = r.RemoteHost
rtn["connectmode"] = r.ConnectMode
rtn["autoinstall"] = r.AutoInstall
rtn["sshopts"] = quickJson(r.SSHOpts)
rtn["remoteopts"] = quickJson(r.RemoteOpts)
rtn["lastconnectts"] = r.LastConnectTs
2022-09-14 02:11:36 +02:00
rtn["archived"] = r.Archived
2022-09-14 21:06:55 +02:00
rtn["remoteidx"] = r.RemoteIdx
rtn["local"] = r.Local
rtn["statevars"] = quickJson(r.StateVars)
ssh config import (#156) * create migrations for required database change This is a first attempt that does not appear to be working properly. It requires review. * fix errors in db migrations The previous commit had an extra json call that broke the update and did not remove the imported interies during a downgrade. * change migrations to use column instead of json It makes more sense to associate the source of a config with the remote type than the sshopts type. This change makes that clear in the database structure. * ensure adding a remote manually tags correctly Using the usual way of adding a remote should result in a sshconfigsrc of "waveterm-manual". This will be important for filtering out remotes installed manually and remotes installed via import * create basic structure for parsing ssh config This entails creating a new command, making it possible to query only the imported remotes from the database, and implementing the logic to handle all of the updates needed. This needs improvements in a few areas: - the /etc/ssh/config needs to be parsed as well - the logic for editing exisiting imported remotes needs to be written - error handling needs to be improved - update packet responses need to be provided * add sshkey support and implement editing We now search for the ssh identity keyfile and add it if it is found. Additionally, the logic to edit previously imported ssh hosts has been added. * combine hosts from user and system ssh config We now check both the user ~/.ssh/config as well as the /etc/ssh/config for hosts. This loops through each file starting with the user one. For each host, it selects the first pattern without a wildcard and chooses that to be the alias. If any future hosts are found to have the same alias, they are skipped. Errors are raised if neither config file can be opened or no aliases were found. * improve logging and error reporting Error reporting is now shortcircuited in cases of individual remotes in order to allow the other remotes to continue. These errors are now printed to logs instead. * allow imports to edit ssh port Previously, ssh ports could not be edited after the fact. Unfortunately, this can cause problems since the port can be changed in an ssh config file. To address this, we allow imports to change the port if a host with the same canonical name had previously been imported. * fix response to parse command * fix error handline for alias parsing Small mistake of checking for equality instead of inequality * fix the ability to overwrite hostName with alias if ssh_config does not find Hostname, it won't output an error. Now we compare against the result instead of looking for an error. * fix the error catching for User and Port This fixes the same problem where parsing the config doesn't give an error in the case when nothing is found. As before, this checks for a blank result instead. * remove unused code * remove repeated canonical name check The logic that checks for an existing canonical name already exists in the AddRemote function, so it is not needed here. Secondly, we now only allow edits of previously created remotes if they have not been archived. If they have, the usual logic for creating a new remote takes precedence. Lastly, there is no need to archive a remote that has already been archived so an additional check has been added. * allow archives to preserve the SSHConfigSrc * add log message for archiving of imported remotes * create variables for string variants Matches existing code style * add cleanup for opened files * move migration 25 to migration 26 (already merged a migration 25) * fix RemoteRuntimeState in ModelUpdate by moving type to sstore.go. Fix some bugs in remote:parse. Fix key/identityfile, return value, and remote editing (should go through msh). remote sudo. add info messages around parse status * fix issue with archiving the sshconfigsrc A bug in RemoteType's FromMap caused the loss of sshconfigsrc during the conversion. This has been corrected and the schema has been updated. * fix order of archiving removed imported remotes Previously, if the canonical name changed, the code would try to create a new remote before archiving the old one. This did not work if the alias didn't change. Now we archive first and add a new remote after. * fix ability to change port when importing config Importing from sshconfig needs to allow the port to change. This was not happening because of a bug that has been corrected. * always use host in place of hostname Since host is the key actually searched for in the ssh config file, searching for user@hostName may not actually work. To avoid this, we now always use user@host instead. * automatically determine ConnectMode This aims to select a connection mode based off what is provided in the ssh config file. It aims for auto connections when possible but will fall back to manual if we can't easily support it * remove sshkeysource migration number confilict Previously had conflicting migration numbers of 26. The change not in the main branch has been moved to 27 to remove the conflict. * move sshkeysource migration to migration 28 * add WaveOptions flag parsing for ssh config This is currently being used to allow users to force manual connect mode if desired. It will also be used to force skipping options in the future but that is not complete in this commit. * implement ignore flag for ssh config parsing The ignore flag will now archive an imported remote if it previously existed and not create a new remote in its place. * fix discovery of identity file Previously, a ~ in the identity file's path was not expanded to the home dir. Because of this, files with a ~ were previously identified as invalid files. By expanding it during the search, this is no longer the case. * disable frontend edit button for imported remotes Imported Remotes should not be editable in waveterm by users. This edit makes it clear that the button will not work for those cases. Further edits may be needed to explain why it doesn't work and what to do instead. * add backend rejection of updating imported remote As before, we don't want manual editing of an imported remote inside the app. This ensures that it can't happen on the backend. * create tooltips for sshconfig edit/delete buttons For remotes that are imported, edits are not allowed. This adds a tooltip that explains what to do instead. Deleting remotes that are imported is allowed, but they will come back if the user imports again. The tooltip explains a way to avoid this. * add logo after name for imported remotes In the connections screen, there previously was not a way to tell imported connections from manually created connections. This change adds a logo after the imported ones to differentiate them. * small formatting updates * add import tooltip to connection modal Added the logo for an imported config to the connection modal. It also provides a short description when it the mouse hovers over it. * add button to import ssh config Make the command into a button for a simple gui interface. Also ran prettier to clean up some syntax. * remove strict casing on WaveOptions WaveOptions was previously very specific about the casing of the ignore and connectmode subcommands. With this update, the casing is automatically converted to lowercase and can be ignored. * add status dot before name in connections screen * add space and tooltip to connection imported icon * re-prettier
2023-12-28 20:09:41 +01:00
rtn["sshconfigsrc"] = r.SSHConfigSrc
rtn["openaiopts"] = quickJson(r.OpenAIOpts)
zsh support (#227) adds zsh support to waveterm. big change, lots going on here. lots of other improvements and bug fixes added while debugging and building out the feature. Commits: * refactor shexec parser.go into new package shellenv. separate out bash specific parsing from generic functions * checkpoint * work on refactoring shexec. created two new packages shellapi (for bash/zsh specific stuff), and shellutil (shared between shellapi and shexec) * more refactoring * create shellapi interface to abstract bash specific functionality * more refactoring, move bash shell state parsing to shellapi * move makeRcFile to shellapi. remove all of the 'client' options CLI options from waveshell * get shellType passed through to server/single paths for waveshell * add a local shelltype detector * mock out a zshapi * move shelltype through more of the code * get a command to run via zsh * zsh can now switch directories. poc, needs cleanup * working on ShellState encoding differences between zsh/bash. Working on parsing zsh decls. move utilfn package into waveshell (shouldn't have been in wavesrv) * switch to use []byte for vardecl serialization + diffs * progress on zsh environment. still have issues reconciling init environment with trap environment * fix typeset argument parsing * parse promptvars, more zsh specific ignores * fix bug with promptvar not getting set (wrong check in FeState func) * add sdk (issue #188) to list of rtnstate commands * more zsh compatibility -- working with a larger ohmyzsh environment. ignore more variables, handle exit trap better. unique path/fpath. add a processtype variable to base. * must return a value * zsh alias parsing/restoring. diff changes (and rtnstate changes). introduces linediff v1. * force zmodload of zsh/parameter * starting work on zsh functions * need a v1 of mapdiff as well (to handle null chars) * pack/unpack of ints was wrong (one used int and one use uint). turned out we only ever encoded '0' so it worked. that also means it is safe to change unpack to unpackUInt * reworking for binary encoding of aliases and functions (because of zsh allows any character, including nulls, in names and values) * fixes, working on functions, issue with line endings * zsh functions. lots of ugliness here around dealing with line dicipline and cooked stty. new runcommand function to grab output from a non-tty fd. note that we still to run the actual command in a stty to get the proper output. * write uuid tempdir, cleanup with tmprcfilename code * hack in some simple zsh function declaration finding code for rtnstate. create function diff for rtnstate that supports zsh * make sure key order is constant so shell hashes are consistent * fix problems with state diffs to support new zsh formats. add diff/apply code to shellapi (moved from shellenv), that is now specific to zsh or bash * add log packet and new shellstate packets * switch to shellstate map that's also keyed by shelltype * add shelltype to remoteinstance * remove shell argument from waveshell * added new shelltype statemap to remote.go (msh), deal with fallout * move shellstate out of init packet, and move to an explicit reinit call. try to initialize all of the active shell states * change dont always store init state (only store on demand). initialize shell states on demand (if not already initialized). allow reset to change shells * add shellpref field to remote table. use to drive the default shell choice for new tabs * show shelltag on cmdinput, pass through ri and remote (defaultshellstate) * bump mshell version to v0.4 * better version validation for shellstate. also relax compatibility requirements for diffing states (shelltype + major version need to match) * better error handling, check shellstate compatibility during run (on waveshell server) * add extra separator for bash shellstate processing to deal with spurious output from rc files * special migration for v30 -- flag invalid bash shell states and show special button in UI to fix * format * remove zsh-decls (unused) * remove test code * remove debug print * fix typo
2024-01-17 01:11:04 +01:00
rtn["shellpref"] = r.ShellPref
return rtn
}
func (r *RemoteType) FromMap(m map[string]interface{}) bool {
quickSetStr(&r.RemoteId, m, "remoteid")
quickSetStr(&r.RemoteType, m, "remotetype")
2022-08-17 00:08:28 +02:00
quickSetStr(&r.RemoteAlias, m, "remotealias")
quickSetStr(&r.RemoteCanonicalName, m, "remotecanonicalname")
quickSetStr(&r.RemoteUser, m, "remoteuser")
quickSetStr(&r.RemoteHost, m, "remotehost")
quickSetStr(&r.ConnectMode, m, "connectmode")
quickSetBool(&r.AutoInstall, m, "autoinstall")
quickSetJson(&r.SSHOpts, m, "sshopts")
quickSetJson(&r.RemoteOpts, m, "remoteopts")
quickSetInt64(&r.LastConnectTs, m, "lastconnectts")
2022-09-14 02:11:36 +02:00
quickSetBool(&r.Archived, m, "archived")
2022-09-14 21:06:55 +02:00
quickSetInt64(&r.RemoteIdx, m, "remoteidx")
quickSetBool(&r.Local, m, "local")
quickSetJson(&r.StateVars, m, "statevars")
ssh config import (#156) * create migrations for required database change This is a first attempt that does not appear to be working properly. It requires review. * fix errors in db migrations The previous commit had an extra json call that broke the update and did not remove the imported interies during a downgrade. * change migrations to use column instead of json It makes more sense to associate the source of a config with the remote type than the sshopts type. This change makes that clear in the database structure. * ensure adding a remote manually tags correctly Using the usual way of adding a remote should result in a sshconfigsrc of "waveterm-manual". This will be important for filtering out remotes installed manually and remotes installed via import * create basic structure for parsing ssh config This entails creating a new command, making it possible to query only the imported remotes from the database, and implementing the logic to handle all of the updates needed. This needs improvements in a few areas: - the /etc/ssh/config needs to be parsed as well - the logic for editing exisiting imported remotes needs to be written - error handling needs to be improved - update packet responses need to be provided * add sshkey support and implement editing We now search for the ssh identity keyfile and add it if it is found. Additionally, the logic to edit previously imported ssh hosts has been added. * combine hosts from user and system ssh config We now check both the user ~/.ssh/config as well as the /etc/ssh/config for hosts. This loops through each file starting with the user one. For each host, it selects the first pattern without a wildcard and chooses that to be the alias. If any future hosts are found to have the same alias, they are skipped. Errors are raised if neither config file can be opened or no aliases were found. * improve logging and error reporting Error reporting is now shortcircuited in cases of individual remotes in order to allow the other remotes to continue. These errors are now printed to logs instead. * allow imports to edit ssh port Previously, ssh ports could not be edited after the fact. Unfortunately, this can cause problems since the port can be changed in an ssh config file. To address this, we allow imports to change the port if a host with the same canonical name had previously been imported. * fix response to parse command * fix error handline for alias parsing Small mistake of checking for equality instead of inequality * fix the ability to overwrite hostName with alias if ssh_config does not find Hostname, it won't output an error. Now we compare against the result instead of looking for an error. * fix the error catching for User and Port This fixes the same problem where parsing the config doesn't give an error in the case when nothing is found. As before, this checks for a blank result instead. * remove unused code * remove repeated canonical name check The logic that checks for an existing canonical name already exists in the AddRemote function, so it is not needed here. Secondly, we now only allow edits of previously created remotes if they have not been archived. If they have, the usual logic for creating a new remote takes precedence. Lastly, there is no need to archive a remote that has already been archived so an additional check has been added. * allow archives to preserve the SSHConfigSrc * add log message for archiving of imported remotes * create variables for string variants Matches existing code style * add cleanup for opened files * move migration 25 to migration 26 (already merged a migration 25) * fix RemoteRuntimeState in ModelUpdate by moving type to sstore.go. Fix some bugs in remote:parse. Fix key/identityfile, return value, and remote editing (should go through msh). remote sudo. add info messages around parse status * fix issue with archiving the sshconfigsrc A bug in RemoteType's FromMap caused the loss of sshconfigsrc during the conversion. This has been corrected and the schema has been updated. * fix order of archiving removed imported remotes Previously, if the canonical name changed, the code would try to create a new remote before archiving the old one. This did not work if the alias didn't change. Now we archive first and add a new remote after. * fix ability to change port when importing config Importing from sshconfig needs to allow the port to change. This was not happening because of a bug that has been corrected. * always use host in place of hostname Since host is the key actually searched for in the ssh config file, searching for user@hostName may not actually work. To avoid this, we now always use user@host instead. * automatically determine ConnectMode This aims to select a connection mode based off what is provided in the ssh config file. It aims for auto connections when possible but will fall back to manual if we can't easily support it * remove sshkeysource migration number confilict Previously had conflicting migration numbers of 26. The change not in the main branch has been moved to 27 to remove the conflict. * move sshkeysource migration to migration 28 * add WaveOptions flag parsing for ssh config This is currently being used to allow users to force manual connect mode if desired. It will also be used to force skipping options in the future but that is not complete in this commit. * implement ignore flag for ssh config parsing The ignore flag will now archive an imported remote if it previously existed and not create a new remote in its place. * fix discovery of identity file Previously, a ~ in the identity file's path was not expanded to the home dir. Because of this, files with a ~ were previously identified as invalid files. By expanding it during the search, this is no longer the case. * disable frontend edit button for imported remotes Imported Remotes should not be editable in waveterm by users. This edit makes it clear that the button will not work for those cases. Further edits may be needed to explain why it doesn't work and what to do instead. * add backend rejection of updating imported remote As before, we don't want manual editing of an imported remote inside the app. This ensures that it can't happen on the backend. * create tooltips for sshconfig edit/delete buttons For remotes that are imported, edits are not allowed. This adds a tooltip that explains what to do instead. Deleting remotes that are imported is allowed, but they will come back if the user imports again. The tooltip explains a way to avoid this. * add logo after name for imported remotes In the connections screen, there previously was not a way to tell imported connections from manually created connections. This change adds a logo after the imported ones to differentiate them. * small formatting updates * add import tooltip to connection modal Added the logo for an imported config to the connection modal. It also provides a short description when it the mouse hovers over it. * add button to import ssh config Make the command into a button for a simple gui interface. Also ran prettier to clean up some syntax. * remove strict casing on WaveOptions WaveOptions was previously very specific about the casing of the ignore and connectmode subcommands. With this update, the casing is automatically converted to lowercase and can be ignored. * add status dot before name in connections screen * add space and tooltip to connection imported icon * re-prettier
2023-12-28 20:09:41 +01:00
quickSetStr(&r.SSHConfigSrc, m, "sshconfigsrc")
quickSetJson(&r.OpenAIOpts, m, "openaiopts")
zsh support (#227) adds zsh support to waveterm. big change, lots going on here. lots of other improvements and bug fixes added while debugging and building out the feature. Commits: * refactor shexec parser.go into new package shellenv. separate out bash specific parsing from generic functions * checkpoint * work on refactoring shexec. created two new packages shellapi (for bash/zsh specific stuff), and shellutil (shared between shellapi and shexec) * more refactoring * create shellapi interface to abstract bash specific functionality * more refactoring, move bash shell state parsing to shellapi * move makeRcFile to shellapi. remove all of the 'client' options CLI options from waveshell * get shellType passed through to server/single paths for waveshell * add a local shelltype detector * mock out a zshapi * move shelltype through more of the code * get a command to run via zsh * zsh can now switch directories. poc, needs cleanup * working on ShellState encoding differences between zsh/bash. Working on parsing zsh decls. move utilfn package into waveshell (shouldn't have been in wavesrv) * switch to use []byte for vardecl serialization + diffs * progress on zsh environment. still have issues reconciling init environment with trap environment * fix typeset argument parsing * parse promptvars, more zsh specific ignores * fix bug with promptvar not getting set (wrong check in FeState func) * add sdk (issue #188) to list of rtnstate commands * more zsh compatibility -- working with a larger ohmyzsh environment. ignore more variables, handle exit trap better. unique path/fpath. add a processtype variable to base. * must return a value * zsh alias parsing/restoring. diff changes (and rtnstate changes). introduces linediff v1. * force zmodload of zsh/parameter * starting work on zsh functions * need a v1 of mapdiff as well (to handle null chars) * pack/unpack of ints was wrong (one used int and one use uint). turned out we only ever encoded '0' so it worked. that also means it is safe to change unpack to unpackUInt * reworking for binary encoding of aliases and functions (because of zsh allows any character, including nulls, in names and values) * fixes, working on functions, issue with line endings * zsh functions. lots of ugliness here around dealing with line dicipline and cooked stty. new runcommand function to grab output from a non-tty fd. note that we still to run the actual command in a stty to get the proper output. * write uuid tempdir, cleanup with tmprcfilename code * hack in some simple zsh function declaration finding code for rtnstate. create function diff for rtnstate that supports zsh * make sure key order is constant so shell hashes are consistent * fix problems with state diffs to support new zsh formats. add diff/apply code to shellapi (moved from shellenv), that is now specific to zsh or bash * add log packet and new shellstate packets * switch to shellstate map that's also keyed by shelltype * add shelltype to remoteinstance * remove shell argument from waveshell * added new shelltype statemap to remote.go (msh), deal with fallout * move shellstate out of init packet, and move to an explicit reinit call. try to initialize all of the active shell states * change dont always store init state (only store on demand). initialize shell states on demand (if not already initialized). allow reset to change shells * add shellpref field to remote table. use to drive the default shell choice for new tabs * show shelltag on cmdinput, pass through ri and remote (defaultshellstate) * bump mshell version to v0.4 * better version validation for shellstate. also relax compatibility requirements for diffing states (shelltype + major version need to match) * better error handling, check shellstate compatibility during run (on waveshell server) * add extra separator for bash shellstate processing to deal with spurious output from rc files * special migration for v30 -- flag invalid bash shell states and show special button in UI to fix * format * remove zsh-decls (unused) * remove test code * remove debug print * fix typo
2024-01-17 01:11:04 +01:00
quickSetStr(&r.ShellPref, m, "shellpref")
return true
2022-07-07 09:10:37 +02:00
}
func (cmd *CmdType) ToMap() map[string]interface{} {
rtn := make(map[string]interface{})
rtn["screenid"] = cmd.ScreenId
2023-07-31 02:16:43 +02:00
rtn["lineid"] = cmd.LineId
2022-08-24 22:21:54 +02:00
rtn["remoteownerid"] = cmd.Remote.OwnerId
rtn["remoteid"] = cmd.Remote.RemoteId
rtn["remotename"] = cmd.Remote.Name
2022-07-07 09:10:37 +02:00
rtn["cmdstr"] = cmd.CmdStr
2023-03-21 03:20:57 +01:00
rtn["rawcmdstr"] = cmd.RawCmdStr
rtn["festate"] = quickJson(cmd.FeState)
rtn["statebasehash"] = cmd.StatePtr.BaseHash
rtn["statediffhasharr"] = quickJsonArr(cmd.StatePtr.DiffHashArr)
2022-07-07 09:10:37 +02:00
rtn["termopts"] = quickJson(cmd.TermOpts)
2022-09-22 07:02:38 +02:00
rtn["origtermopts"] = quickJson(cmd.OrigTermOpts)
2022-07-07 09:10:37 +02:00
rtn["status"] = cmd.Status
2023-07-31 02:16:43 +02:00
rtn["cmdpid"] = cmd.CmdPid
rtn["remotepid"] = cmd.RemotePid
rtn["restartts"] = cmd.RestartTs
2023-07-31 02:16:43 +02:00
rtn["donets"] = cmd.DoneTs
rtn["exitcode"] = cmd.ExitCode
rtn["durationms"] = cmd.DurationMs
2022-07-07 09:10:37 +02:00
rtn["runout"] = quickJson(cmd.RunOut)
rtn["rtnstate"] = cmd.RtnState
rtn["rtnbasehash"] = cmd.RtnStatePtr.BaseHash
rtn["rtndiffhasharr"] = quickJsonArr(cmd.RtnStatePtr.DiffHashArr)
2022-07-07 09:10:37 +02:00
return rtn
}
func (cmd *CmdType) FromMap(m map[string]interface{}) bool {
quickSetStr(&cmd.ScreenId, m, "screenid")
2023-07-31 02:16:43 +02:00
quickSetStr(&cmd.LineId, m, "lineid")
2022-08-24 22:21:54 +02:00
quickSetStr(&cmd.Remote.OwnerId, m, "remoteownerid")
quickSetStr(&cmd.Remote.RemoteId, m, "remoteid")
quickSetStr(&cmd.Remote.Name, m, "remotename")
2022-07-07 09:10:37 +02:00
quickSetStr(&cmd.CmdStr, m, "cmdstr")
2023-03-21 03:20:57 +01:00
quickSetStr(&cmd.RawCmdStr, m, "rawcmdstr")
quickSetJson(&cmd.FeState, m, "festate")
quickSetStr(&cmd.StatePtr.BaseHash, m, "statebasehash")
quickSetJsonArr(&cmd.StatePtr.DiffHashArr, m, "statediffhasharr")
2022-07-07 09:10:37 +02:00
quickSetJson(&cmd.TermOpts, m, "termopts")
2022-09-22 07:02:38 +02:00
quickSetJson(&cmd.OrigTermOpts, m, "origtermopts")
2022-07-07 09:10:37 +02:00
quickSetStr(&cmd.Status, m, "status")
2023-07-31 02:16:43 +02:00
quickSetInt(&cmd.CmdPid, m, "cmdpid")
quickSetInt(&cmd.RemotePid, m, "remotepid")
quickSetInt64(&cmd.DoneTs, m, "donets")
quickSetInt64(&cmd.RestartTs, m, "restartts")
2023-07-31 02:16:43 +02:00
quickSetInt(&cmd.ExitCode, m, "exitcode")
quickSetInt(&cmd.DurationMs, m, "durationms")
2022-07-07 09:10:37 +02:00
quickSetJson(&cmd.RunOut, m, "runout")
quickSetBool(&cmd.RtnState, m, "rtnstate")
quickSetStr(&cmd.RtnStatePtr.BaseHash, m, "rtnbasehash")
quickSetJsonArr(&cmd.RtnStatePtr.DiffHashArr, m, "rtndiffhasharr")
return true
2022-06-13 20:11:56 +02:00
}
2023-07-31 02:16:43 +02:00
func (cmd *CmdType) IsRunning() bool {
return cmd.Status == CmdStatusRunning || cmd.Status == CmdStatusDetached
}
func makeNewLineCmd(screenId string, userId string, lineId string, renderer string, lineState map[string]any) *LineType {
2022-06-13 20:11:56 +02:00
rtn := &LineType{}
2023-03-15 00:37:22 +01:00
rtn.ScreenId = screenId
rtn.UserId = userId
2023-07-31 02:16:43 +02:00
rtn.LineId = lineId
2022-06-13 20:11:56 +02:00
rtn.Ts = time.Now().UnixMilli()
rtn.LineLocal = true
2022-06-13 20:11:56 +02:00
rtn.LineType = LineTypeCmd
2023-07-31 02:16:43 +02:00
rtn.LineId = lineId
rtn.ContentHeight = LineNoHeight
2023-02-06 09:30:23 +01:00
rtn.Renderer = renderer
if lineState == nil {
lineState = make(map[string]any)
}
rtn.LineState = lineState
2022-06-13 20:11:56 +02:00
return rtn
}
2023-03-21 03:20:57 +01:00
func makeNewLineText(screenId string, userId string, text string) *LineType {
2022-06-13 20:11:56 +02:00
rtn := &LineType{}
2023-03-15 00:37:22 +01:00
rtn.ScreenId = screenId
rtn.UserId = userId
rtn.LineId = scbase.GenWaveUUID()
2022-06-13 20:11:56 +02:00
rtn.Ts = time.Now().UnixMilli()
rtn.LineLocal = true
2022-06-13 20:11:56 +02:00
rtn.LineType = LineTypeText
rtn.Text = text
rtn.ContentHeight = LineNoHeight
2023-09-02 01:45:01 +02:00
rtn.LineState = make(map[string]any)
2022-06-13 20:11:56 +02:00
return rtn
}
2022-06-21 06:57:23 +02:00
2023-07-31 02:16:43 +02:00
func makeNewLineOpenAI(screenId string, userId string, lineId string) *LineType {
2023-05-04 10:01:13 +02:00
rtn := &LineType{}
rtn.ScreenId = screenId
rtn.UserId = userId
2023-07-31 02:16:43 +02:00
rtn.LineId = lineId
2023-05-04 10:01:13 +02:00
rtn.Ts = time.Now().UnixMilli()
rtn.LineLocal = true
rtn.LineType = LineTypeOpenAI
rtn.ContentHeight = LineNoHeight
rtn.Renderer = CmdRendererOpenAI
2023-09-02 01:45:01 +02:00
rtn.LineState = make(map[string]any)
2023-05-04 10:01:13 +02:00
return rtn
}
2023-03-21 03:20:57 +01:00
func AddCommentLine(ctx context.Context, screenId string, userId string, commentText string) (*LineType, error) {
rtnLine := makeNewLineText(screenId, userId, commentText)
err := InsertLine(ctx, rtnLine, nil)
2022-07-05 19:51:47 +02:00
if err != nil {
return nil, err
}
return rtnLine, nil
}
2023-05-04 10:01:13 +02:00
func AddOpenAILine(ctx context.Context, screenId string, userId string, cmd *CmdType) (*LineType, error) {
2023-07-31 02:16:43 +02:00
rtnLine := makeNewLineOpenAI(screenId, userId, cmd.LineId)
2023-05-04 10:01:13 +02:00
err := InsertLine(ctx, rtnLine, cmd)
if err != nil {
return nil, err
}
return rtnLine, nil
}
func AddCmdLine(ctx context.Context, screenId string, userId string, cmd *CmdType, renderer string, lineState map[string]any) (*LineType, error) {
rtnLine := makeNewLineCmd(screenId, userId, cmd.LineId, renderer, lineState)
err := InsertLine(ctx, rtnLine, cmd)
2022-07-05 19:51:47 +02:00
if err != nil {
return nil, err
}
return rtnLine, nil
}
2022-07-01 21:17:19 +02:00
func EnsureLocalRemote(ctx context.Context) error {
remote, err := GetLocalRemote(ctx)
2022-07-01 21:17:19 +02:00
if err != nil {
return fmt.Errorf("getting local remote from db: %w", err)
2022-07-01 21:17:19 +02:00
}
if remote != nil {
return nil
}
2022-08-17 00:08:28 +02:00
hostName, err := os.Hostname()
if err != nil {
return fmt.Errorf("getting hostname: %w", err)
}
user, err := user.Current()
if err != nil {
return fmt.Errorf("getting user: %w", err)
}
2022-07-01 21:17:19 +02:00
// create the local remote
localRemote := &RemoteType{
RemoteId: scbase.GenWaveUUID(),
RemoteType: RemoteTypeSsh,
RemoteAlias: LocalRemoteAlias,
2022-08-17 00:08:28 +02:00
RemoteCanonicalName: fmt.Sprintf("%s@%s", user.Username, hostName),
RemoteUser: user.Username,
RemoteHost: hostName,
ConnectMode: ConnectModeStartup,
2022-09-25 07:42:52 +02:00
AutoInstall: true,
2022-08-24 06:05:49 +02:00
SSHOpts: &SSHOpts{Local: true},
Local: true,
ssh config import (#156) * create migrations for required database change This is a first attempt that does not appear to be working properly. It requires review. * fix errors in db migrations The previous commit had an extra json call that broke the update and did not remove the imported interies during a downgrade. * change migrations to use column instead of json It makes more sense to associate the source of a config with the remote type than the sshopts type. This change makes that clear in the database structure. * ensure adding a remote manually tags correctly Using the usual way of adding a remote should result in a sshconfigsrc of "waveterm-manual". This will be important for filtering out remotes installed manually and remotes installed via import * create basic structure for parsing ssh config This entails creating a new command, making it possible to query only the imported remotes from the database, and implementing the logic to handle all of the updates needed. This needs improvements in a few areas: - the /etc/ssh/config needs to be parsed as well - the logic for editing exisiting imported remotes needs to be written - error handling needs to be improved - update packet responses need to be provided * add sshkey support and implement editing We now search for the ssh identity keyfile and add it if it is found. Additionally, the logic to edit previously imported ssh hosts has been added. * combine hosts from user and system ssh config We now check both the user ~/.ssh/config as well as the /etc/ssh/config for hosts. This loops through each file starting with the user one. For each host, it selects the first pattern without a wildcard and chooses that to be the alias. If any future hosts are found to have the same alias, they are skipped. Errors are raised if neither config file can be opened or no aliases were found. * improve logging and error reporting Error reporting is now shortcircuited in cases of individual remotes in order to allow the other remotes to continue. These errors are now printed to logs instead. * allow imports to edit ssh port Previously, ssh ports could not be edited after the fact. Unfortunately, this can cause problems since the port can be changed in an ssh config file. To address this, we allow imports to change the port if a host with the same canonical name had previously been imported. * fix response to parse command * fix error handline for alias parsing Small mistake of checking for equality instead of inequality * fix the ability to overwrite hostName with alias if ssh_config does not find Hostname, it won't output an error. Now we compare against the result instead of looking for an error. * fix the error catching for User and Port This fixes the same problem where parsing the config doesn't give an error in the case when nothing is found. As before, this checks for a blank result instead. * remove unused code * remove repeated canonical name check The logic that checks for an existing canonical name already exists in the AddRemote function, so it is not needed here. Secondly, we now only allow edits of previously created remotes if they have not been archived. If they have, the usual logic for creating a new remote takes precedence. Lastly, there is no need to archive a remote that has already been archived so an additional check has been added. * allow archives to preserve the SSHConfigSrc * add log message for archiving of imported remotes * create variables for string variants Matches existing code style * add cleanup for opened files * move migration 25 to migration 26 (already merged a migration 25) * fix RemoteRuntimeState in ModelUpdate by moving type to sstore.go. Fix some bugs in remote:parse. Fix key/identityfile, return value, and remote editing (should go through msh). remote sudo. add info messages around parse status * fix issue with archiving the sshconfigsrc A bug in RemoteType's FromMap caused the loss of sshconfigsrc during the conversion. This has been corrected and the schema has been updated. * fix order of archiving removed imported remotes Previously, if the canonical name changed, the code would try to create a new remote before archiving the old one. This did not work if the alias didn't change. Now we archive first and add a new remote after. * fix ability to change port when importing config Importing from sshconfig needs to allow the port to change. This was not happening because of a bug that has been corrected. * always use host in place of hostname Since host is the key actually searched for in the ssh config file, searching for user@hostName may not actually work. To avoid this, we now always use user@host instead. * automatically determine ConnectMode This aims to select a connection mode based off what is provided in the ssh config file. It aims for auto connections when possible but will fall back to manual if we can't easily support it * remove sshkeysource migration number confilict Previously had conflicting migration numbers of 26. The change not in the main branch has been moved to 27 to remove the conflict. * move sshkeysource migration to migration 28 * add WaveOptions flag parsing for ssh config This is currently being used to allow users to force manual connect mode if desired. It will also be used to force skipping options in the future but that is not complete in this commit. * implement ignore flag for ssh config parsing The ignore flag will now archive an imported remote if it previously existed and not create a new remote in its place. * fix discovery of identity file Previously, a ~ in the identity file's path was not expanded to the home dir. Because of this, files with a ~ were previously identified as invalid files. By expanding it during the search, this is no longer the case. * disable frontend edit button for imported remotes Imported Remotes should not be editable in waveterm by users. This edit makes it clear that the button will not work for those cases. Further edits may be needed to explain why it doesn't work and what to do instead. * add backend rejection of updating imported remote As before, we don't want manual editing of an imported remote inside the app. This ensures that it can't happen on the backend. * create tooltips for sshconfig edit/delete buttons For remotes that are imported, edits are not allowed. This adds a tooltip that explains what to do instead. Deleting remotes that are imported is allowed, but they will come back if the user imports again. The tooltip explains a way to avoid this. * add logo after name for imported remotes In the connections screen, there previously was not a way to tell imported connections from manually created connections. This change adds a logo after the imported ones to differentiate them. * small formatting updates * add import tooltip to connection modal Added the logo for an imported config to the connection modal. It also provides a short description when it the mouse hovers over it. * add button to import ssh config Make the command into a button for a simple gui interface. Also ran prettier to clean up some syntax. * remove strict casing on WaveOptions WaveOptions was previously very specific about the casing of the ignore and connectmode subcommands. With this update, the casing is automatically converted to lowercase and can be ignored. * add status dot before name in connections screen * add space and tooltip to connection imported icon * re-prettier
2023-12-28 20:09:41 +01:00
SSHConfigSrc: SSHConfigSrcTypeManual,
zsh support (#227) adds zsh support to waveterm. big change, lots going on here. lots of other improvements and bug fixes added while debugging and building out the feature. Commits: * refactor shexec parser.go into new package shellenv. separate out bash specific parsing from generic functions * checkpoint * work on refactoring shexec. created two new packages shellapi (for bash/zsh specific stuff), and shellutil (shared between shellapi and shexec) * more refactoring * create shellapi interface to abstract bash specific functionality * more refactoring, move bash shell state parsing to shellapi * move makeRcFile to shellapi. remove all of the 'client' options CLI options from waveshell * get shellType passed through to server/single paths for waveshell * add a local shelltype detector * mock out a zshapi * move shelltype through more of the code * get a command to run via zsh * zsh can now switch directories. poc, needs cleanup * working on ShellState encoding differences between zsh/bash. Working on parsing zsh decls. move utilfn package into waveshell (shouldn't have been in wavesrv) * switch to use []byte for vardecl serialization + diffs * progress on zsh environment. still have issues reconciling init environment with trap environment * fix typeset argument parsing * parse promptvars, more zsh specific ignores * fix bug with promptvar not getting set (wrong check in FeState func) * add sdk (issue #188) to list of rtnstate commands * more zsh compatibility -- working with a larger ohmyzsh environment. ignore more variables, handle exit trap better. unique path/fpath. add a processtype variable to base. * must return a value * zsh alias parsing/restoring. diff changes (and rtnstate changes). introduces linediff v1. * force zmodload of zsh/parameter * starting work on zsh functions * need a v1 of mapdiff as well (to handle null chars) * pack/unpack of ints was wrong (one used int and one use uint). turned out we only ever encoded '0' so it worked. that also means it is safe to change unpack to unpackUInt * reworking for binary encoding of aliases and functions (because of zsh allows any character, including nulls, in names and values) * fixes, working on functions, issue with line endings * zsh functions. lots of ugliness here around dealing with line dicipline and cooked stty. new runcommand function to grab output from a non-tty fd. note that we still to run the actual command in a stty to get the proper output. * write uuid tempdir, cleanup with tmprcfilename code * hack in some simple zsh function declaration finding code for rtnstate. create function diff for rtnstate that supports zsh * make sure key order is constant so shell hashes are consistent * fix problems with state diffs to support new zsh formats. add diff/apply code to shellapi (moved from shellenv), that is now specific to zsh or bash * add log packet and new shellstate packets * switch to shellstate map that's also keyed by shelltype * add shelltype to remoteinstance * remove shell argument from waveshell * added new shelltype statemap to remote.go (msh), deal with fallout * move shellstate out of init packet, and move to an explicit reinit call. try to initialize all of the active shell states * change dont always store init state (only store on demand). initialize shell states on demand (if not already initialized). allow reset to change shells * add shellpref field to remote table. use to drive the default shell choice for new tabs * show shelltag on cmdinput, pass through ri and remote (defaultshellstate) * bump mshell version to v0.4 * better version validation for shellstate. also relax compatibility requirements for diffing states (shelltype + major version need to match) * better error handling, check shellstate compatibility during run (on waveshell server) * add extra separator for bash shellstate processing to deal with spurious output from rc files * special migration for v30 -- flag invalid bash shell states and show special button in UI to fix * format * remove zsh-decls (unused) * remove test code * remove debug print * fix typo
2024-01-17 01:11:04 +01:00
ShellPref: ShellTypePref_Detect,
2022-07-01 21:17:19 +02:00
}
2022-09-14 02:11:36 +02:00
err = UpsertRemote(ctx, localRemote)
2022-07-01 21:17:19 +02:00
if err != nil {
return err
}
log.Printf("[db] added local remote '%s', id=%s\n", localRemote.RemoteCanonicalName, localRemote.RemoteId)
2022-12-29 09:07:16 +01:00
sudoRemote := &RemoteType{
RemoteId: scbase.GenWaveUUID(),
2022-12-29 09:07:16 +01:00
RemoteType: RemoteTypeSsh,
RemoteAlias: "sudo",
RemoteCanonicalName: fmt.Sprintf("sudo@%s@%s", user.Username, hostName),
RemoteUser: "root",
RemoteHost: hostName,
ConnectMode: ConnectModeManual,
AutoInstall: true,
SSHOpts: &SSHOpts{Local: true, IsSudo: true},
2022-12-29 09:07:16 +01:00
RemoteOpts: &RemoteOptsType{Color: "red"},
Local: true,
ssh config import (#156) * create migrations for required database change This is a first attempt that does not appear to be working properly. It requires review. * fix errors in db migrations The previous commit had an extra json call that broke the update and did not remove the imported interies during a downgrade. * change migrations to use column instead of json It makes more sense to associate the source of a config with the remote type than the sshopts type. This change makes that clear in the database structure. * ensure adding a remote manually tags correctly Using the usual way of adding a remote should result in a sshconfigsrc of "waveterm-manual". This will be important for filtering out remotes installed manually and remotes installed via import * create basic structure for parsing ssh config This entails creating a new command, making it possible to query only the imported remotes from the database, and implementing the logic to handle all of the updates needed. This needs improvements in a few areas: - the /etc/ssh/config needs to be parsed as well - the logic for editing exisiting imported remotes needs to be written - error handling needs to be improved - update packet responses need to be provided * add sshkey support and implement editing We now search for the ssh identity keyfile and add it if it is found. Additionally, the logic to edit previously imported ssh hosts has been added. * combine hosts from user and system ssh config We now check both the user ~/.ssh/config as well as the /etc/ssh/config for hosts. This loops through each file starting with the user one. For each host, it selects the first pattern without a wildcard and chooses that to be the alias. If any future hosts are found to have the same alias, they are skipped. Errors are raised if neither config file can be opened or no aliases were found. * improve logging and error reporting Error reporting is now shortcircuited in cases of individual remotes in order to allow the other remotes to continue. These errors are now printed to logs instead. * allow imports to edit ssh port Previously, ssh ports could not be edited after the fact. Unfortunately, this can cause problems since the port can be changed in an ssh config file. To address this, we allow imports to change the port if a host with the same canonical name had previously been imported. * fix response to parse command * fix error handline for alias parsing Small mistake of checking for equality instead of inequality * fix the ability to overwrite hostName with alias if ssh_config does not find Hostname, it won't output an error. Now we compare against the result instead of looking for an error. * fix the error catching for User and Port This fixes the same problem where parsing the config doesn't give an error in the case when nothing is found. As before, this checks for a blank result instead. * remove unused code * remove repeated canonical name check The logic that checks for an existing canonical name already exists in the AddRemote function, so it is not needed here. Secondly, we now only allow edits of previously created remotes if they have not been archived. If they have, the usual logic for creating a new remote takes precedence. Lastly, there is no need to archive a remote that has already been archived so an additional check has been added. * allow archives to preserve the SSHConfigSrc * add log message for archiving of imported remotes * create variables for string variants Matches existing code style * add cleanup for opened files * move migration 25 to migration 26 (already merged a migration 25) * fix RemoteRuntimeState in ModelUpdate by moving type to sstore.go. Fix some bugs in remote:parse. Fix key/identityfile, return value, and remote editing (should go through msh). remote sudo. add info messages around parse status * fix issue with archiving the sshconfigsrc A bug in RemoteType's FromMap caused the loss of sshconfigsrc during the conversion. This has been corrected and the schema has been updated. * fix order of archiving removed imported remotes Previously, if the canonical name changed, the code would try to create a new remote before archiving the old one. This did not work if the alias didn't change. Now we archive first and add a new remote after. * fix ability to change port when importing config Importing from sshconfig needs to allow the port to change. This was not happening because of a bug that has been corrected. * always use host in place of hostname Since host is the key actually searched for in the ssh config file, searching for user@hostName may not actually work. To avoid this, we now always use user@host instead. * automatically determine ConnectMode This aims to select a connection mode based off what is provided in the ssh config file. It aims for auto connections when possible but will fall back to manual if we can't easily support it * remove sshkeysource migration number confilict Previously had conflicting migration numbers of 26. The change not in the main branch has been moved to 27 to remove the conflict. * move sshkeysource migration to migration 28 * add WaveOptions flag parsing for ssh config This is currently being used to allow users to force manual connect mode if desired. It will also be used to force skipping options in the future but that is not complete in this commit. * implement ignore flag for ssh config parsing The ignore flag will now archive an imported remote if it previously existed and not create a new remote in its place. * fix discovery of identity file Previously, a ~ in the identity file's path was not expanded to the home dir. Because of this, files with a ~ were previously identified as invalid files. By expanding it during the search, this is no longer the case. * disable frontend edit button for imported remotes Imported Remotes should not be editable in waveterm by users. This edit makes it clear that the button will not work for those cases. Further edits may be needed to explain why it doesn't work and what to do instead. * add backend rejection of updating imported remote As before, we don't want manual editing of an imported remote inside the app. This ensures that it can't happen on the backend. * create tooltips for sshconfig edit/delete buttons For remotes that are imported, edits are not allowed. This adds a tooltip that explains what to do instead. Deleting remotes that are imported is allowed, but they will come back if the user imports again. The tooltip explains a way to avoid this. * add logo after name for imported remotes In the connections screen, there previously was not a way to tell imported connections from manually created connections. This change adds a logo after the imported ones to differentiate them. * small formatting updates * add import tooltip to connection modal Added the logo for an imported config to the connection modal. It also provides a short description when it the mouse hovers over it. * add button to import ssh config Make the command into a button for a simple gui interface. Also ran prettier to clean up some syntax. * remove strict casing on WaveOptions WaveOptions was previously very specific about the casing of the ignore and connectmode subcommands. With this update, the casing is automatically converted to lowercase and can be ignored. * add status dot before name in connections screen * add space and tooltip to connection imported icon * re-prettier
2023-12-28 20:09:41 +01:00
SSHConfigSrc: SSHConfigSrcTypeManual,
zsh support (#227) adds zsh support to waveterm. big change, lots going on here. lots of other improvements and bug fixes added while debugging and building out the feature. Commits: * refactor shexec parser.go into new package shellenv. separate out bash specific parsing from generic functions * checkpoint * work on refactoring shexec. created two new packages shellapi (for bash/zsh specific stuff), and shellutil (shared between shellapi and shexec) * more refactoring * create shellapi interface to abstract bash specific functionality * more refactoring, move bash shell state parsing to shellapi * move makeRcFile to shellapi. remove all of the 'client' options CLI options from waveshell * get shellType passed through to server/single paths for waveshell * add a local shelltype detector * mock out a zshapi * move shelltype through more of the code * get a command to run via zsh * zsh can now switch directories. poc, needs cleanup * working on ShellState encoding differences between zsh/bash. Working on parsing zsh decls. move utilfn package into waveshell (shouldn't have been in wavesrv) * switch to use []byte for vardecl serialization + diffs * progress on zsh environment. still have issues reconciling init environment with trap environment * fix typeset argument parsing * parse promptvars, more zsh specific ignores * fix bug with promptvar not getting set (wrong check in FeState func) * add sdk (issue #188) to list of rtnstate commands * more zsh compatibility -- working with a larger ohmyzsh environment. ignore more variables, handle exit trap better. unique path/fpath. add a processtype variable to base. * must return a value * zsh alias parsing/restoring. diff changes (and rtnstate changes). introduces linediff v1. * force zmodload of zsh/parameter * starting work on zsh functions * need a v1 of mapdiff as well (to handle null chars) * pack/unpack of ints was wrong (one used int and one use uint). turned out we only ever encoded '0' so it worked. that also means it is safe to change unpack to unpackUInt * reworking for binary encoding of aliases and functions (because of zsh allows any character, including nulls, in names and values) * fixes, working on functions, issue with line endings * zsh functions. lots of ugliness here around dealing with line dicipline and cooked stty. new runcommand function to grab output from a non-tty fd. note that we still to run the actual command in a stty to get the proper output. * write uuid tempdir, cleanup with tmprcfilename code * hack in some simple zsh function declaration finding code for rtnstate. create function diff for rtnstate that supports zsh * make sure key order is constant so shell hashes are consistent * fix problems with state diffs to support new zsh formats. add diff/apply code to shellapi (moved from shellenv), that is now specific to zsh or bash * add log packet and new shellstate packets * switch to shellstate map that's also keyed by shelltype * add shelltype to remoteinstance * remove shell argument from waveshell * added new shelltype statemap to remote.go (msh), deal with fallout * move shellstate out of init packet, and move to an explicit reinit call. try to initialize all of the active shell states * change dont always store init state (only store on demand). initialize shell states on demand (if not already initialized). allow reset to change shells * add shellpref field to remote table. use to drive the default shell choice for new tabs * show shelltag on cmdinput, pass through ri and remote (defaultshellstate) * bump mshell version to v0.4 * better version validation for shellstate. also relax compatibility requirements for diffing states (shelltype + major version need to match) * better error handling, check shellstate compatibility during run (on waveshell server) * add extra separator for bash shellstate processing to deal with spurious output from rc files * special migration for v30 -- flag invalid bash shell states and show special button in UI to fix * format * remove zsh-decls (unused) * remove test code * remove debug print * fix typo
2024-01-17 01:11:04 +01:00
ShellPref: ShellTypePref_Detect,
2022-12-29 09:07:16 +01:00
}
err = UpsertRemote(ctx, sudoRemote)
if err != nil {
return err
}
log.Printf("[db] added sudo remote '%s', id=%s\n", sudoRemote.RemoteCanonicalName, sudoRemote.RemoteId)
return nil
}
func EnsureOneSession(ctx context.Context) error {
numSessions, err := GetSessionCount(ctx)
2022-07-01 23:07:13 +02:00
if err != nil {
return err
2022-07-01 23:07:13 +02:00
}
if numSessions > 0 {
return nil
2022-07-01 23:07:13 +02:00
}
2023-07-26 19:10:27 +02:00
_, err = InsertSessionWithName(ctx, DefaultSessionName, true)
2022-07-01 23:07:13 +02:00
if err != nil {
return err
2022-07-01 23:07:13 +02:00
}
return nil
2022-07-01 21:17:19 +02:00
}
func createClientData(tx *TxWrap) error {
curve := elliptic.P384()
pkey, err := ecdsa.GenerateKey(curve, rand.Reader)
if err != nil {
return fmt.Errorf("generating P-834 key: %w", err)
}
pkBytes, err := x509.MarshalECPrivateKey(pkey)
if err != nil {
return fmt.Errorf("marshaling (pkcs8) private key bytes: %w", err)
}
pubBytes, err := x509.MarshalPKIXPublicKey(&pkey.PublicKey)
if err != nil {
return fmt.Errorf("marshaling (pkix) public key bytes: %w", err)
}
2022-09-22 07:02:38 +02:00
c := ClientData{
ClientId: uuid.New().String(),
UserId: uuid.New().String(),
UserPrivateKeyBytes: pkBytes,
UserPublicKeyBytes: pubBytes,
ActiveSessionId: "",
2022-09-25 09:26:33 +02:00
WinSize: ClientWinSizeType{},
2023-03-21 03:20:57 +01:00
CmdStoreType: CmdStoreTypeScreen,
ReleaseInfo: ReleaseInfoType{},
2022-09-22 07:02:38 +02:00
}
query := `INSERT INTO client ( clientid, userid, activesessionid, userpublickeybytes, userprivatekeybytes, winsize, cmdstoretype, releaseinfo)
VALUES (:clientid,:userid,:activesessionid,:userpublickeybytes,:userprivatekeybytes,:winsize,:cmdstoretype,:releaseinfo)`
tx.NamedExec(query, dbutil.ToDBMap(c, false))
2022-10-31 20:40:45 +01:00
log.Printf("create new clientid[%s] userid[%s] with public/private keypair\n", c.ClientId, c.UserId)
return nil
}
func EnsureClientData(ctx context.Context) (*ClientData, error) {
rtn, err := WithTxRtn(ctx, func(tx *TxWrap) (*ClientData, error) {
query := `SELECT count(*) FROM client`
count := tx.GetInt(query)
if count > 1 {
return nil, fmt.Errorf("invalid client database, multiple (%d) rows in client table", count)
}
if count == 0 {
createErr := createClientData(tx)
if createErr != nil {
return nil, createErr
}
}
cdata := dbutil.GetMappable[*ClientData](tx, `SELECT * FROM client`)
2022-09-22 07:02:38 +02:00
if cdata == nil {
return nil, fmt.Errorf("no client data found")
}
dbVersion := tx.GetInt(`SELECT version FROM schema_migrations`)
cdata.DBVersion = dbVersion
return cdata, nil
})
if err != nil {
return nil, err
}
if rtn.UserId == "" {
return nil, fmt.Errorf("invalid client data (no userid)")
}
if len(rtn.UserPrivateKeyBytes) == 0 || len(rtn.UserPublicKeyBytes) == 0 {
return nil, fmt.Errorf("invalid client data (no public/private keypair)")
}
rtn.UserPrivateKey, err = x509.ParseECPrivateKey(rtn.UserPrivateKeyBytes)
if err != nil {
return nil, fmt.Errorf("invalid client data, cannot parse private key: %w", err)
}
pubKey, err := x509.ParsePKIXPublicKey(rtn.UserPublicKeyBytes)
if err != nil {
return nil, fmt.Errorf("invalid client data, cannot parse public key: %w", err)
}
var ok bool
rtn.UserPublicKey, ok = pubKey.(*ecdsa.PublicKey)
if !ok {
return nil, fmt.Errorf("invalid client data, wrong public key type: %T", pubKey)
}
return rtn, nil
}
func SetClientOpts(ctx context.Context, clientOpts ClientOptsType) error {
txErr := WithTx(ctx, func(tx *TxWrap) error {
query := `UPDATE client SET clientopts = ?`
tx.Exec(query, quickJson(clientOpts))
return nil
})
return txErr
}
func SetReleaseInfo(ctx context.Context, releaseInfo ReleaseInfoType) error {
txErr := WithTx(ctx, func(tx *TxWrap) error {
query := `UPDATE client SET releaseinfo = ?`
tx.Exec(query, quickJson(releaseInfo))
return nil
})
return txErr
}
// Sets the in-memory status indicator for the given screenId to the given value and adds it to the ModelUpdate. By default, the active screen will be ignored when updating status. To force a status update for the active screen, set force=true.
func SetStatusIndicatorLevel_Update(ctx context.Context, update *scbus.ModelUpdatePacketType, screenId string, level StatusIndicatorLevel, force bool) error {
var newStatus StatusIndicatorLevel
if force {
// Force the update and set the new status to the given level, regardless of the current status or the active screen
ScreenMemSetIndicatorLevel(screenId, level)
newStatus = level
} else {
// Only update the status if the given screen is not the active screen and if the given level is higher than the current level
activeSessionId, err := GetActiveSessionId(ctx)
if err != nil {
return fmt.Errorf("error getting active session id: %w", err)
}
bareSession, err := GetBareSessionById(ctx, activeSessionId)
if err != nil {
return fmt.Errorf("error getting bare session: %w", err)
}
activeScreenId := bareSession.ActiveScreenId
if activeScreenId == screenId {
return nil
}
// If we are not forcing the update, follow the rules for combining status indicators
newLevel := ScreenMemCombineIndicatorLevels(screenId, level)
if newLevel == level {
newStatus = level
} else {
return nil
}
}
update.AddUpdate(ScreenStatusIndicatorType{
ScreenId: screenId,
Status: newStatus,
})
return nil
}
// Sets the in-memory status indicator for the given screenId to the given value and pushes the new value to the FE
func SetStatusIndicatorLevel(ctx context.Context, screenId string, level StatusIndicatorLevel, force bool) error {
update := scbus.MakeUpdatePacket()
err := SetStatusIndicatorLevel_Update(ctx, update, screenId, level, false)
if err != nil {
return err
}
scbus.MainUpdateBus.DoUpdate(update)
return nil
}
// Resets the in-memory status indicator for the given screenId to StatusIndicatorLevel_None and adds it to the ModelUpdate
func ResetStatusIndicator_Update(update *scbus.ModelUpdatePacketType, screenId string) error {
// We do not need to set context when resetting the status indicator because we will not need to call the DB
return SetStatusIndicatorLevel_Update(context.TODO(), update, screenId, StatusIndicatorLevel_None, true)
}
// Resets the in-memory status indicator for the given screenId to StatusIndicatorLevel_None and pushes the new value to the FE
func ResetStatusIndicator(screenId string) error {
// We do not need to set context when resetting the status indicator because we will not need to call the DB
return SetStatusIndicatorLevel(context.TODO(), screenId, StatusIndicatorLevel_None, true)
}
func IncrementNumRunningCmds_Update(update *scbus.ModelUpdatePacketType, screenId string, delta int) {
newNum := ScreenMemIncrementNumRunningCommands(screenId, delta)
update.AddUpdate(ScreenNumRunningCommandsType{
ScreenId: screenId,
Num: newNum,
})
}
func IncrementNumRunningCmds(screenId string, delta int) {
update := scbus.MakeUpdatePacket()
IncrementNumRunningCmds_Update(update, screenId, delta)
scbus.MainUpdateBus.DoUpdate(update)
}