Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ba8cd2d7a1 | ||
|
|
02fd716314 | ||
|
|
846879f62d | ||
|
|
d67a05a01d | ||
|
|
127b16cafa | ||
|
|
d6423b9d15 | ||
|
|
00e20a0147 | ||
|
|
e0454798b4 | ||
|
|
4adb352172 |
No files matched your search
@@ -1,5 +1,29 @@
|
||||
# Changelog
|
||||
|
||||
## [0.2.0] - 2026-08-18
|
||||
|
||||
- Copy passwords through a built-in pure-Go X11 clipboard on Linux, with no
|
||||
external clipboard tool required; other systems keep using wl-copy, xclip,
|
||||
xsel, pbcopy, or clip.exe.
|
||||
- Clear copied passwords automatically after a delay with `--clear-after`;
|
||||
by default they stay until another application takes the clipboard.
|
||||
- Read the master password from an OpenSSL-encrypted vault with `--vault`;
|
||||
the vault passphrase is asked for on the terminal or read from piped input,
|
||||
so the master password never appears in argv or the environment.
|
||||
- Save named profiles (a login plus default settings) in an optional
|
||||
configuration file and generate with `--profile`.
|
||||
- Print the current clipboard contents with `--read-clipboard`.
|
||||
- Install the binary as `pass` to use the compact `pass PROFILE SITE` form,
|
||||
which copies without printing.
|
||||
|
||||
## [0.1.3] - 2026-08-17
|
||||
|
||||
- Generate passwords directly on the website's home page: the full browser
|
||||
generator now runs in the front-page card, with no separate page to open.
|
||||
- The browser generator loads only when you start using it, keeping the
|
||||
front page fast for everyone else.
|
||||
- The standalone web app page remains available with the same generator.
|
||||
|
||||
## [0.1.2] - 2026-08-17
|
||||
|
||||
- Make keyboard navigation reliable: click a field, then use Tab and Shift+Tab
|
||||
|
||||
@@ -5,13 +5,14 @@ DATA_DIR ?= $(if $(XDG_DATA_HOME),$(XDG_DATA_HOME),$(HOME)/.local/share)
|
||||
|
||||
KRYON_ARCH ?= $(shell uname -m)
|
||||
KRYON_BUILD_DIR := vendor/kryon/build/linux-$(KRYON_ARCH)
|
||||
KRYON_RUNTIME_SOURCES := $(shell find vendor/kryon/src vendor/kryon/include -type f)
|
||||
|
||||
all: cli gui
|
||||
|
||||
cli:
|
||||
go build -o gopass ./cmd/gopass
|
||||
|
||||
$(KRYON_BUILD_DIR)/libkryon.a:
|
||||
$(KRYON_BUILD_DIR)/libkryon.a: $(KRYON_RUNTIME_SOURCES) vendor/kryon/Makefile
|
||||
$(MAKE) -C vendor/kryon -f Makefile all
|
||||
|
||||
gui: $(KRYON_BUILD_DIR)/libkryon.a
|
||||
|
||||
@@ -46,10 +46,67 @@ gopass --length 24 --counter 2 example.com alice
|
||||
gopass --no-symbols --exclude '0O1Il' example.com alice
|
||||
```
|
||||
|
||||
`--copy` sends the result through standard input to an available clipboard
|
||||
program (`wl-copy`, `xclip`, `xsel`, `pbcopy`, or `clip.exe`) and does not print
|
||||
the generated password. The command reports an error if no supported clipboard
|
||||
tool can be used.
|
||||
`--copy` sends the result to the clipboard without printing it. On Linux a
|
||||
built-in pure-Go X11 clipboard is used when an X server (X.Org, Xlibre, or
|
||||
XWayland) is reachable, so no external tool is needed; otherwise `gopass`
|
||||
falls back to `wl-copy`, `xclip`, `xsel`, `pbcopy`, or `clip.exe` and reports
|
||||
an error if none can be used. The copied password is served by a small
|
||||
detached process and disappears when another application takes the clipboard;
|
||||
`--clear-after 90s` releases it automatically after a delay (built-in X11
|
||||
clipboard only), and `--read-clipboard` prints the current contents.
|
||||
|
||||
## Profiles
|
||||
|
||||
An optional configuration file at `$XDG_CONFIG_HOME/gopass/profiles.json`
|
||||
(usually `~/.config/gopass/profiles.json`) can store named profiles — a login
|
||||
plus default settings — so daily invocations shrink to one flag:
|
||||
|
||||
```sh
|
||||
gopass --profile work example.com
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"vault": "~/.secret_vault",
|
||||
"copy": true,
|
||||
"clear_after": "90s",
|
||||
"profiles": {
|
||||
"work": {"login": "alice", "counter": 9, "length": 23, "symbols": false}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Profiles hold no secrets. Command-line flags always win over profile values,
|
||||
and without a configuration file gopass behaves exactly as before.
|
||||
|
||||
## Master password from a vault
|
||||
|
||||
`--vault PATH` reads the master password from a file encrypted with OpenSSL:
|
||||
|
||||
```sh
|
||||
printf 'master password' | openssl enc -aes-256-cbc -md sha512 -a \
|
||||
-pbkdf2 -iter 100000 -salt -pass pass:... > ~/.secret_vault
|
||||
gopass --vault ~/.secret_vault example.com alice
|
||||
```
|
||||
|
||||
The vault passphrase is requested on the terminal with echo disabled, or read
|
||||
from piped standard input, and the decrypted contents are used as the master
|
||||
password — the master itself never appears in argv or the environment. The
|
||||
vault path can also be set once in the profiles file.
|
||||
|
||||
## The `pass` shorthand
|
||||
|
||||
Copying or symlinking the binary as `pass` enables a compact personal mode
|
||||
built on profiles:
|
||||
|
||||
```sh
|
||||
ln -s gopass ~/bin/pass
|
||||
pass work example.com
|
||||
```
|
||||
|
||||
`pass PROFILE SITE` copies the password without printing it and clears the
|
||||
clipboard after 90 seconds (`-timeout 30s` to change, `-timeout 0` to keep it
|
||||
until another application takes over).
|
||||
|
||||
Run `gopass --help` for all flags.
|
||||
|
||||
|
||||
+11
-1
@@ -3,9 +3,11 @@ package main
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type clipboardCommand struct {
|
||||
@@ -13,7 +15,15 @@ type clipboardCommand struct {
|
||||
args []string
|
||||
}
|
||||
|
||||
func copyToClipboard(value string) error {
|
||||
func copyToClipboard(value string, clearAfter time.Duration) error {
|
||||
// The built-in pure-Go X11 clipboard doubles as the only backend that can
|
||||
// auto-clear: it owns the selection from a daemon and releases it on time.
|
||||
if handled, err := copyViaX11(value, clearAfter); handled {
|
||||
return err
|
||||
}
|
||||
if clearAfter > 0 {
|
||||
fmt.Fprintln(os.Stderr, "warning: --clear-after needs the built-in X11 clipboard; copying without auto-clear")
|
||||
}
|
||||
commands := clipboardCommands()
|
||||
var failures []error
|
||||
for _, candidate := range commands {
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
//go:build !linux
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
// The built-in X11 clipboard is Linux-only; other platforms always fall back
|
||||
// to external clipboard tools.
|
||||
|
||||
func copyViaX11(text string, clearAfter time.Duration) (bool, error) {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func runClipboardDaemon(timeout time.Duration) error {
|
||||
return errors.New("the built-in clipboard daemon is Linux-only")
|
||||
}
|
||||
|
||||
func readClipboardSelection() (string, error) {
|
||||
return "", errors.New("reading the clipboard is Linux-only")
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
//go:build linux
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/BurntSushi/xgb"
|
||||
"github.com/BurntSushi/xgb/xproto"
|
||||
)
|
||||
|
||||
// Pure-Go X11 clipboard. Xlibre is protocol-compatible with X.Org, so the
|
||||
// regular CLIPBOARD selection works there too. No xclip/xsel/wl-copy needed.
|
||||
|
||||
const (
|
||||
selClipboard = "CLIPBOARD"
|
||||
atomUTF8 = "UTF8_STRING"
|
||||
atomString = "STRING"
|
||||
atomText = "TEXT"
|
||||
atomTextPlain = "text/plain"
|
||||
atomPlainUTF8 = "text/plain;charset=utf-8"
|
||||
atomTargets = "TARGETS"
|
||||
atomMultiple = "MULTIPLE"
|
||||
propName = "GOPASS_SELECTION"
|
||||
)
|
||||
|
||||
type xAtoms map[string]xproto.Atom
|
||||
|
||||
func allAtomNames() []string {
|
||||
return []string{selClipboard, atomUTF8, atomString, atomText, atomTextPlain,
|
||||
atomPlainUTF8, atomTargets, atomMultiple, propName}
|
||||
}
|
||||
|
||||
func internAtoms(c *xgb.Conn, names ...string) (xAtoms, error) {
|
||||
m := make(xAtoms, len(names))
|
||||
for _, n := range names {
|
||||
rep, err := xproto.InternAtom(c, false, uint16(len(n)), n).Reply()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
m[n] = rep.Atom
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// serveClipboard takes ownership of the X11 CLIPBOARD selection and answers
|
||||
// paste requests until another client takes ownership or timeout elapses
|
||||
// (timeout <= 0 means "until replaced"). If ready is non-nil it is closed once
|
||||
// ownership has been confirmed.
|
||||
func serveClipboard(text string, timeout time.Duration, ready chan<- struct{}) error {
|
||||
c, err := xgb.NewConn()
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot connect to X server: %v", err)
|
||||
}
|
||||
defer c.Close()
|
||||
|
||||
atoms, err := internAtoms(c, allAtomNames()...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
screen := xproto.Setup(c).DefaultScreen(c)
|
||||
wid, err := c.NewId()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = xproto.CreateWindowChecked(c, 0, xproto.Window(wid), screen.Root,
|
||||
-1, -1, 1, 1, 0, 0, 0, 0, nil).Check()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
xproto.SetSelectionOwner(c, xproto.Window(wid), atoms[selClipboard], xproto.TimeCurrentTime)
|
||||
|
||||
rep, err := xproto.GetSelectionOwner(c, atoms[selClipboard]).Reply()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if rep.Owner != xproto.Window(wid) {
|
||||
return errors.New("failed to acquire CLIPBOARD ownership")
|
||||
}
|
||||
if ready != nil {
|
||||
close(ready)
|
||||
}
|
||||
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- selectionEventLoop(c, text, atoms) }()
|
||||
|
||||
sig := make(chan os.Signal, 1)
|
||||
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
|
||||
defer signal.Stop(sig)
|
||||
|
||||
if timeout > 0 {
|
||||
timer := time.NewTimer(timeout)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case err := <-done:
|
||||
return err
|
||||
case <-timer.C:
|
||||
return nil
|
||||
case <-sig:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
select {
|
||||
case err := <-done:
|
||||
return err
|
||||
case <-sig:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func selectionEventLoop(c *xgb.Conn, text string, atoms xAtoms) error {
|
||||
for {
|
||||
ev, err := c.WaitForEvent()
|
||||
if err != nil { // connection closed or protocol error
|
||||
return err
|
||||
}
|
||||
switch e := ev.(type) {
|
||||
case xproto.SelectionClearEvent:
|
||||
return nil // another client owns the clipboard now
|
||||
case xproto.DestroyNotifyEvent:
|
||||
return nil
|
||||
case xproto.SelectionRequestEvent:
|
||||
handleSelectionRequest(c, e, text, atoms)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func handleSelectionRequest(c *xgb.Conn, e xproto.SelectionRequestEvent, text string, atoms xAtoms) {
|
||||
prop := e.Property
|
||||
if prop == xproto.AtomNone {
|
||||
prop = e.Target
|
||||
}
|
||||
|
||||
ok := false
|
||||
switch e.Target {
|
||||
case atoms[atomTargets]:
|
||||
targets := []xproto.Atom{
|
||||
atoms[atomTargets], atoms[atomMultiple],
|
||||
atoms[atomUTF8], atoms[atomPlainUTF8],
|
||||
atoms[atomText], atoms[atomTextPlain], atoms[atomString],
|
||||
}
|
||||
buf := make([]byte, 4*len(targets))
|
||||
for i, t := range targets {
|
||||
binary.LittleEndian.PutUint32(buf[i*4:], uint32(t))
|
||||
}
|
||||
ok = changeProperty(c, e.Requestor, prop, xproto.AtomAtom, 32, buf)
|
||||
case atoms[atomUTF8], atoms[atomPlainUTF8], atoms[atomText], atoms[atomTextPlain], atoms[atomString]:
|
||||
// Generated passwords are plain ASCII, so serving the same bytes for
|
||||
// STRING (Latin-1) and TEXT targets is safe.
|
||||
ok = changeProperty(c, e.Requestor, prop, e.Target, 8, []byte(text))
|
||||
}
|
||||
if !ok {
|
||||
prop = xproto.AtomNone // refuse this target
|
||||
}
|
||||
|
||||
// Reply with a SelectionNotify event (event code 31).
|
||||
b := make([]byte, 32)
|
||||
b[0] = 31
|
||||
binary.LittleEndian.PutUint32(b[4:], uint32(e.Time))
|
||||
binary.LittleEndian.PutUint32(b[8:], uint32(e.Requestor))
|
||||
binary.LittleEndian.PutUint32(b[12:], uint32(e.Selection))
|
||||
binary.LittleEndian.PutUint32(b[16:], uint32(e.Target))
|
||||
binary.LittleEndian.PutUint32(b[20:], uint32(prop))
|
||||
xproto.SendEvent(c, false, e.Requestor, 0, string(b))
|
||||
}
|
||||
|
||||
func changeProperty(c *xgb.Conn, win xproto.Window, prop, typ xproto.Atom, format byte, data []byte) bool {
|
||||
units := uint32(len(data))
|
||||
if format == 32 {
|
||||
units /= 4
|
||||
}
|
||||
return xproto.ChangePropertyChecked(c, xproto.PropModeReplace, win, prop,
|
||||
typ, format, units, data).Check() == nil
|
||||
}
|
||||
|
||||
// copyViaX11 copies through the built-in clipboard server. It reports false
|
||||
// when no X server is reachable, so the caller can fall back to external
|
||||
// clipboard tools.
|
||||
func copyViaX11(text string, clearAfter time.Duration) (bool, error) {
|
||||
if os.Getenv("DISPLAY") == "" {
|
||||
return false, nil
|
||||
}
|
||||
probe, err := xgb.NewConn()
|
||||
if err != nil {
|
||||
return false, nil
|
||||
}
|
||||
probe.Close()
|
||||
return true, spawnClipboardDaemon(text, clearAfter)
|
||||
}
|
||||
|
||||
// spawnClipboardDaemon re-executes this binary detached (new session) so the
|
||||
// clipboard keeps working after the terminal is closed. The password travels
|
||||
// over a pipe; it is never in argv or the environment.
|
||||
func spawnClipboardDaemon(text string, timeout time.Duration) error {
|
||||
r, w, err := os.Pipe()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
cmd := exec.Command(selfPath(), "--serve-clipboard", "--clear-after="+timeout.String())
|
||||
cmd.ExtraFiles = []*os.File{r}
|
||||
cmd.Env = os.Environ() // keep DISPLAY for the child
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
|
||||
|
||||
if err := cmd.Start(); err != nil {
|
||||
r.Close()
|
||||
w.Close()
|
||||
return err
|
||||
}
|
||||
if _, err := io.WriteString(w, text); err != nil {
|
||||
return err
|
||||
}
|
||||
w.Close()
|
||||
r.Close()
|
||||
return nil
|
||||
}
|
||||
|
||||
// selfPath returns the absolute path of this running executable, so the
|
||||
// detached clipboard daemon can re-exec itself reliably.
|
||||
func selfPath() string {
|
||||
if p, err := os.Executable(); err == nil {
|
||||
return p
|
||||
}
|
||||
return os.Args[0]
|
||||
}
|
||||
|
||||
// runClipboardDaemon is the detached child process: it receives the password
|
||||
// over the pipe passed as fd 3 and serves the X11 clipboard until it is
|
||||
// replaced or the timeout elapses.
|
||||
func runClipboardDaemon(timeout time.Duration) error {
|
||||
f := os.NewFile(uintptr(3), "pipe")
|
||||
if f == nil {
|
||||
return errors.New("no pipe on fd 3")
|
||||
}
|
||||
data := make([]byte, 0, 64)
|
||||
buf := make([]byte, 64)
|
||||
for {
|
||||
n, err := f.Read(buf)
|
||||
data = append(data, buf[:n]...)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
f.Close()
|
||||
if len(data) == 0 {
|
||||
return errors.New("empty clipboard payload")
|
||||
}
|
||||
return serveClipboard(string(data), timeout, nil)
|
||||
}
|
||||
|
||||
// readClipboardSelection requests the current CLIPBOARD contents as
|
||||
// UTF8_STRING (equivalent of "xclip -o -selection clipboard").
|
||||
func readClipboardSelection() (string, error) {
|
||||
c, err := xgb.NewConn()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("cannot connect to X server: %v", err)
|
||||
}
|
||||
defer c.Close()
|
||||
|
||||
atoms, err := internAtoms(c, allAtomNames()...)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
screen := xproto.Setup(c).DefaultScreen(c)
|
||||
wid, err := c.NewId()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := xproto.CreateWindowChecked(c, 0, xproto.Window(wid), screen.Root,
|
||||
-1, -1, 1, 1, 0, 0, 0, 0, nil).Check(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
xproto.ConvertSelection(c, xproto.Window(wid), atoms[selClipboard],
|
||||
atoms[atomUTF8], atoms[propName], xproto.TimeCurrentTime)
|
||||
|
||||
// Wait for the SelectionNotify reply.
|
||||
var prop xproto.Atom
|
||||
found := false
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for !found {
|
||||
if time.Now().After(deadline) {
|
||||
return "", errors.New("timed out waiting for the clipboard owner")
|
||||
}
|
||||
ev, err := c.WaitForEvent()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if sn, ok := ev.(xproto.SelectionNotifyEvent); ok {
|
||||
if sn.Selection != atoms[selClipboard] {
|
||||
continue
|
||||
}
|
||||
if sn.Property == xproto.AtomNone {
|
||||
return "", errors.New("clipboard owner refused the request")
|
||||
}
|
||||
prop = sn.Property
|
||||
found = true
|
||||
}
|
||||
}
|
||||
|
||||
rep, err := xproto.GetProperty(c, false, xproto.Window(wid), prop,
|
||||
xproto.GetPropertyTypeAny, 0, 1<<20).Reply()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(rep.Value), nil
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
//go:build linux
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Live X11 round trip: take ownership of the CLIPBOARD selection, then read
|
||||
// it back as a separate X client.
|
||||
func TestClipboardRoundTrip(t *testing.T) {
|
||||
if os.Getenv("DISPLAY") == "" {
|
||||
t.Skip("no X11 display available")
|
||||
}
|
||||
|
||||
text := "TestPassword123"
|
||||
ready := make(chan struct{})
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- serveClipboard(text, 10*time.Second, ready) }()
|
||||
|
||||
select {
|
||||
case <-ready:
|
||||
case err := <-done:
|
||||
t.Fatalf("clipboard server exited early: %v", err)
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("timed out waiting for clipboard ownership")
|
||||
}
|
||||
|
||||
// Reading immediately can race with clipboard managers stealing the
|
||||
// selection; poll briefly for the expected content.
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for {
|
||||
got, err := readClipboardSelection()
|
||||
if err == nil && got == text {
|
||||
return // success
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("clipboard round trip failed: last read = %q, err = %v", got, err)
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
+161
-9
@@ -1,26 +1,59 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
password "github.com/waozixyz/gopass"
|
||||
"github.com/waozixyz/gopass/vault"
|
||||
)
|
||||
|
||||
const environmentVariable = "LESSPASS_MASTER_PASSWORD"
|
||||
|
||||
// promptVaultPassphrase asks for the vault passphrase on the terminal, or
|
||||
// reads it from standard input when stdin is piped ("echo pw | gopass ...").
|
||||
func promptVaultPassphrase() (string, error) {
|
||||
if info, err := os.Stdin.Stat(); err == nil && info.Mode()&os.ModeCharDevice == 0 {
|
||||
line, err := bufio.NewReader(os.Stdin).ReadString('\n')
|
||||
if err != nil && line == "" {
|
||||
return "", err
|
||||
}
|
||||
return strings.TrimRight(line, "\r\n"), nil
|
||||
}
|
||||
return readPassword("Vault passphrase: ")
|
||||
}
|
||||
|
||||
// readVaultPassphrase is the hook tests replace to decrypt a synthetic vault.
|
||||
var readVaultPassphrase = promptVaultPassphrase
|
||||
|
||||
func main() {
|
||||
if err := run(os.Args[1:], os.Stdout, os.Stderr); err != nil {
|
||||
arguments := os.Args[1:]
|
||||
if filepath.Base(os.Args[0]) == "pass" {
|
||||
translated, ok := translatePassArguments(arguments)
|
||||
if !ok {
|
||||
os.Exit(2)
|
||||
}
|
||||
arguments = translated
|
||||
}
|
||||
if err := run(arguments, os.Stdout, os.Stderr); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "gopass: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func run(arguments []string, stdout, stderr io.Writer) error {
|
||||
config, err := loadConfig()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
options := password.DefaultOptions()
|
||||
flags := flag.NewFlagSet("gopass", flag.ContinueOnError)
|
||||
flags.SetOutput(stderr)
|
||||
@@ -45,20 +78,32 @@ func run(arguments []string, stdout, stderr io.Writer) error {
|
||||
flags.BoolVar(&noSymbols, "no-symbols", false, "exclude symbols")
|
||||
flags.StringVar(&options.Exclude, "exclude", "", "characters to exclude")
|
||||
|
||||
var forcePrompt, copyPassword, showVersion bool
|
||||
var forcePrompt, copyPassword, noCopy, showVersion, readClipboard, serveClipboard bool
|
||||
flags.BoolVar(&forcePrompt, "p", false, "prompt for the master password")
|
||||
flags.BoolVar(&forcePrompt, "prompt", false, "prompt for the master password")
|
||||
flags.BoolVar(©Password, "c", false, "copy the password to the clipboard")
|
||||
flags.BoolVar(©Password, "copy", false, "copy the password to the clipboard")
|
||||
flags.BoolVar(&noCopy, "no-copy", false, "print instead of copying when the profile says to copy")
|
||||
flags.BoolVar(&showVersion, "v", false, "show version")
|
||||
flags.BoolVar(&showVersion, "version", false, "show version")
|
||||
|
||||
var profileName, vaultFlag string
|
||||
var clearAfter time.Duration
|
||||
flags.StringVar(&profileName, "P", "", "use a named profile from the configuration file")
|
||||
flags.StringVar(&profileName, "profile", "", "use a named profile from the configuration file")
|
||||
flags.StringVar(&vaultFlag, "vault", "", "read the master password from an OpenSSL-encrypted vault")
|
||||
flags.DurationVar(&clearAfter, "clear-after", 0, "clear the clipboard after this long; 0 keeps it until replaced (built-in X11 clipboard only)")
|
||||
flags.BoolVar(&readClipboard, "read-clipboard", false, "print the current clipboard contents")
|
||||
flags.BoolVar(&serveClipboard, "serve-clipboard", false, "") // internal: detached clipboard daemon mode
|
||||
|
||||
if err := flags.Parse(normalizeArguments(arguments)); err != nil {
|
||||
if errors.Is(err, flag.ErrHelp) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
explicit := map[string]bool{}
|
||||
flags.Visit(func(f *flag.Flag) { explicit[f.Name] = true })
|
||||
if noLowercase {
|
||||
options.Lowercase = false
|
||||
}
|
||||
@@ -75,9 +120,41 @@ func run(arguments []string, stdout, stderr io.Writer) error {
|
||||
fmt.Fprintf(stdout, "gopass %s\n", password.Version)
|
||||
return nil
|
||||
}
|
||||
if serveClipboard {
|
||||
return runClipboardDaemon(clearAfter)
|
||||
}
|
||||
if readClipboard {
|
||||
text, err := readClipboardSelection()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Fprintln(stdout, text)
|
||||
return nil
|
||||
}
|
||||
|
||||
var profile Profile
|
||||
if profileName != "" {
|
||||
if config == nil {
|
||||
return fmt.Errorf("unknown profile %q: no configuration file at %s", profileName, configPath())
|
||||
}
|
||||
found, ok := config.Profiles[profileName]
|
||||
if !ok {
|
||||
return fmt.Errorf("unknown profile %q", profileName)
|
||||
}
|
||||
if found.Login == "" {
|
||||
return fmt.Errorf("profile %q has no login", profileName)
|
||||
}
|
||||
profile = found
|
||||
profile.apply(&options, explicit)
|
||||
}
|
||||
|
||||
positional := flags.Args()
|
||||
if len(positional) < 2 || len(positional) > 3 {
|
||||
if profileName != "" {
|
||||
if len(positional) != 1 {
|
||||
printHelp(stderr)
|
||||
return errors.New("expected SITE with --profile")
|
||||
}
|
||||
} else if len(positional) < 2 || len(positional) > 3 {
|
||||
printHelp(stderr)
|
||||
return errors.New("expected SITE LOGIN and an optional MASTER_PASSWORD")
|
||||
}
|
||||
@@ -85,19 +162,70 @@ func run(arguments []string, stdout, stderr io.Writer) error {
|
||||
return errors.New("MASTER_PASSWORD cannot be supplied together with --prompt")
|
||||
}
|
||||
|
||||
master, err := masterPassword(positional, forcePrompt)
|
||||
site, login := positional[0], ""
|
||||
if profileName != "" {
|
||||
login = profile.Login
|
||||
} else {
|
||||
login = positional[1]
|
||||
}
|
||||
|
||||
// A vault from the configuration is the least authoritative master
|
||||
// password source: anything the user spells out for this invocation
|
||||
// (--vault, the environment, --prompt, a positional password) wins.
|
||||
vaultPath := vaultFlag
|
||||
if vaultPath == "" {
|
||||
_, envSet := os.LookupEnv(environmentVariable)
|
||||
if !envSet && !forcePrompt && len(positional) < 3 {
|
||||
switch {
|
||||
case profile.Vault != "":
|
||||
vaultPath = expandHome(profile.Vault)
|
||||
case config != nil && config.Vault != "":
|
||||
vaultPath = expandHome(config.Vault)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !noCopy && !anySet(explicit, "c", "copy") {
|
||||
switch {
|
||||
case profile.Copy != nil:
|
||||
copyPassword = *profile.Copy
|
||||
case config != nil && config.Copy != nil:
|
||||
copyPassword = *config.Copy
|
||||
}
|
||||
}
|
||||
if noCopy {
|
||||
copyPassword = false
|
||||
}
|
||||
if !anySet(explicit, "clear-after") {
|
||||
setting := profile.ClearAfter
|
||||
if setting == "" && config != nil {
|
||||
setting = config.ClearAfter
|
||||
}
|
||||
if setting != "" {
|
||||
duration, err := time.ParseDuration(setting)
|
||||
if err != nil {
|
||||
return fmt.Errorf("clear_after: %w", err)
|
||||
}
|
||||
clearAfter = duration
|
||||
}
|
||||
}
|
||||
|
||||
master, err := masterPassword(positional, forcePrompt, vaultPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
generated, err := password.Generate(positional[0], positional[1], master, options)
|
||||
generated, err := password.Generate(site, login, master, options)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if copyPassword {
|
||||
if err := copyToClipboard(generated); err != nil {
|
||||
if err := copyToClipboard(generated, clearAfter); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Fprintln(stderr, "Password copied to the clipboard.")
|
||||
if clearAfter > 0 {
|
||||
fmt.Fprintf(stderr, "Password copied to the clipboard (auto-clears in %s).\n", clearAfter)
|
||||
} else {
|
||||
fmt.Fprintln(stderr, "Password copied to the clipboard.")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
fmt.Fprintln(stdout, generated)
|
||||
@@ -112,6 +240,8 @@ func normalizeArguments(arguments []string) []string {
|
||||
"-L": true, "--length": true,
|
||||
"-C": true, "--counter": true,
|
||||
"--exclude": true,
|
||||
"-P": true, "--profile": true,
|
||||
"--vault": true, "--clear-after": true,
|
||||
}
|
||||
options := make([]string, 0, len(arguments))
|
||||
positional := make([]string, 0, 3)
|
||||
@@ -135,7 +265,20 @@ func normalizeArguments(arguments []string) []string {
|
||||
return append(options, positional...)
|
||||
}
|
||||
|
||||
func masterPassword(positional []string, forcePrompt bool) (string, error) {
|
||||
func masterPassword(positional []string, forcePrompt bool, vaultPath string) (string, error) {
|
||||
if vaultPath != "" {
|
||||
if forcePrompt {
|
||||
return "", errors.New("--vault cannot be combined with --prompt")
|
||||
}
|
||||
if len(positional) == 3 {
|
||||
return "", errors.New("--vault cannot be combined with MASTER_PASSWORD")
|
||||
}
|
||||
passphrase, err := readVaultPassphrase()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return vault.Decrypt(vaultPath, passphrase)
|
||||
}
|
||||
if !forcePrompt && len(positional) == 3 {
|
||||
return positional[2], nil
|
||||
}
|
||||
@@ -151,7 +294,11 @@ func printHelp(output io.Writer) {
|
||||
fmt.Fprintln(output, `Usage: gopass [OPTIONS] SITE LOGIN [MASTER_PASSWORD]
|
||||
|
||||
Derive a site-specific password. If MASTER_PASSWORD is omitted, gopass reads
|
||||
LESSPASS_MASTER_PASSWORD or asks for it on the controlling terminal.
|
||||
LESSPASS_MASTER_PASSWORD or asks for it on the controlling terminal. With
|
||||
--vault it instead decrypts an OpenSSL-encrypted vault and uses its contents
|
||||
as the master password. With --profile, a named profile from the
|
||||
configuration file supplies the login and default settings and only SITE is
|
||||
passed on the command line.
|
||||
|
||||
Options:
|
||||
-L, --length N password length (default 16)
|
||||
@@ -167,6 +314,11 @@ Options:
|
||||
--exclude CHARS remove characters from all enabled classes
|
||||
-p, --prompt always ask for the master password
|
||||
-c, --copy copy result without printing it
|
||||
--no-copy print instead of copying when the profile says to copy
|
||||
-P, --profile NAME use a named profile from the configuration file
|
||||
--vault PATH read the master password from an OpenSSL-encrypted vault
|
||||
--clear-after DUR clear the clipboard after DUR; 0 keeps it until replaced
|
||||
--read-clipboard print the current clipboard contents
|
||||
-v, --version show version
|
||||
-h, --help show this help`)
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
const passUsage = `pass - generate a LessPass password and copy it to the clipboard
|
||||
|
||||
Usage:
|
||||
pass [flags] <profile> <site>
|
||||
|
||||
The profile name selects a login and settings from the gopass profiles file.
|
||||
You will be prompted (hidden input) for the passphrase of your OpenSSL
|
||||
secret vault when one is configured. The password is copied to the
|
||||
CLIPBOARD selection; it is never displayed.
|
||||
|
||||
Flags:
|
||||
`
|
||||
|
||||
// translatePassArguments rewrites the legacy two-argument `pass PROFILE SITE`
|
||||
// command line into the equivalent gopass arguments, so a copy or symlink of
|
||||
// the gopass binary named "pass" keeps working as the personal shorthand.
|
||||
// It reports false (after printing usage) on a malformed legacy invocation.
|
||||
func translatePassArguments(arguments []string) ([]string, bool) {
|
||||
flags := flag.NewFlagSet("pass", flag.ContinueOnError)
|
||||
flags.SetOutput(io.Discard) // report errors through reportPassUsage instead
|
||||
|
||||
vaultPath := flags.String("vault", "", "path to an OpenSSL-encrypted vault holding the master password")
|
||||
counter := flags.Int64("counter", -1, "LessPass counter")
|
||||
length := flags.Int("length", 0, "password length")
|
||||
symbols := flags.Bool("symbols", false, "include symbols in the generated password")
|
||||
timeout := flags.Duration("timeout", 90*time.Second, "clipboard auto-clear timeout; 0 keeps it until overwritten")
|
||||
read := flags.Bool("read", false, "print the current clipboard contents")
|
||||
|
||||
if err := flags.Parse(arguments); err != nil {
|
||||
if errors.Is(err, flag.ErrHelp) {
|
||||
reportPassUsage(os.Stdout, flags)
|
||||
os.Exit(0)
|
||||
}
|
||||
reportPassUsage(os.Stderr, flags)
|
||||
fmt.Fprintf(os.Stderr, "\nerror: %v\n", err)
|
||||
return nil, false
|
||||
}
|
||||
|
||||
translated := []string{"--copy", "--clear-after=" + timeout.String()}
|
||||
if *vaultPath != "" {
|
||||
translated = append(translated, "--vault", *vaultPath)
|
||||
}
|
||||
if *counter >= 0 {
|
||||
translated = append(translated, "-C", strconv.FormatInt(*counter, 10))
|
||||
}
|
||||
if *length > 0 {
|
||||
translated = append(translated, "-L", strconv.Itoa(*length))
|
||||
}
|
||||
if *symbols {
|
||||
translated = append(translated, "-s")
|
||||
}
|
||||
if *read {
|
||||
return append(translated, "--read-clipboard"), true
|
||||
}
|
||||
|
||||
rest := flags.Args()
|
||||
if len(rest) != 2 {
|
||||
reportPassUsage(os.Stderr, flags)
|
||||
return nil, false
|
||||
}
|
||||
return append(translated, "--profile", rest[0], rest[1]), true
|
||||
}
|
||||
|
||||
// reportPassUsage prints the legacy usage block, the way the original pass
|
||||
// tool reported a bad command line.
|
||||
func reportPassUsage(output io.Writer, flags *flag.FlagSet) {
|
||||
fmt.Fprint(output, passUsage)
|
||||
flags.SetOutput(output)
|
||||
flags.PrintDefaults()
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestTranslatePassArguments(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
in []string
|
||||
want []string
|
||||
}{
|
||||
{
|
||||
name: "plain",
|
||||
in: []string{"w", "example.org"},
|
||||
want: []string{"--copy", "--clear-after=1m30s", "--profile", "w", "example.org"},
|
||||
},
|
||||
{
|
||||
name: "all flags",
|
||||
in: []string{"-vault", "/v", "-counter", "5", "-length", "20", "-symbols", "n", "s.org"},
|
||||
want: []string{"--copy", "--clear-after=1m30s", "--vault", "/v", "-C", "5", "-L", "20", "-s", "--profile", "n", "s.org"},
|
||||
},
|
||||
{
|
||||
name: "zero timeout keeps the clipboard",
|
||||
in: []string{"-timeout", "0", "w", "example.org"},
|
||||
want: []string{"--copy", "--clear-after=0s", "--profile", "w", "example.org"},
|
||||
},
|
||||
{
|
||||
name: "read mode",
|
||||
in: []string{"-read"},
|
||||
want: []string{"--copy", "--clear-after=1m30s", "--read-clipboard"},
|
||||
},
|
||||
}
|
||||
for _, test := range tests {
|
||||
got, ok := translatePassArguments(test.in)
|
||||
if !ok {
|
||||
t.Errorf("%s: translatePassArguments(%v) rejected the arguments", test.name, test.in)
|
||||
continue
|
||||
}
|
||||
if !reflect.DeepEqual(got, test.want) {
|
||||
t.Errorf("%s: got %v, want %v", test.name, got, test.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTranslatePassArgumentsRejectsBadUsage(t *testing.T) {
|
||||
for _, arguments := range [][]string{
|
||||
{},
|
||||
{"w"},
|
||||
{"w", "example.org", "extra"},
|
||||
{"-length", "notanumber", "w", "example.org"},
|
||||
} {
|
||||
if got, ok := translatePassArguments(arguments); ok {
|
||||
t.Errorf("translatePassArguments(%v) = %v, want rejection", arguments, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
password "github.com/waozixyz/gopass"
|
||||
)
|
||||
|
||||
// Profile holds the saved settings for one named identity: a login plus the
|
||||
// generator options and clipboard behavior to use with it. Profiles contain
|
||||
// no secrets — the master password always comes from a prompt, the
|
||||
// environment, or an encrypted vault referenced by path.
|
||||
type Profile struct {
|
||||
Login string `json:"login"`
|
||||
Counter uint64 `json:"counter,omitempty"`
|
||||
Length int `json:"length,omitempty"`
|
||||
Lowercase *bool `json:"lowercase,omitempty"`
|
||||
Uppercase *bool `json:"uppercase,omitempty"`
|
||||
Digits *bool `json:"digits,omitempty"`
|
||||
Symbols *bool `json:"symbols,omitempty"`
|
||||
Exclude string `json:"exclude,omitempty"`
|
||||
Vault string `json:"vault,omitempty"`
|
||||
Copy *bool `json:"copy,omitempty"`
|
||||
ClearAfter string `json:"clear_after,omitempty"`
|
||||
}
|
||||
|
||||
// Config is the optional profiles file. Every field is a default that flags
|
||||
// and profile entries override; a missing file leaves gopass fully stateless.
|
||||
type Config struct {
|
||||
Vault string `json:"vault,omitempty"`
|
||||
Copy *bool `json:"copy,omitempty"`
|
||||
ClearAfter string `json:"clear_after,omitempty"`
|
||||
Profiles map[string]Profile `json:"profiles"`
|
||||
}
|
||||
|
||||
// configPath is a variable so tests can point it at a temporary file.
|
||||
var configPath = defaultConfigPath
|
||||
|
||||
func defaultConfigPath() string {
|
||||
if dir := os.Getenv("XDG_CONFIG_HOME"); dir != "" {
|
||||
return filepath.Join(dir, "gopass", "profiles.json")
|
||||
}
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return filepath.Join(home, ".config", "gopass", "profiles.json")
|
||||
}
|
||||
|
||||
// loadConfig reads the profiles file. A missing file is not an error: the
|
||||
// feature is simply off and gopass behaves as a plain stateless generator.
|
||||
func loadConfig() (*Config, error) {
|
||||
path := configPath()
|
||||
if path == "" {
|
||||
return nil, nil
|
||||
}
|
||||
raw, err := os.ReadFile(path)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var config Config
|
||||
if err := json.Unmarshal(raw, &config); err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", path, err)
|
||||
}
|
||||
return &config, nil
|
||||
}
|
||||
|
||||
// apply fills the option fields that were not set explicitly on the command
|
||||
// line, so the precedence is always flag > profile > built-in default.
|
||||
func (p Profile) apply(options *password.Options, explicit map[string]bool) {
|
||||
if p.Length > 0 && !anySet(explicit, "L", "length") {
|
||||
options.Length = p.Length
|
||||
}
|
||||
if p.Counter > 0 && !anySet(explicit, "C", "counter") {
|
||||
options.Counter = p.Counter
|
||||
}
|
||||
if p.Lowercase != nil && !anySet(explicit, "l", "lowercase", "no-lowercase") {
|
||||
options.Lowercase = *p.Lowercase
|
||||
}
|
||||
if p.Uppercase != nil && !anySet(explicit, "u", "uppercase", "no-uppercase") {
|
||||
options.Uppercase = *p.Uppercase
|
||||
}
|
||||
if p.Digits != nil && !anySet(explicit, "d", "digits", "no-digits") {
|
||||
options.Digits = *p.Digits
|
||||
}
|
||||
if p.Symbols != nil && !anySet(explicit, "s", "symbols", "no-symbols") {
|
||||
options.Symbols = *p.Symbols
|
||||
}
|
||||
if p.Exclude != "" && !anySet(explicit, "exclude") {
|
||||
options.Exclude = p.Exclude
|
||||
}
|
||||
}
|
||||
|
||||
func anySet(explicit map[string]bool, names ...string) bool {
|
||||
for _, name := range names {
|
||||
if explicit[name] {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// expandHome resolves a leading ~ so config entries stay portable.
|
||||
func expandHome(path string) string {
|
||||
if path == "~" || strings.HasPrefix(path, "~/") {
|
||||
if home, err := os.UserHomeDir(); err == nil {
|
||||
return filepath.Join(home, strings.TrimPrefix(path, "~"))
|
||||
}
|
||||
}
|
||||
return path
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
password "github.com/waozixyz/gopass"
|
||||
)
|
||||
|
||||
// withConfig points the config loader at a temporary file for one test.
|
||||
func withConfig(t *testing.T, content string) {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "profiles.json")
|
||||
if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
original := configPath
|
||||
configPath = func() string { return path }
|
||||
t.Cleanup(func() { configPath = original })
|
||||
}
|
||||
|
||||
func withVaultPassphrase(t *testing.T, passphrase string) {
|
||||
t.Helper()
|
||||
original := readVaultPassphrase
|
||||
readVaultPassphrase = func() (string, error) { return passphrase, nil }
|
||||
t.Cleanup(func() { readVaultPassphrase = original })
|
||||
}
|
||||
|
||||
func TestRunWithProfileSettings(t *testing.T) {
|
||||
withConfig(t, `{
|
||||
"vault": "/nonexistent/vault",
|
||||
"copy": true,
|
||||
"clear_after": "90s",
|
||||
"profiles": {
|
||||
"w": {"login": "alice", "counter": 9, "length": 23, "symbols": false}
|
||||
}
|
||||
}`)
|
||||
t.Setenv(environmentVariable, "correct horse battery staple")
|
||||
var output, diagnostics bytes.Buffer
|
||||
err := run([]string{"-P", "w", "--no-copy", "example.com"}, &output, &diagnostics)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want, err := password.Generate("example.com", "alice", "correct horse battery staple", password.Options{
|
||||
Length: 23, Counter: 9, Lowercase: true, Uppercase: true, Digits: true, Symbols: false,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := strings.TrimSpace(output.String()); got != want {
|
||||
t.Fatalf("output = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProfileSettingsDoNotOverrideExplicitFlags(t *testing.T) {
|
||||
withConfig(t, `{"profiles": {"w": {"login": "alice", "length": 23, "symbols": false}}}`)
|
||||
t.Setenv(environmentVariable, "correct horse battery staple")
|
||||
var output, diagnostics bytes.Buffer
|
||||
err := run([]string{"-P", "w", "-L", "10", "example.com"}, &output, &diagnostics)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := strings.TrimSpace(output.String()); len(got) != 10 {
|
||||
t.Fatalf("output length = %d, want 10 (flag must beat profile)", len(got))
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunRejectsBadProfileNames(t *testing.T) {
|
||||
withConfig(t, `{"profiles": {"w": {"login": "alice"}, "n": {}}}`)
|
||||
t.Setenv(environmentVariable, "x")
|
||||
|
||||
var output, diagnostics bytes.Buffer
|
||||
if err := run([]string{"-P", "x", "example.com"}, &output, &diagnostics); err == nil ||
|
||||
!strings.Contains(err.Error(), "unknown profile") {
|
||||
t.Fatalf("error = %v, want unknown profile", err)
|
||||
}
|
||||
if err := run([]string{"-P", "n", "example.com"}, &output, &diagnostics); err == nil ||
|
||||
!strings.Contains(err.Error(), "has no login") {
|
||||
t.Fatalf("error = %v, want missing login", err)
|
||||
}
|
||||
// A profile without a configuration file at all.
|
||||
original := configPath
|
||||
configPath = func() string { return filepath.Join(t.TempDir(), "absent.json") }
|
||||
defer func() { configPath = original }()
|
||||
if err := run([]string{"-P", "w", "example.com"}, &output, &diagnostics); err == nil ||
|
||||
!strings.Contains(err.Error(), "no configuration file") {
|
||||
t.Fatalf("error = %v, want missing configuration", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunRejectsInvalidConfig(t *testing.T) {
|
||||
withConfig(t, `{"profiles":`)
|
||||
var output, diagnostics bytes.Buffer
|
||||
if err := run([]string{"example.com", "alice", "master"}, &output, &diagnostics); err == nil {
|
||||
t.Fatal("expected error for malformed configuration")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunRejectsInvalidClearAfter(t *testing.T) {
|
||||
withConfig(t, `{"clear_after": "not-a-duration", "profiles": {"w": {"login": "alice"}}}`)
|
||||
t.Setenv(environmentVariable, "x")
|
||||
var output, diagnostics bytes.Buffer
|
||||
err := run([]string{"-P", "w", "--no-copy", "example.com"}, &output, &diagnostics)
|
||||
if err == nil || !strings.Contains(err.Error(), "clear_after") {
|
||||
t.Fatalf("error = %v, want clear_after parse failure", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVaultMasterPasswordBeatsEnvironmentAndPositional(t *testing.T) {
|
||||
if _, err := exec.LookPath("openssl"); err != nil {
|
||||
t.Skip("openssl not available")
|
||||
}
|
||||
vaultFile := filepath.Join(t.TempDir(), ".secret_vault")
|
||||
encrypt := `printf 'my-top-secret' | openssl enc -aes-256-cbc -md sha512 -a -pbkdf2 -iter 100000 -salt -pass pass:masterpw > ` + vaultFile
|
||||
if out, err := exec.Command("sh", "-c", encrypt).CombinedOutput(); err != nil {
|
||||
t.Fatalf("openssl encrypt failed: %v: %s", err, out)
|
||||
}
|
||||
|
||||
withVaultPassphrase(t, "masterpw")
|
||||
t.Setenv(environmentVariable, "environment-must-be-ignored")
|
||||
|
||||
var output, diagnostics bytes.Buffer
|
||||
err := run([]string{"--vault", vaultFile, "example.com", "alice"}, &output, &diagnostics)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want, err := password.Generate("example.com", "alice", "my-top-secret", password.DefaultOptions())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := strings.TrimSpace(output.String()); got != want {
|
||||
t.Fatalf("output = %q, want %q", got, want)
|
||||
}
|
||||
|
||||
if err := run([]string{"--vault", vaultFile, "example.com", "alice", "master"}, &output, &diagnostics); err == nil ||
|
||||
!strings.Contains(err.Error(), "cannot be combined") {
|
||||
t.Fatalf("error = %v, want source conflict with MASTER_PASSWORD", err)
|
||||
}
|
||||
if err := run([]string{"--vault", vaultFile, "--prompt", "example.com", "alice"}, &output, &diagnostics); err == nil ||
|
||||
!strings.Contains(err.Error(), "cannot be combined") {
|
||||
t.Fatalf("error = %v, want source conflict with --prompt", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigVaultIsUsedForProfile(t *testing.T) {
|
||||
if _, err := exec.LookPath("openssl"); err != nil {
|
||||
t.Skip("openssl not available")
|
||||
}
|
||||
vaultFile := filepath.Join(t.TempDir(), ".secret_vault")
|
||||
encrypt := `printf 'cfg-secret' | openssl enc -aes-256-cbc -md sha512 -a -pbkdf2 -iter 100000 -salt -pass pass:masterpw > ` + vaultFile
|
||||
if out, err := exec.Command("sh", "-c", encrypt).CombinedOutput(); err != nil {
|
||||
t.Fatalf("openssl encrypt failed: %v: %s", err, out)
|
||||
}
|
||||
|
||||
withConfig(t, `{"vault": "`+vaultFile+`", "profiles": {"w": {"login": "alice"}}}`)
|
||||
withVaultPassphrase(t, "masterpw")
|
||||
|
||||
var output, diagnostics bytes.Buffer
|
||||
if err := run([]string{"-P", "w", "--no-copy", "example.com"}, &output, &diagnostics); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want, err := password.Generate("example.com", "alice", "cfg-secret", password.DefaultOptions())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := strings.TrimSpace(output.String()); got != want {
|
||||
t.Fatalf("output = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExpandHome(t *testing.T) {
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
t.Skip("no home directory")
|
||||
}
|
||||
for _, test := range []struct{ in, want string }{
|
||||
{"~", home},
|
||||
{"~/bin/.secret_vault", filepath.Join(home, "bin", ".secret_vault")},
|
||||
{"/abs/path", "/abs/path"},
|
||||
{"relative", "relative"},
|
||||
} {
|
||||
if got := expandHome(test.in); got != test.want {
|
||||
t.Errorf("expandHome(%q) = %q, want %q", test.in, got, test.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestVaultPassphraseFromPipedStdin(t *testing.T) {
|
||||
if _, err := exec.LookPath("openssl"); err != nil {
|
||||
t.Skip("openssl not available")
|
||||
}
|
||||
vaultFile := filepath.Join(t.TempDir(), ".secret_vault")
|
||||
encrypt := `printf 'piped-secret' | openssl enc -aes-256-cbc -md sha512 -a -pbkdf2 -iter 100000 -salt -pass pass:masterpw > ` + vaultFile
|
||||
if out, err := exec.Command("sh", "-c", encrypt).CombinedOutput(); err != nil {
|
||||
t.Fatalf("openssl encrypt failed: %v: %s", err, out)
|
||||
}
|
||||
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
contents string
|
||||
}{
|
||||
{"newline", "masterpw\n"},
|
||||
{"crlf", "masterpw\r\n"},
|
||||
{"no trailing newline", "masterpw"},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
input, err := os.CreateTemp(t.TempDir(), "stdin")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := input.WriteString(test.contents); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := input.Seek(0, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
previous := os.Stdin
|
||||
os.Stdin = input
|
||||
defer func() { os.Stdin = previous }()
|
||||
|
||||
got, err := promptVaultPassphrase()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got != "masterpw" {
|
||||
t.Fatalf("passphrase = %q, want %q", got, "masterpw")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,7 @@ android {
|
||||
minSdk 21
|
||||
targetSdk 36
|
||||
versionCode 2
|
||||
versionName "0.1.2"
|
||||
versionName "0.2.0"
|
||||
// Default to the two realistic phone targets; override with
|
||||
// -Pabi=x86_64 etc. for emulator builds.
|
||||
def abis = project.findProperty('abi') ?: 'armeabi-v7a,arm64-v8a'
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
module github.com/waozixyz/gopass
|
||||
|
||||
go 1.24
|
||||
|
||||
require github.com/BurntSushi/xgb v0.0.0-20210121224620-deaf085860bc
|
||||
@@ -0,0 +1,2 @@
|
||||
github.com/BurntSushi/xgb v0.0.0-20210121224620-deaf085860bc h1:7D+Bh06CRPCJO3gr2F7h1sriovOZ8BMhca2Rg85c2nk=
|
||||
github.com/BurntSushi/xgb v0.0.0-20210121224620-deaf085860bc/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
|
||||
@@ -11,5 +11,5 @@
|
||||
<launchable type="desktop-id">xyz.waozi.pass.desktop</launchable>
|
||||
<url type="homepage">https://github.com/waozixyz/gopass</url>
|
||||
<provides><binary>gopass-gui</binary></provides>
|
||||
<releases><release version="0.1.2" date="2026-08-17"/><release version="0.1.1" date="2026-08-17"/><release version="0.1.0" date="2026-08-17"/></releases>
|
||||
<releases><release version="0.2.0" date="2026-08-18"/><release version="0.1.3" date="2026-08-17"/><release version="0.1.2" date="2026-08-17"/><release version="0.1.1" date="2026-08-17"/><release version="0.1.0" date="2026-08-17"/></releases>
|
||||
</component>
|
||||
@@ -0,0 +1,94 @@
|
||||
// Package vault decrypts OpenSSL-encrypted secret files so they can be used
|
||||
// as master passwords without storing them anywhere.
|
||||
package vault
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/pbkdf2"
|
||||
"crypto/sha512"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrFormat = errors.New("vault is not in OpenSSL salted base64 format")
|
||||
ErrDecrypt = errors.New("wrong vault passphrase or corrupted vault")
|
||||
)
|
||||
|
||||
// Decrypt decrypts a file produced by:
|
||||
//
|
||||
// openssl enc -aes-256-cbc -md sha512 -a -pbkdf2 -iter 100000 -salt \
|
||||
// -pass pass:... > vault
|
||||
//
|
||||
// File format: base64("Salted__" + 8-byte salt + AES-256-CBC ciphertext).
|
||||
// Key/IV are derived with PBKDF2-HMAC-SHA512(passphrase, salt, 100000, 48):
|
||||
// first 32 bytes are the AES key, the next 16 are the CBC IV.
|
||||
// Trailing newlines are stripped, matching the $(...) substitution of the
|
||||
// shell scripts this replaces.
|
||||
func Decrypt(path, passphrase string) (string, error) {
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// The base64 body may contain newlines; strip all whitespace first.
|
||||
var b strings.Builder
|
||||
for _, c := range raw {
|
||||
switch c {
|
||||
case '\n', '\r', ' ', '\t':
|
||||
default:
|
||||
b.WriteByte(c)
|
||||
}
|
||||
}
|
||||
data, err := base64.StdEncoding.DecodeString(b.String())
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("%w: %v", ErrFormat, err)
|
||||
}
|
||||
if len(data) < aes.BlockSize*2 || string(data[:8]) != "Salted__" {
|
||||
return "", ErrFormat
|
||||
}
|
||||
salt := data[8:16]
|
||||
ciphertext := data[16:]
|
||||
if len(ciphertext) == 0 || len(ciphertext)%aes.BlockSize != 0 {
|
||||
return "", ErrFormat
|
||||
}
|
||||
|
||||
keyIV, err := pbkdf2.Key(sha512.New, passphrase, salt, 100000, aes.BlockSize*3)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
key, iv := keyIV[:32], keyIV[32:48]
|
||||
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
plaintext := make([]byte, len(ciphertext))
|
||||
cipher.NewCBCDecrypter(block, iv).CryptBlocks(plaintext, ciphertext)
|
||||
|
||||
// Strip PKCS#7 padding; a bad pad almost always means a wrong passphrase.
|
||||
pad := int(plaintext[len(plaintext)-1])
|
||||
if pad == 0 || pad > aes.BlockSize || pad > len(plaintext) {
|
||||
return "", ErrDecrypt
|
||||
}
|
||||
for _, p := range plaintext[len(plaintext)-pad:] {
|
||||
if int(p) != pad {
|
||||
return "", ErrDecrypt
|
||||
}
|
||||
}
|
||||
plaintext = plaintext[:len(plaintext)-pad]
|
||||
|
||||
secret := strings.TrimRight(string(plaintext), "\n")
|
||||
clear(plaintext) // best effort: wipe the decrypted bytes
|
||||
return secret, nil
|
||||
}
|
||||
|
||||
func clear(buf []byte) {
|
||||
for i := range buf {
|
||||
buf[i] = 0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package vault
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Round-trip against the real openssl binary using the exact command line of
|
||||
// the original pass shell script.
|
||||
func TestDecryptAgainstOpenSSL(t *testing.T) {
|
||||
if _, err := exec.LookPath("openssl"); err != nil {
|
||||
t.Skip("openssl not available")
|
||||
}
|
||||
dir := t.TempDir()
|
||||
file := filepath.Join(dir, ".secret_vault")
|
||||
|
||||
encrypt := `printf 'my-top-secret' | openssl enc -aes-256-cbc -md sha512 -a -pbkdf2 -iter 100000 -salt -pass pass:masterpw > ` + file
|
||||
if out, err := exec.Command("sh", "-c", encrypt).CombinedOutput(); err != nil {
|
||||
t.Fatalf("openssl encrypt failed: %v: %s", err, out)
|
||||
}
|
||||
|
||||
got, err := Decrypt(file, "masterpw")
|
||||
if err != nil {
|
||||
t.Fatalf("Decrypt: %v", err)
|
||||
}
|
||||
if got != "my-top-secret" {
|
||||
t.Errorf("got %q, want %q", got, "my-top-secret")
|
||||
}
|
||||
|
||||
// Trailing newlines in the plaintext must be stripped ($(...) parity).
|
||||
encryptNL := `printf 'secret-with-newline\n\n' | openssl enc -aes-256-cbc -md sha512 -a -pbkdf2 -iter 100000 -salt -pass pass:masterpw > ` + file
|
||||
if out, err := exec.Command("sh", "-c", encryptNL).CombinedOutput(); err != nil {
|
||||
t.Fatalf("openssl encrypt failed: %v: %s", err, out)
|
||||
}
|
||||
got, err = Decrypt(file, "masterpw")
|
||||
if err != nil {
|
||||
t.Fatalf("Decrypt: %v", err)
|
||||
}
|
||||
if got != "secret-with-newline" {
|
||||
t.Errorf("got %q, want %q (trailing newlines stripped)", got, "secret-with-newline")
|
||||
}
|
||||
|
||||
if _, err := Decrypt(file, "wrong-passphrase"); err == nil {
|
||||
t.Error("expected error with wrong passphrase")
|
||||
}
|
||||
|
||||
if err := os.WriteFile(file, []byte("not-base64-$$$!!!"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := Decrypt(file, "masterpw"); err == nil {
|
||||
t.Error("expected error for non-OpenSSL file")
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
// Copyright (c) 2009 The XGB Authors. All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following disclaimer
|
||||
// in the documentation and/or other materials provided with the
|
||||
// distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from
|
||||
// this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
//
|
||||
// Subject to the terms and conditions of this License, Google hereby
|
||||
// grants to You a perpetual, worldwide, non-exclusive, no-charge,
|
||||
// royalty-free, irrevocable (except as stated in this section) patent
|
||||
// license to make, have made, use, offer to sell, sell, import, and
|
||||
// otherwise transfer this implementation of XGB, where such license
|
||||
// applies only to those patent claims licensable by Google that are
|
||||
// necessarily infringed by use of this implementation of XGB. If You
|
||||
// institute patent litigation against any entity (including a
|
||||
// cross-claim or counterclaim in a lawsuit) alleging that this
|
||||
// implementation of XGB or a Contribution incorporated within this
|
||||
// implementation of XGB constitutes direct or contributory patent
|
||||
// infringement, then any patent licenses granted to You under this
|
||||
// License for this implementation of XGB shall terminate as of the date
|
||||
// such litigation is filed.
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
package xgb
|
||||
|
||||
/*
|
||||
auth.go contains functions to facilitate the parsing of .Xauthority files.
|
||||
|
||||
It is largely unmodified from the original XGB package that I forked.
|
||||
*/
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
|
||||
// readAuthority reads the X authority file for the DISPLAY.
|
||||
// If hostname == "" or hostname == "localhost",
|
||||
// then use the system's hostname (as returned by os.Hostname) instead.
|
||||
func readAuthority(hostname, display string) (
|
||||
name string, data []byte, err error) {
|
||||
|
||||
// b is a scratch buffer to use and should be at least 256 bytes long
|
||||
// (i.e. it should be able to hold a hostname).
|
||||
b := make([]byte, 256)
|
||||
|
||||
// As per /usr/include/X11/Xauth.h.
|
||||
const familyLocal = 256
|
||||
const familyWild = 65535
|
||||
|
||||
if len(hostname) == 0 || hostname == "localhost" {
|
||||
hostname, err = os.Hostname()
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
}
|
||||
|
||||
fname := os.Getenv("XAUTHORITY")
|
||||
if len(fname) == 0 {
|
||||
home := os.Getenv("HOME")
|
||||
if len(home) == 0 {
|
||||
err = errors.New("Xauthority not found: $XAUTHORITY, $HOME not set")
|
||||
return "", nil, err
|
||||
}
|
||||
fname = home + "/.Xauthority"
|
||||
}
|
||||
|
||||
r, err := os.Open(fname)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
defer r.Close()
|
||||
|
||||
for {
|
||||
var family uint16
|
||||
if err := binary.Read(r, binary.BigEndian, &family); err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
|
||||
addr, err := getString(r, b)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
|
||||
disp, err := getString(r, b)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
|
||||
name0, err := getString(r, b)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
|
||||
data0, err := getBytes(r, b)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
|
||||
addrmatch := (family == familyWild) ||
|
||||
(family == familyLocal && addr == hostname)
|
||||
dispmatch := (disp == "") || (disp == display)
|
||||
|
||||
if addrmatch && dispmatch {
|
||||
return name0, data0, nil
|
||||
}
|
||||
}
|
||||
panic("unreachable")
|
||||
}
|
||||
|
||||
func getBytes(r io.Reader, b []byte) ([]byte, error) {
|
||||
var n uint16
|
||||
if err := binary.Read(r, binary.BigEndian, &n); err != nil {
|
||||
return nil, err
|
||||
} else if n > uint16(len(b)) {
|
||||
return nil, errors.New("bytes too long for buffer")
|
||||
}
|
||||
|
||||
if _, err := io.ReadFull(r, b[0:n]); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return b[0:n], nil
|
||||
}
|
||||
|
||||
func getString(r io.Reader, b []byte) (string, error) {
|
||||
b, err := getBytes(r, b)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(b), nil
|
||||
}
|
||||
+186
@@ -0,0 +1,186 @@
|
||||
package xgb
|
||||
|
||||
/*
|
||||
conn.go contains a couple of functions that do some real dirty work related
|
||||
to the initial connection handshake with X.
|
||||
|
||||
This code is largely unmodified from the original XGB package that I forked.
|
||||
*/
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// connect connects to the X server given in the 'display' string,
|
||||
// and does all the necessary setup handshaking.
|
||||
// If 'display' is empty it will be taken from os.Getenv("DISPLAY").
|
||||
// Note that you should read and understand the "Connection Setup" of the
|
||||
// X Protocol Reference Manual before changing this function:
|
||||
// http://goo.gl/4zGQg
|
||||
func (c *Conn) connect(display string) error {
|
||||
err := c.dial(display)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.postConnect()
|
||||
}
|
||||
|
||||
// connect init from to the net.Conn,
|
||||
func (c *Conn) connectNet(netConn net.Conn) error {
|
||||
c.conn = netConn
|
||||
return c.postConnect()
|
||||
}
|
||||
|
||||
// do the postConnect action after Conn get it's underly net.Conn
|
||||
func (c *Conn) postConnect() error {
|
||||
// Get authentication data
|
||||
authName, authData, err := readAuthority(c.host, c.display)
|
||||
noauth := false
|
||||
if err != nil {
|
||||
Logger.Printf("Could not get authority info: %v", err)
|
||||
Logger.Println("Trying connection without authority info...")
|
||||
authName = ""
|
||||
authData = []byte{}
|
||||
noauth = true
|
||||
}
|
||||
|
||||
// Assume that the authentication protocol is "MIT-MAGIC-COOKIE-1".
|
||||
if !noauth && (authName != "MIT-MAGIC-COOKIE-1" || len(authData) != 16) {
|
||||
return errors.New("unsupported auth protocol " + authName)
|
||||
}
|
||||
|
||||
buf := make([]byte, 12+Pad(len(authName))+Pad(len(authData)))
|
||||
buf[0] = 0x6c
|
||||
buf[1] = 0
|
||||
Put16(buf[2:], 11)
|
||||
Put16(buf[4:], 0)
|
||||
Put16(buf[6:], uint16(len(authName)))
|
||||
Put16(buf[8:], uint16(len(authData)))
|
||||
Put16(buf[10:], 0)
|
||||
copy(buf[12:], []byte(authName))
|
||||
copy(buf[12+Pad(len(authName)):], authData)
|
||||
if _, err = c.conn.Write(buf); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
head := make([]byte, 8)
|
||||
if _, err = io.ReadFull(c.conn, head[0:8]); err != nil {
|
||||
return err
|
||||
}
|
||||
code := head[0]
|
||||
reasonLen := head[1]
|
||||
major := Get16(head[2:])
|
||||
minor := Get16(head[4:])
|
||||
dataLen := Get16(head[6:])
|
||||
|
||||
if major != 11 || minor != 0 {
|
||||
return fmt.Errorf("x protocol version mismatch: %d.%d", major, minor)
|
||||
}
|
||||
|
||||
buf = make([]byte, int(dataLen)*4+8, int(dataLen)*4+8)
|
||||
copy(buf, head)
|
||||
if _, err = io.ReadFull(c.conn, buf[8:]); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if code == 0 {
|
||||
reason := buf[8 : 8+reasonLen]
|
||||
return fmt.Errorf("x protocol authentication refused: %s",
|
||||
string(reason))
|
||||
}
|
||||
|
||||
// Unfortunately, it isn't really feasible to read the setup bytes here,
|
||||
// since the code to do so is in a different package.
|
||||
// Users must call 'xproto.Setup(X)' to get the setup info.
|
||||
c.SetupBytes = buf
|
||||
|
||||
// But also read stuff that we *need* to get started.
|
||||
c.setupResourceIdBase = Get32(buf[12:])
|
||||
c.setupResourceIdMask = Get32(buf[16:])
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// dial initializes the actual net connection with X.
|
||||
func (c *Conn) dial(display string) error {
|
||||
if len(display) == 0 {
|
||||
display = os.Getenv("DISPLAY")
|
||||
}
|
||||
|
||||
display0 := display
|
||||
if len(display) == 0 {
|
||||
return errors.New("empty display string")
|
||||
}
|
||||
|
||||
colonIdx := strings.LastIndex(display, ":")
|
||||
if colonIdx < 0 {
|
||||
return errors.New("bad display string: " + display0)
|
||||
}
|
||||
|
||||
var protocol, socket string
|
||||
|
||||
if display[0] == '/' {
|
||||
socket = display[0:colonIdx]
|
||||
} else {
|
||||
slashIdx := strings.LastIndex(display, "/")
|
||||
if slashIdx >= 0 {
|
||||
protocol = display[0:slashIdx]
|
||||
c.host = display[slashIdx+1 : colonIdx]
|
||||
} else {
|
||||
c.host = display[0:colonIdx]
|
||||
}
|
||||
}
|
||||
|
||||
display = display[colonIdx+1 : len(display)]
|
||||
if len(display) == 0 {
|
||||
return errors.New("bad display string: " + display0)
|
||||
}
|
||||
|
||||
var scr string
|
||||
dotIdx := strings.LastIndex(display, ".")
|
||||
if dotIdx < 0 {
|
||||
c.display = display[0:]
|
||||
} else {
|
||||
c.display = display[0:dotIdx]
|
||||
scr = display[dotIdx+1:]
|
||||
}
|
||||
|
||||
var err error
|
||||
c.DisplayNumber, err = strconv.Atoi(c.display)
|
||||
if err != nil || c.DisplayNumber < 0 {
|
||||
return errors.New("bad display string: " + display0)
|
||||
}
|
||||
|
||||
if len(scr) != 0 {
|
||||
c.DefaultScreen, err = strconv.Atoi(scr)
|
||||
if err != nil {
|
||||
return errors.New("bad display string: " + display0)
|
||||
}
|
||||
}
|
||||
|
||||
// Connect to server
|
||||
if len(socket) != 0 {
|
||||
c.conn, err = net.Dial("unix", socket+":"+c.display)
|
||||
} else if len(c.host) != 0 && c.host != "unix" {
|
||||
if protocol == "" {
|
||||
protocol = "tcp"
|
||||
}
|
||||
c.conn, err = net.Dial(protocol,
|
||||
c.host+":"+strconv.Itoa(6000+c.DisplayNumber))
|
||||
} else {
|
||||
c.host = ""
|
||||
c.conn, err = net.Dial("unix", "/tmp/.X11-unix/X"+c.display)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return errors.New("cannot connect to " + display0 + ": " + err.Error())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
package xgb
|
||||
|
||||
import (
|
||||
"errors"
|
||||
)
|
||||
|
||||
// Cookie is the internal representation of a cookie, where one is generated
|
||||
// for *every* request sent by XGB.
|
||||
// 'cookie' is most frequently used by embedding it into a more specific
|
||||
// kind of cookie, i.e., 'GetInputFocusCookie'.
|
||||
type Cookie struct {
|
||||
conn *Conn
|
||||
Sequence uint16
|
||||
replyChan chan []byte
|
||||
errorChan chan error
|
||||
pingChan chan bool
|
||||
}
|
||||
|
||||
// NewCookie creates a new cookie with the correct channels initialized
|
||||
// depending upon the values of 'checked' and 'reply'. Together, there are
|
||||
// four different kinds of cookies. (See more detailed comments in the
|
||||
// function for more info on those.)
|
||||
// Note that a sequence number is not set until just before the request
|
||||
// corresponding to this cookie is sent over the wire.
|
||||
//
|
||||
// Unless you're building requests from bytes by hand, this method should
|
||||
// not be used.
|
||||
func (c *Conn) NewCookie(checked, reply bool) *Cookie {
|
||||
cookie := &Cookie{
|
||||
conn: c,
|
||||
Sequence: 0, // we add the sequence id just before sending a request
|
||||
replyChan: nil,
|
||||
errorChan: nil,
|
||||
pingChan: nil,
|
||||
}
|
||||
|
||||
// There are four different kinds of cookies:
|
||||
// Checked requests with replies get a reply channel and an error channel.
|
||||
// Unchecked requests with replies get a reply channel and a ping channel.
|
||||
// Checked requests w/o replies get a ping channel and an error channel.
|
||||
// Unchecked requests w/o replies get no channels.
|
||||
// The reply channel is used to send reply data.
|
||||
// The error channel is used to send error data.
|
||||
// The ping channel is used when one of the 'reply' or 'error' channels
|
||||
// is missing but the other is present. The ping channel is way to force
|
||||
// the blocking to stop and basically say "the error has been received
|
||||
// in the main event loop" (when the ping channel is coupled with a reply
|
||||
// channel) or "the request you made that has no reply was successful"
|
||||
// (when the ping channel is coupled with an error channel).
|
||||
if checked {
|
||||
cookie.errorChan = make(chan error, 1)
|
||||
if !reply {
|
||||
cookie.pingChan = make(chan bool, 1)
|
||||
}
|
||||
}
|
||||
if reply {
|
||||
cookie.replyChan = make(chan []byte, 1)
|
||||
if !checked {
|
||||
cookie.pingChan = make(chan bool, 1)
|
||||
}
|
||||
}
|
||||
|
||||
return cookie
|
||||
}
|
||||
|
||||
// Reply detects whether this is a checked or unchecked cookie, and calls
|
||||
// 'replyChecked' or 'replyUnchecked' appropriately.
|
||||
//
|
||||
// Unless you're building requests from bytes by hand, this method should
|
||||
// not be used.
|
||||
func (c Cookie) Reply() ([]byte, error) {
|
||||
// checked
|
||||
if c.errorChan != nil {
|
||||
return c.replyChecked()
|
||||
}
|
||||
return c.replyUnchecked()
|
||||
}
|
||||
|
||||
// replyChecked waits for a response on either the replyChan or errorChan
|
||||
// channels. If the former arrives, the bytes are returned with a nil error.
|
||||
// If the latter arrives, no bytes are returned (nil) and the error received
|
||||
// is returned.
|
||||
//
|
||||
// Unless you're building requests from bytes by hand, this method should
|
||||
// not be used.
|
||||
func (c Cookie) replyChecked() ([]byte, error) {
|
||||
if c.replyChan == nil {
|
||||
return nil, errors.New("Cannot call 'replyChecked' on a cookie that " +
|
||||
"is not expecting a *reply* or an error.")
|
||||
}
|
||||
if c.errorChan == nil {
|
||||
return nil, errors.New("Cannot call 'replyChecked' on a cookie that " +
|
||||
"is not expecting a reply or an *error*.")
|
||||
}
|
||||
|
||||
select {
|
||||
case reply := <-c.replyChan:
|
||||
return reply, nil
|
||||
case err := <-c.errorChan:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
// replyUnchecked waits for a response on either the replyChan or pingChan
|
||||
// channels. If the former arrives, the bytes are returned with a nil error.
|
||||
// If the latter arrives, no bytes are returned (nil) and a nil error
|
||||
// is returned. (In the latter case, the corresponding error can be retrieved
|
||||
// from (Wait|Poll)ForEvent asynchronously.)
|
||||
// In all honesty, you *probably* don't want to use this method.
|
||||
//
|
||||
// Unless you're building requests from bytes by hand, this method should
|
||||
// not be used.
|
||||
func (c Cookie) replyUnchecked() ([]byte, error) {
|
||||
if c.replyChan == nil {
|
||||
return nil, errors.New("Cannot call 'replyUnchecked' on a cookie " +
|
||||
"that is not expecting a *reply*.")
|
||||
}
|
||||
|
||||
select {
|
||||
case reply := <-c.replyChan:
|
||||
return reply, nil
|
||||
case <-c.pingChan:
|
||||
return nil, nil
|
||||
}
|
||||
}
|
||||
|
||||
// Check is used for checked requests that have no replies. It is a mechanism
|
||||
// by which to report "success" or "error" in a synchronous fashion. (Therefore,
|
||||
// unchecked requests without replies cannot use this method.)
|
||||
// If the request causes an error, it is sent to this cookie's errorChan.
|
||||
// If the request was successful, there is no response from the server.
|
||||
// Thus, pingChan is sent a value when the *next* reply is read.
|
||||
// If no more replies are being processed, we force a round trip request with
|
||||
// GetInputFocus.
|
||||
//
|
||||
// Unless you're building requests from bytes by hand, this method should
|
||||
// not be used.
|
||||
func (c Cookie) Check() error {
|
||||
if c.replyChan != nil {
|
||||
return errors.New("Cannot call 'Check' on a cookie that is " +
|
||||
"expecting a *reply*. Use 'Reply' instead.")
|
||||
}
|
||||
if c.errorChan == nil {
|
||||
return errors.New("Cannot call 'Check' on a cookie that is " +
|
||||
"not expecting a possible *error*.")
|
||||
}
|
||||
|
||||
// First do a quick non-blocking check to see if we've been pinged.
|
||||
select {
|
||||
case err := <-c.errorChan:
|
||||
return err
|
||||
case <-c.pingChan:
|
||||
return nil
|
||||
default:
|
||||
}
|
||||
|
||||
// Now force a round trip and try again, but block this time.
|
||||
c.conn.Sync()
|
||||
select {
|
||||
case err := <-c.errorChan:
|
||||
return err
|
||||
case <-c.pingChan:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
/*
|
||||
Package XGB provides the X Go Binding, which is a low-level API to communicate
|
||||
with the core X protocol and many of the X extensions.
|
||||
|
||||
It is *very* closely modeled on XCB, so that experience with XCB (or xpyb) is
|
||||
easily translatable to XGB. That is, it uses the same cookie/reply model
|
||||
and is thread safe. There are otherwise no major differences (in the API).
|
||||
|
||||
Most uses of XGB typically fall under the realm of window manager and GUI kit
|
||||
development, but other applications (like pagers, panels, tilers, etc.) may
|
||||
also require XGB. Moreover, it is a near certainty that if you need to work
|
||||
with X, xgbutil will be of great use to you as well:
|
||||
https://github.com/BurntSushi/xgbutil
|
||||
|
||||
Example
|
||||
|
||||
This is an extremely terse example that demonstrates how to connect to X,
|
||||
create a window, listen to StructureNotify events and Key{Press,Release}
|
||||
events, map the window, and print out all events received. An example with
|
||||
accompanying documentation can be found in examples/create-window.
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/BurntSushi/xgb"
|
||||
"github.com/BurntSushi/xgb/xproto"
|
||||
)
|
||||
|
||||
func main() {
|
||||
X, err := xgb.NewConn()
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
|
||||
wid, _ := xproto.NewWindowId(X)
|
||||
screen := xproto.Setup(X).DefaultScreen(X)
|
||||
xproto.CreateWindow(X, screen.RootDepth, wid, screen.Root,
|
||||
0, 0, 500, 500, 0,
|
||||
xproto.WindowClassInputOutput, screen.RootVisual,
|
||||
xproto.CwBackPixel | xproto.CwEventMask,
|
||||
[]uint32{ // values must be in the order defined by the protocol
|
||||
0xffffffff,
|
||||
xproto.EventMaskStructureNotify |
|
||||
xproto.EventMaskKeyPress |
|
||||
xproto.EventMaskKeyRelease})
|
||||
|
||||
xproto.MapWindow(X, wid)
|
||||
for {
|
||||
ev, xerr := X.WaitForEvent()
|
||||
if ev == nil && xerr == nil {
|
||||
fmt.Println("Both event and error are nil. Exiting...")
|
||||
return
|
||||
}
|
||||
|
||||
if ev != nil {
|
||||
fmt.Printf("Event: %s\n", ev)
|
||||
}
|
||||
if xerr != nil {
|
||||
fmt.Printf("Error: %s\n", xerr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Xinerama Example
|
||||
|
||||
This is another small example that shows how to query Xinerama for geometry
|
||||
information of each active head. Accompanying documentation for this example
|
||||
can be found in examples/xinerama.
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"github.com/BurntSushi/xgb"
|
||||
"github.com/BurntSushi/xgb/xinerama"
|
||||
)
|
||||
|
||||
func main() {
|
||||
X, err := xgb.NewConn()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
// Initialize the Xinerama extension.
|
||||
// The appropriate 'Init' function must be run for *every*
|
||||
// extension before any of its requests can be used.
|
||||
err = xinerama.Init(X)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
reply, err := xinerama.QueryScreens(X).Reply()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
fmt.Printf("Number of heads: %d\n", reply.Number)
|
||||
for i, screen := range reply.ScreenInfo {
|
||||
fmt.Printf("%d :: X: %d, Y: %d, Width: %d, Height: %d\n",
|
||||
i, screen.XOrg, screen.YOrg, screen.Width, screen.Height)
|
||||
}
|
||||
}
|
||||
|
||||
Parallelism
|
||||
|
||||
XGB can benefit greatly from parallelism due to its concurrent design. For
|
||||
evidence of this claim, please see the benchmarks in xproto/xproto_test.go.
|
||||
|
||||
Tests
|
||||
|
||||
xproto/xproto_test.go contains a number of contrived tests that stress
|
||||
particular corners of XGB that I presume could be problem areas. Namely:
|
||||
requests with no replies, requests with replies, checked errors, unchecked
|
||||
errors, sequence number wrapping, cookie buffer flushing (i.e., forcing a round
|
||||
trip every N requests made that don't have a reply), getting/setting properties
|
||||
and creating a window and listening to StructureNotify events.
|
||||
|
||||
Code Generator
|
||||
|
||||
Both XCB and xpyb use the same Python module (xcbgen) for a code generator. XGB
|
||||
(before this fork) used the same code generator as well, but in my attempt to
|
||||
add support for more extensions, I found the code generator extremely difficult
|
||||
to work with. Therefore, I re-wrote the code generator in Go. It can be found
|
||||
in its own sub-package, xgbgen, of xgb. My design of xgbgen includes a rough
|
||||
consideration that it could be used for other languages.
|
||||
|
||||
What works
|
||||
|
||||
I am reasonably confident that the core X protocol is in full working form. I've
|
||||
also tested the Xinerama and RandR extensions sparingly. Many of the other
|
||||
existing extensions have Go source generated (and are compilable) and are
|
||||
included in this package, but I am currently unsure of their status. They
|
||||
*should* work.
|
||||
|
||||
What does not work
|
||||
|
||||
XKB is the only extension that intentionally does not work, although I suspect
|
||||
that GLX also does not work (however, there is Go source code for GLX that
|
||||
compiles, unlike XKB). I don't currently have any intention of getting XKB
|
||||
working, due to its complexity and my current mental incapacity to test it.
|
||||
|
||||
*/
|
||||
package xgb
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
package xgb
|
||||
|
||||
/*
|
||||
help.go is meant to contain a rough hodge podge of functions that are mainly
|
||||
used in the auto generated code. Indeed, several functions here are simple
|
||||
wrappers so that the sub-packages don't need to be smart about which stdlib
|
||||
packages to import.
|
||||
|
||||
Also, the 'Get..' and 'Put..' functions are used through the core xgb package
|
||||
too. (xgbutil uses them too.)
|
||||
*/
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// StringsJoin is an alias to strings.Join. It allows us to avoid having to
|
||||
// import 'strings' in each of the generated Go files.
|
||||
func StringsJoin(ss []string, sep string) string {
|
||||
return strings.Join(ss, sep)
|
||||
}
|
||||
|
||||
// Sprintf is so we don't need to import 'fmt' in the generated Go files.
|
||||
func Sprintf(format string, v ...interface{}) string {
|
||||
return fmt.Sprintf(format, v...)
|
||||
}
|
||||
|
||||
// Errorf is just a wrapper for fmt.Errorf. Exists for the same reason
|
||||
// that 'stringsJoin' and 'sprintf' exists.
|
||||
func Errorf(format string, v ...interface{}) error {
|
||||
return fmt.Errorf(format, v...)
|
||||
}
|
||||
|
||||
// Pad a length to align on 4 bytes.
|
||||
func Pad(n int) int {
|
||||
return (n + 3) & ^3
|
||||
}
|
||||
|
||||
// PopCount counts the number of bits set in a value list mask.
|
||||
func PopCount(mask0 int) int {
|
||||
mask := uint32(mask0)
|
||||
n := 0
|
||||
for i := uint32(0); i < 32; i++ {
|
||||
if mask&(1<<i) != 0 {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// Put16 takes a 16 bit integer and copies it into a byte slice.
|
||||
func Put16(buf []byte, v uint16) {
|
||||
buf[0] = byte(v)
|
||||
buf[1] = byte(v >> 8)
|
||||
}
|
||||
|
||||
// Put32 takes a 32 bit integer and copies it into a byte slice.
|
||||
func Put32(buf []byte, v uint32) {
|
||||
buf[0] = byte(v)
|
||||
buf[1] = byte(v >> 8)
|
||||
buf[2] = byte(v >> 16)
|
||||
buf[3] = byte(v >> 24)
|
||||
}
|
||||
|
||||
// Put64 takes a 64 bit integer and copies it into a byte slice.
|
||||
func Put64(buf []byte, v uint64) {
|
||||
buf[0] = byte(v)
|
||||
buf[1] = byte(v >> 8)
|
||||
buf[2] = byte(v >> 16)
|
||||
buf[3] = byte(v >> 24)
|
||||
buf[4] = byte(v >> 32)
|
||||
buf[5] = byte(v >> 40)
|
||||
buf[6] = byte(v >> 48)
|
||||
buf[7] = byte(v >> 56)
|
||||
}
|
||||
|
||||
// Get16 constructs a 16 bit integer from the beginning of a byte slice.
|
||||
func Get16(buf []byte) uint16 {
|
||||
v := uint16(buf[0])
|
||||
v |= uint16(buf[1]) << 8
|
||||
return v
|
||||
}
|
||||
|
||||
// Get32 constructs a 32 bit integer from the beginning of a byte slice.
|
||||
func Get32(buf []byte) uint32 {
|
||||
v := uint32(buf[0])
|
||||
v |= uint32(buf[1]) << 8
|
||||
v |= uint32(buf[2]) << 16
|
||||
v |= uint32(buf[3]) << 24
|
||||
return v
|
||||
}
|
||||
|
||||
// Get64 constructs a 64 bit integer from the beginning of a byte slice.
|
||||
func Get64(buf []byte) uint64 {
|
||||
v := uint64(buf[0])
|
||||
v |= uint64(buf[1]) << 8
|
||||
v |= uint64(buf[2]) << 16
|
||||
v |= uint64(buf[3]) << 24
|
||||
v |= uint64(buf[4]) << 32
|
||||
v |= uint64(buf[5]) << 40
|
||||
v |= uint64(buf[6]) << 48
|
||||
v |= uint64(buf[7]) << 56
|
||||
return v
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package xgb
|
||||
|
||||
// Sync sends a round trip request and waits for the response.
|
||||
// This forces all pending cookies to be dealt with.
|
||||
// You actually shouldn't need to use this like you might with Xlib. Namely,
|
||||
// buffers are automatically flushed using Go's channels and round trip requests
|
||||
// are forced where appropriate automatically.
|
||||
func (c *Conn) Sync() {
|
||||
cookie := c.NewCookie(true, true)
|
||||
c.NewRequest(c.getInputFocusRequest(), cookie)
|
||||
cookie.Reply() // wait for the buffer to clear
|
||||
}
|
||||
|
||||
// getInputFocusRequest writes the raw bytes to a buffer.
|
||||
// It is duplicated from xproto/xproto.go.
|
||||
func (c *Conn) getInputFocusRequest() []byte {
|
||||
size := 4
|
||||
b := 0
|
||||
buf := make([]byte, size)
|
||||
|
||||
buf[b] = 43 // request opcode
|
||||
b += 1
|
||||
|
||||
b += 1 // padding
|
||||
Put16(buf[b:], uint16(size/4)) // write request size in 4-byte units
|
||||
b += 2
|
||||
|
||||
return buf
|
||||
}
|
||||
+554
@@ -0,0 +1,554 @@
|
||||
package xgb
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"os"
|
||||
"sync"
|
||||
)
|
||||
|
||||
var (
|
||||
// Where to log error-messages. Defaults to stderr.
|
||||
// To disable logging, just set this to log.New(ioutil.Discard, "", 0)
|
||||
Logger = log.New(os.Stderr, "XGB: ", log.Lshortfile)
|
||||
)
|
||||
|
||||
const (
|
||||
// cookieBuffer represents the queue size of cookies existing at any
|
||||
// point in time. The size of the buffer is really only important when
|
||||
// there are many requests without replies made in sequence. Once the
|
||||
// buffer fills, a round trip request is made to clear the buffer.
|
||||
cookieBuffer = 1000
|
||||
|
||||
// xidBuffer represents the queue size of the xid channel.
|
||||
// I don't think this value matters much, since xid generation is not
|
||||
// that expensive.
|
||||
xidBuffer = 5
|
||||
|
||||
// seqBuffer represents the queue size of the sequence number channel.
|
||||
// I don't think this value matters much, since sequence number generation
|
||||
// is not that expensive.
|
||||
seqBuffer = 5
|
||||
|
||||
// reqBuffer represents the queue size of the number of requests that
|
||||
// can be made until new ones block. This value seems OK.
|
||||
reqBuffer = 100
|
||||
|
||||
// eventBuffer represents the queue size of the number of events or errors
|
||||
// that can be loaded off the wire and not grabbed with WaitForEvent
|
||||
// until reading an event blocks. This value should be big enough to handle
|
||||
// bursts of events.
|
||||
eventBuffer = 5000
|
||||
)
|
||||
|
||||
// A Conn represents a connection to an X server.
|
||||
type Conn struct {
|
||||
host string
|
||||
conn net.Conn
|
||||
display string
|
||||
DisplayNumber int
|
||||
DefaultScreen int
|
||||
SetupBytes []byte
|
||||
|
||||
setupResourceIdBase uint32
|
||||
setupResourceIdMask uint32
|
||||
|
||||
eventChan chan eventOrError
|
||||
cookieChan chan *Cookie
|
||||
xidChan chan xid
|
||||
seqChan chan uint16
|
||||
reqChan chan *request
|
||||
closing chan chan struct{}
|
||||
|
||||
// ExtLock is a lock used whenever new extensions are initialized.
|
||||
// It should not be used. It is exported for use in the extension
|
||||
// sub-packages.
|
||||
ExtLock sync.RWMutex
|
||||
|
||||
// Extensions is a map from extension name to major opcode. It should
|
||||
// not be used. It is exported for use in the extension sub-packages.
|
||||
Extensions map[string]byte
|
||||
}
|
||||
|
||||
// NewConn creates a new connection instance. It initializes locks, data
|
||||
// structures, and performs the initial handshake. (The code for the handshake
|
||||
// has been relegated to conn.go.)
|
||||
func NewConn() (*Conn, error) {
|
||||
return NewConnDisplay("")
|
||||
}
|
||||
|
||||
// NewConnDisplay is just like NewConn, but allows a specific DISPLAY
|
||||
// string to be used.
|
||||
// If 'display' is empty it will be taken from os.Getenv("DISPLAY").
|
||||
//
|
||||
// Examples:
|
||||
// NewConn(":1") -> net.Dial("unix", "", "/tmp/.X11-unix/X1")
|
||||
// NewConn("/tmp/launch-12/:0") -> net.Dial("unix", "", "/tmp/launch-12/:0")
|
||||
// NewConn("hostname:2.1") -> net.Dial("tcp", "", "hostname:6002")
|
||||
// NewConn("tcp/hostname:1.0") -> net.Dial("tcp", "", "hostname:6001")
|
||||
func NewConnDisplay(display string) (*Conn, error) {
|
||||
conn := &Conn{}
|
||||
|
||||
// First connect. This reads authority, checks DISPLAY environment
|
||||
// variable, and loads the initial Setup info.
|
||||
err := conn.connect(display)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return postNewConn(conn)
|
||||
}
|
||||
|
||||
// NewConnDisplay is just like NewConn, but allows a specific net.Conn
|
||||
// to be used.
|
||||
func NewConnNet(netConn net.Conn) (*Conn, error) {
|
||||
conn := &Conn{}
|
||||
|
||||
// First connect. This reads authority, checks DISPLAY environment
|
||||
// variable, and loads the initial Setup info.
|
||||
err := conn.connectNet(netConn)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return postNewConn(conn)
|
||||
}
|
||||
|
||||
func postNewConn(conn *Conn) (*Conn, error) {
|
||||
conn.Extensions = make(map[string]byte)
|
||||
|
||||
conn.cookieChan = make(chan *Cookie, cookieBuffer)
|
||||
conn.xidChan = make(chan xid, xidBuffer)
|
||||
conn.seqChan = make(chan uint16, seqBuffer)
|
||||
conn.reqChan = make(chan *request, reqBuffer)
|
||||
conn.eventChan = make(chan eventOrError, eventBuffer)
|
||||
conn.closing = make(chan chan struct{}, 1)
|
||||
|
||||
go conn.generateXIds()
|
||||
go conn.generateSeqIds()
|
||||
go conn.sendRequests()
|
||||
go conn.readResponses()
|
||||
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
// Close gracefully closes the connection to the X server.
|
||||
func (c *Conn) Close() {
|
||||
close(c.reqChan)
|
||||
}
|
||||
|
||||
// Event is an interface that can contain any of the events returned by the
|
||||
// server. Use a type assertion switch to extract the Event structs.
|
||||
type Event interface {
|
||||
Bytes() []byte
|
||||
String() string
|
||||
}
|
||||
|
||||
// NewEventFun is the type of function use to construct events from raw bytes.
|
||||
// It should not be used. It is exported for use in the extension sub-packages.
|
||||
type NewEventFun func(buf []byte) Event
|
||||
|
||||
// NewEventFuncs is a map from event numbers to functions that create
|
||||
// the corresponding event. It should not be used. It is exported for use
|
||||
// in the extension sub-packages.
|
||||
var NewEventFuncs = make(map[int]NewEventFun)
|
||||
|
||||
// NewExtEventFuncs is a temporary map that stores event constructor functions
|
||||
// for each extension. When an extension is initialized, each event for that
|
||||
// extension is added to the 'NewEventFuncs' map. It should not be used. It is
|
||||
// exported for use in the extension sub-packages.
|
||||
var NewExtEventFuncs = make(map[string]map[int]NewEventFun)
|
||||
|
||||
// Error is an interface that can contain any of the errors returned by
|
||||
// the server. Use a type assertion switch to extract the Error structs.
|
||||
type Error interface {
|
||||
SequenceId() uint16
|
||||
BadId() uint32
|
||||
Error() string
|
||||
}
|
||||
|
||||
// NewErrorFun is the type of function use to construct errors from raw bytes.
|
||||
// It should not be used. It is exported for use in the extension sub-packages.
|
||||
type NewErrorFun func(buf []byte) Error
|
||||
|
||||
// NewErrorFuncs is a map from error numbers to functions that create
|
||||
// the corresponding error. It should not be used. It is exported for use in
|
||||
// the extension sub-packages.
|
||||
var NewErrorFuncs = make(map[int]NewErrorFun)
|
||||
|
||||
// NewExtErrorFuncs is a temporary map that stores error constructor functions
|
||||
// for each extension. When an extension is initialized, each error for that
|
||||
// extension is added to the 'NewErrorFuncs' map. It should not be used. It is
|
||||
// exported for use in the extension sub-packages.
|
||||
var NewExtErrorFuncs = make(map[string]map[int]NewErrorFun)
|
||||
|
||||
// eventOrError corresponds to values that can be either an event or an
|
||||
// error.
|
||||
type eventOrError interface{}
|
||||
|
||||
// NewId generates a new unused ID for use with requests like CreateWindow.
|
||||
// If no new ids can be generated, the id returned is 0 and error is non-nil.
|
||||
// This shouldn't be used directly, and is exported for use in the extension
|
||||
// sub-packages.
|
||||
// If you need identifiers, use the appropriate constructor.
|
||||
// e.g., For a window id, use xproto.NewWindowId. For
|
||||
// a new pixmap id, use xproto.NewPixmapId. And so on.
|
||||
func (c *Conn) NewId() (uint32, error) {
|
||||
xid := <-c.xidChan
|
||||
if xid.err != nil {
|
||||
return 0, xid.err
|
||||
}
|
||||
return xid.id, nil
|
||||
}
|
||||
|
||||
// xid encapsulates a resource identifier being sent over the Conn.xidChan
|
||||
// channel. If no new resource id can be generated, id is set to 0 and a
|
||||
// non-nil error is set in xid.err.
|
||||
type xid struct {
|
||||
id uint32
|
||||
err error
|
||||
}
|
||||
|
||||
// generateXids sends new Ids down the channel for NewId to use.
|
||||
// generateXids should be run in its own goroutine.
|
||||
// This needs to be updated to use the XC Misc extension once we run out of
|
||||
// new ids.
|
||||
// Thanks to libxcb/src/xcb_xid.c. This code is greatly inspired by it.
|
||||
func (conn *Conn) generateXIds() {
|
||||
defer close(conn.xidChan)
|
||||
|
||||
// This requires some explanation. From the horse's mouth:
|
||||
// "The resource-id-mask contains a single contiguous set of bits (at least
|
||||
// 18). The client allocates resource IDs for types WINDOW, PIXMAP,
|
||||
// CURSOR, FONT, GCONTEXT, and COLORMAP by choosing a value with only some
|
||||
// subset of these bits set and ORing it with resource-id-base. Only values
|
||||
// constructed in this way can be used to name newly created resources over
|
||||
// this connection."
|
||||
// So for example (using 8 bit integers), the mask might look like:
|
||||
// 00111000
|
||||
// So that valid values would be 00101000, 00110000, 00001000, and so on.
|
||||
// Thus, the idea is to increment it by the place of the last least
|
||||
// significant '1'. In this case, that value would be 00001000. To get
|
||||
// that value, we can AND the original mask with its two's complement:
|
||||
// 00111000 & 11001000 = 00001000.
|
||||
// And we use that value to increment the last resource id to get a new one.
|
||||
// (And then, of course, we OR it with resource-id-base.)
|
||||
inc := conn.setupResourceIdMask & -conn.setupResourceIdMask
|
||||
max := conn.setupResourceIdMask
|
||||
last := uint32(0)
|
||||
for {
|
||||
// TODO: Use the XC Misc extension to look for released ids.
|
||||
if last > 0 && last >= max-inc+1 {
|
||||
conn.xidChan <- xid{
|
||||
id: 0,
|
||||
err: errors.New("There are no more available resource" +
|
||||
"identifiers."),
|
||||
}
|
||||
}
|
||||
|
||||
last += inc
|
||||
conn.xidChan <- xid{
|
||||
id: last | conn.setupResourceIdBase,
|
||||
err: nil,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// newSeqId fetches the next sequence id from the Conn.seqChan channel.
|
||||
func (c *Conn) newSequenceId() uint16 {
|
||||
return <-c.seqChan
|
||||
}
|
||||
|
||||
// generateSeqIds returns new sequence ids. It is meant to be run in its
|
||||
// own goroutine.
|
||||
// A sequence id is generated for *every* request. It's the identifier used
|
||||
// to match up replies with requests.
|
||||
// Since sequence ids can only be 16 bit integers we start over at zero when it
|
||||
// comes time to wrap.
|
||||
// N.B. As long as the cookie buffer is less than 2^16, there are no limitations
|
||||
// on the number (or kind) of requests made in sequence.
|
||||
func (c *Conn) generateSeqIds() {
|
||||
defer close(c.seqChan)
|
||||
|
||||
seqid := uint16(1)
|
||||
for {
|
||||
c.seqChan <- seqid
|
||||
if seqid == uint16((1<<16)-1) {
|
||||
seqid = 0
|
||||
} else {
|
||||
seqid++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// request encapsulates a buffer of raw bytes (containing the request data)
|
||||
// and a cookie, which when combined represents a single request.
|
||||
// The cookie is used to match up the reply/error.
|
||||
type request struct {
|
||||
buf []byte
|
||||
cookie *Cookie
|
||||
|
||||
// seq is closed when the request (cookie) has been sequenced by the Conn.
|
||||
seq chan struct{}
|
||||
}
|
||||
|
||||
// NewRequest takes the bytes and a cookie of a particular request, constructs
|
||||
// a request type, and sends it over the Conn.reqChan channel.
|
||||
// Note that the sequence number is added to the cookie after it is sent
|
||||
// over the request channel, but before it is sent to X.
|
||||
//
|
||||
// Note that you may safely use NewRequest to send arbitrary byte requests
|
||||
// to X. The resulting cookie can be used just like any normal cookie and
|
||||
// abides by the same rules, except that for replies, you'll get back the
|
||||
// raw byte data. This may be useful for performance critical sections where
|
||||
// every allocation counts, since all X requests in XGB allocate a new byte
|
||||
// slice. In contrast, NewRequest allocates one small request struct and
|
||||
// nothing else. (Except when the cookie buffer is full and has to be flushed.)
|
||||
//
|
||||
// If you're using NewRequest manually, you'll need to use NewCookie to create
|
||||
// a new cookie.
|
||||
//
|
||||
// In all likelihood, you should be able to copy and paste with some minor
|
||||
// edits the generated code for the request you want to issue.
|
||||
func (c *Conn) NewRequest(buf []byte, cookie *Cookie) {
|
||||
seq := make(chan struct{})
|
||||
c.reqChan <- &request{buf: buf, cookie: cookie, seq: seq}
|
||||
<-seq
|
||||
}
|
||||
|
||||
// sendRequests is run as a single goroutine that takes requests and writes
|
||||
// the bytes to the wire and adds the cookie to the cookie queue.
|
||||
// It is meant to be run as its own goroutine.
|
||||
func (c *Conn) sendRequests() {
|
||||
defer close(c.cookieChan)
|
||||
|
||||
for req := range c.reqChan {
|
||||
// ho there! if the cookie channel is nearly full, force a round
|
||||
// trip to clear out the cookie buffer.
|
||||
// Note that we circumvent the request channel, because we're *in*
|
||||
// the request channel.
|
||||
if len(c.cookieChan) == cookieBuffer-1 {
|
||||
if err := c.noop(); err != nil {
|
||||
// Shut everything down.
|
||||
break
|
||||
}
|
||||
}
|
||||
req.cookie.Sequence = c.newSequenceId()
|
||||
c.cookieChan <- req.cookie
|
||||
c.writeBuffer(req.buf)
|
||||
close(req.seq)
|
||||
}
|
||||
response := make(chan struct{})
|
||||
c.closing <- response
|
||||
c.noop() // Flush the response reading goroutine, ignore error.
|
||||
<-response
|
||||
c.conn.Close()
|
||||
}
|
||||
|
||||
// noop circumvents the usual request sending goroutines and forces a round
|
||||
// trip request manually.
|
||||
func (c *Conn) noop() error {
|
||||
cookie := c.NewCookie(true, true)
|
||||
cookie.Sequence = c.newSequenceId()
|
||||
c.cookieChan <- cookie
|
||||
if err := c.writeBuffer(c.getInputFocusRequest()); err != nil {
|
||||
return err
|
||||
}
|
||||
cookie.Reply() // wait for the buffer to clear
|
||||
return nil
|
||||
}
|
||||
|
||||
// writeBuffer is a convenience function for writing a byte slice to the wire.
|
||||
func (c *Conn) writeBuffer(buf []byte) error {
|
||||
if _, err := c.conn.Write(buf); err != nil {
|
||||
Logger.Printf("A write error is unrecoverable: %s", err)
|
||||
return err
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// readResponses is a goroutine that reads events, errors and
|
||||
// replies off the wire.
|
||||
// When an event is read, it is always added to the event channel.
|
||||
// When an error is read, if it corresponds to an existing checked cookie,
|
||||
// it is sent to that cookie's error channel. Otherwise it is added to the
|
||||
// event channel.
|
||||
// When a reply is read, it is added to the corresponding cookie's reply
|
||||
// channel. (It is an error if no such cookie exists in this case.)
|
||||
// Finally, cookies that came "before" this reply are always cleaned up.
|
||||
func (c *Conn) readResponses() {
|
||||
defer close(c.eventChan)
|
||||
|
||||
var (
|
||||
err Error
|
||||
seq uint16
|
||||
replyBytes []byte
|
||||
)
|
||||
|
||||
for {
|
||||
select {
|
||||
case respond := <-c.closing:
|
||||
respond <- struct{}{}
|
||||
return
|
||||
default:
|
||||
}
|
||||
|
||||
buf := make([]byte, 32)
|
||||
err, seq = nil, 0
|
||||
if _, err := io.ReadFull(c.conn, buf); err != nil {
|
||||
Logger.Printf("A read error is unrecoverable: %s", err)
|
||||
c.eventChan <- err
|
||||
c.Close()
|
||||
continue
|
||||
}
|
||||
switch buf[0] {
|
||||
case 0: // This is an error
|
||||
// Use the constructor function for this error (that is auto
|
||||
// generated) by looking it up by the error number.
|
||||
newErrFun, ok := NewErrorFuncs[int(buf[1])]
|
||||
if !ok {
|
||||
Logger.Printf("BUG: Could not find error constructor function "+
|
||||
"for error with number %d.", buf[1])
|
||||
continue
|
||||
}
|
||||
err = newErrFun(buf)
|
||||
seq = err.SequenceId()
|
||||
|
||||
// This error is either sent to the event channel or a specific
|
||||
// cookie's error channel below.
|
||||
case 1: // This is a reply
|
||||
seq = Get16(buf[2:])
|
||||
|
||||
// check to see if this reply has more bytes to be read
|
||||
size := Get32(buf[4:])
|
||||
if size > 0 {
|
||||
byteCount := 32 + size*4
|
||||
biggerBuf := make([]byte, byteCount)
|
||||
copy(biggerBuf[:32], buf)
|
||||
if _, err := io.ReadFull(c.conn, biggerBuf[32:]); err != nil {
|
||||
Logger.Printf("A read error is unrecoverable: %s", err)
|
||||
c.eventChan <- err
|
||||
c.Close()
|
||||
continue
|
||||
}
|
||||
replyBytes = biggerBuf
|
||||
} else {
|
||||
replyBytes = buf
|
||||
}
|
||||
|
||||
// This reply is sent to its corresponding cookie below.
|
||||
default: // This is an event
|
||||
// Use the constructor function for this event (like for errors,
|
||||
// and is also auto generated) by looking it up by the event number.
|
||||
// Note that we AND the event number with 127 so that we ignore
|
||||
// the most significant bit (which is set when it was sent from
|
||||
// a SendEvent request).
|
||||
evNum := int(buf[0] & 127)
|
||||
newEventFun, ok := NewEventFuncs[evNum]
|
||||
if !ok {
|
||||
Logger.Printf("BUG: Could not find event construct function "+
|
||||
"for event with number %d.", evNum)
|
||||
continue
|
||||
}
|
||||
c.eventChan <- newEventFun(buf)
|
||||
continue
|
||||
}
|
||||
|
||||
// At this point, we have a sequence number and we're either
|
||||
// processing an error or a reply, which are both responses to
|
||||
// requests. So all we have to do is find the cookie corresponding
|
||||
// to this error/reply, and send the appropriate data to it.
|
||||
// In doing so, we make sure that any cookies that came before it
|
||||
// are marked as successful if they are void and checked.
|
||||
// If there's a cookie that requires a reply that is before this
|
||||
// reply, then something is wrong.
|
||||
for cookie := range c.cookieChan {
|
||||
// This is the cookie we're looking for. Process and break.
|
||||
if cookie.Sequence == seq {
|
||||
if err != nil { // this is an error to a request
|
||||
// synchronous processing
|
||||
if cookie.errorChan != nil {
|
||||
cookie.errorChan <- err
|
||||
} else { // asynchronous processing
|
||||
c.eventChan <- err
|
||||
// if this is an unchecked reply, ping the cookie too
|
||||
if cookie.pingChan != nil {
|
||||
cookie.pingChan <- true
|
||||
}
|
||||
}
|
||||
} else { // this is a reply
|
||||
if cookie.replyChan == nil {
|
||||
Logger.Printf("Reply with sequence id %d does not "+
|
||||
"have a cookie with a valid reply channel.", seq)
|
||||
continue
|
||||
} else {
|
||||
cookie.replyChan <- replyBytes
|
||||
}
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
switch {
|
||||
// Checked requests with replies
|
||||
case cookie.replyChan != nil && cookie.errorChan != nil:
|
||||
Logger.Printf("Found cookie with sequence id %d that is "+
|
||||
"expecting a reply but will never get it. Currently "+
|
||||
"on sequence number %d", cookie.Sequence, seq)
|
||||
// Unchecked requests with replies
|
||||
case cookie.replyChan != nil && cookie.pingChan != nil:
|
||||
Logger.Printf("Found cookie with sequence id %d that is "+
|
||||
"expecting a reply (and not an error) but will never "+
|
||||
"get it. Currently on sequence number %d",
|
||||
cookie.Sequence, seq)
|
||||
// Checked requests without replies
|
||||
case cookie.pingChan != nil && cookie.errorChan != nil:
|
||||
cookie.pingChan <- true
|
||||
// Unchecked requests without replies don't have any channels,
|
||||
// so we can't do anything with them except let them pass by.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// processEventOrError takes an eventOrError, type switches on it,
|
||||
// and returns it in Go idiomatic style.
|
||||
func processEventOrError(everr eventOrError) (Event, Error) {
|
||||
switch ee := everr.(type) {
|
||||
case Event:
|
||||
return ee, nil
|
||||
case Error:
|
||||
return nil, ee
|
||||
default:
|
||||
Logger.Printf("Invalid event/error type: %T", everr)
|
||||
return nil, nil
|
||||
}
|
||||
}
|
||||
|
||||
// WaitForEvent returns the next event from the server.
|
||||
// It will block until an event is available.
|
||||
// WaitForEvent returns either an Event or an Error. (Returning both
|
||||
// is a bug.) Note than an Error here is an X error and not an XGB error. That
|
||||
// is, X errors are sometimes completely expected (and you may want to ignore
|
||||
// them in some cases).
|
||||
//
|
||||
// If both the event and error are nil, then the connection has been closed.
|
||||
func (c *Conn) WaitForEvent() (Event, Error) {
|
||||
return processEventOrError(<-c.eventChan)
|
||||
}
|
||||
|
||||
// PollForEvent returns the next event from the server if one is available in
|
||||
// the internal queue without blocking. Note that unlike WaitForEvent, both
|
||||
// Event and Error could be nil. Indeed, they are both nil when the event queue
|
||||
// is empty.
|
||||
func (c *Conn) PollForEvent() (Event, Error) {
|
||||
select {
|
||||
case everr := <-c.eventChan:
|
||||
return processEventOrError(everr)
|
||||
default:
|
||||
return nil, nil
|
||||
}
|
||||
}
|
||||
+14910
File diff suppressed because it is too large.
Load diff
Vendored
+1
-1
Submodule vendor/kryon updated: 4fa7f1f0c4...63e6d98463.
Vendored
+4
@@ -0,0 +1,4 @@
|
||||
# github.com/BurntSushi/xgb v0.0.0-20210121224620-deaf085860bc
|
||||
## explicit; go 1.16
|
||||
github.com/BurntSushi/xgb
|
||||
github.com/BurntSushi/xgb/xproto
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package gopass
|
||||
|
||||
// Version is the current application version.
|
||||
const Version = "0.1.2"
|
||||
const Version = "0.2.0"
|
||||
@@ -9,6 +9,7 @@ rm -rf "$out_dir"
|
||||
mkdir -p "$out_dir/app"
|
||||
cp "$root_dir/web/site/index.html" "$out_dir/index.html"
|
||||
cp "$root_dir/web/site/styles.css" "$out_dir/styles.css"
|
||||
cp "$root_dir/web/site/home.js" "$out_dir/home.js"
|
||||
cp "$root_dir/web/site/app/index.html" "$out_dir/app/index.html"
|
||||
cp "$root_dir/web/site/app/app.js" "$out_dir/app/app.js"
|
||||
cp "$root_dir/web/site/CNAME" "$out_dir/CNAME"
|
||||
@@ -24,4 +25,5 @@ cp "$goroot/lib/wasm/wasm_exec.js" "$out_dir/app/wasm_exec.js" 2>/dev/null || \
|
||||
(cd "$root_dir/web/wasm" && GOOS=js GOARCH=wasm go build -o "$out_dir/app/gopass.wasm" .)
|
||||
|
||||
test -s "$out_dir/app/gopass.wasm"
|
||||
test -s "$out_dir/home.js"
|
||||
printf 'built site at %s\n' "$out_dir"
|
||||
@@ -0,0 +1,33 @@
|
||||
(() => {
|
||||
const byId = id => document.getElementById(id);
|
||||
const card = byId('generator');
|
||||
const generate = byId('generate'), copy = byId('copy'), result = byId('result'), message = byId('message');
|
||||
let copied = '', clearTimer = 0, started = false, ready = false, pending = false;
|
||||
|
||||
function runGenerate() {
|
||||
const response = window.gopassGenerate(byId('site').value, byId('login').value, byId('master').value, Number(byId('length').value), Number(byId('counter').value), byId('lower').checked, byId('upper').checked, byId('digits').checked, byId('symbols').checked, byId('exclude').value);
|
||||
if (response.error) { result.textContent = 'Unable to generate'; message.textContent = response.error; copy.disabled = true; return; }
|
||||
result.textContent = response.password; message.textContent = 'Generated locally in this tab'; copy.disabled = false;
|
||||
}
|
||||
|
||||
function startLoad() {
|
||||
if (started) return;
|
||||
started = true;
|
||||
const script = document.createElement('script');
|
||||
script.src = '/app/wasm_exec.js';
|
||||
script.onload = () => {
|
||||
const go = new Go();
|
||||
WebAssembly.instantiateStreaming(fetch('/app/gopass.wasm'), go.importObject).then(instance => go.run(instance.instance)).catch(error => { message.textContent = 'Generator failed to load'; generate.textContent = error; });
|
||||
};
|
||||
script.onerror = () => { message.textContent = 'Generator failed to load'; };
|
||||
document.head.appendChild(script);
|
||||
}
|
||||
|
||||
['focusin', 'input', 'click'].forEach(type => card.addEventListener(type, startLoad, {passive: true, capture: true}));
|
||||
document.addEventListener('gopass-ready', () => { ready = true; generate.disabled = false; if (pending) { pending = false; runGenerate(); } });
|
||||
|
||||
byId('reveal').addEventListener('click', () => { const master = byId('master'); master.type = master.type === 'password' ? 'text' : 'password'; byId('reveal').textContent = master.type === 'password' ? 'Reveal' : 'Hide'; });
|
||||
generate.addEventListener('click', () => { if (!ready) { pending = true; message.textContent = 'Loading secure generator…'; return; } runGenerate(); });
|
||||
copy.addEventListener('click', async () => { await navigator.clipboard.writeText(result.textContent); copied = result.textContent; message.textContent = 'Copied; clipboard clears in 20 seconds'; clearTimeout(clearTimer); clearTimer = setTimeout(async () => { try { const current = await navigator.clipboard.readText(); if (current === copied) await navigator.clipboard.writeText(''); } catch (_) {} copied = ''; }, 20000); });
|
||||
byId('clear').addEventListener('click', () => { ['site','login','master','exclude'].forEach(id => byId(id).value = ''); result.textContent = 'Your generated password appears here'; message.textContent = 'Cleared'; copy.disabled = true; byId('site').focus(); });
|
||||
})();
|
||||
+11
-3
@@ -17,15 +17,23 @@
|
||||
<main>
|
||||
<section class="hero">
|
||||
<div><p class="eyebrow">Stateless · local · open source</p><img class="hero-icon" src="/icons/icon-192.png" alt="gopass"><h1>One master password.<br><span>Every site covered.</span></h1><p class="lede">gopass derives strong, repeatable passwords on your device. Nothing is stored, uploaded, or tracked.</p><div class="actions"><a class="button primary" href="/app/">Run Web</a><a class="button" href="#downloads">Download apps</a></div></div>
|
||||
<div class="preview"><div class="preview-head"><i></i><i></i><i></i><span>generated locally</span></div><div class="preview-body"><label>Site</label><div class="fake-input">example.org</div><label>Generated password</label><div class="password">••••••••••••••••</div><div class="privacy-line">No network requests. No password database.</div></div></div>
|
||||
<div class="preview" id="generator"><div class="preview-head"><i></i><i></i><i></i><span>generated locally</span></div><div class="preview-body"><div class="form-grid">
|
||||
<label>Site<input id="site" autocomplete="off" placeholder="example.org"></label><label>Login<input id="login" autocomplete="username" placeholder="[email protected]"></label>
|
||||
<label class="wide">Master password<span class="password-wrap"><input id="master" type="password" autocomplete="current-password"><button id="reveal" type="button" class="inline">Reveal</button></span></label>
|
||||
<label>Length<input id="length" type="number" min="1" max="128" value="16"></label><label>Counter<input id="counter" type="number" min="1" value="1"></label><label class="wide">Excluded characters<input id="exclude" autocomplete="off"></label>
|
||||
<fieldset class="wide"><legend>Character classes</legend><label><input id="lower" type="checkbox" checked> Lowercase</label><label><input id="upper" type="checkbox" checked> Uppercase</label><label><input id="digits" type="checkbox" checked> Digits</label><label><input id="symbols" type="checkbox" checked> Symbols</label></fieldset>
|
||||
<div class="wide actions"><button id="generate" class="button" disabled>Generate</button><button id="copy" class="button secondary" disabled>Copy</button><button id="clear" class="button ghost">Clear</button></div>
|
||||
<output id="result" class="wide" aria-live="polite">Your generated password appears here</output><p id="message" class="wide status"></p>
|
||||
</div><div class="privacy-line">No network requests. No password database.</div></div></div>
|
||||
</section>
|
||||
<section id="downloads"><p class="eyebrow">DOWNLOADS</p><h2>Choose your interface</h2><div class="cards">
|
||||
<article><span class="tag">DESKTOP</span><h3>Kryon GUI</h3><p>Visual controls, secure masked input, and clipboard clearing.</p><div class="links"><a href="/downloads/gopass-gui-linux-amd64.tar.gz">Linux x86_64</a><a href="/downloads/gopass-gui-linux-arm64.tar.gz">Linux ARM64</a></div></article>
|
||||
<article><span class="tag">DESKTOP</span><h3>GUI</h3><p>Visual controls, secure masked input, and clipboard clearing.</p><div class="links"><a href="/downloads/gopass-gui-linux-amd64.tar.gz">Linux x86_64</a><a href="/downloads/gopass-gui-linux-arm64.tar.gz">Linux ARM64</a></div></article>
|
||||
<article><span class="tag">TERMINAL</span><h3>CLI</h3><p>Small, scriptable binaries for servers and workstations.</p><div class="links"><a href="/downloads/gopass-cli-linux-amd64.tar.gz">Linux</a><a href="/downloads/gopass-cli-darwin-arm64.tar.gz">macOS</a><a href="/downloads/gopass-cli-windows-amd64.zip">Windows</a></div></article>
|
||||
<article><span class="tag">BROWSER</span><h3>Web app</h3><p>The same Go generator compiled to WebAssembly. Runs entirely in your tab.</p><div class="links"><a href="/app/">Open web app</a></div></article>
|
||||
</div></section>
|
||||
<section class="privacy" id="privacy"><p class="eyebrow">PRIVACY</p><h2>Your master password stays yours.</h2><p>The desktop and browser apps derive passwords locally. The website has no analytics, accounts, cookies, or backend API. Source and releases remain available under BSD-3-Clause.</p></section>
|
||||
</main>
|
||||
<footer><span>© 2026 Waozi</span><a href="https://waozi.xyz">waozi.xyz</a></footer>
|
||||
<footer><span>© 2026 <a href="https://waozi.xyz">Waozi</a></span></footer>
|
||||
<script src="home.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
+3
-2
@@ -1,5 +1,6 @@
|
||||
:root{--bg:#f3f1ea;--surface:#fdfcf8;--control:#eae6da;--control-hi:#fff;--ink:#2a3b40;--muted:#5d6f74;--line:rgba(42,59,64,.20);--line-strong:rgba(42,59,64,.30);--accent:#65558f;--accent-deep:#433668;--accent-soft:rgba(101,85,143,.10);--card:#f7f4ec;--radius:10px;--radius-sm:6px;--maxw:1080px;--font:ui-monospace,"SFMono-Regular",Menlo,Consolas,monospace;--bevel:0 1px 0 var(--control-hi),inset 1px 1px 0 var(--control-hi),0 2px 10px rgba(0,0,0,.04)}
|
||||
*{box-sizing:border-box}html{scroll-behavior:smooth;scroll-padding-top:72px}body{margin:0;min-height:100vh;background:var(--bg);color:var(--ink);font:15px/1.6 var(--font);-webkit-font-smoothing:antialiased}body:before{content:"";position:fixed;inset:0;z-index:-1;background-image:linear-gradient(45deg,rgba(42,59,64,.028) 25%,transparent 25%),linear-gradient(-45deg,rgba(42,59,64,.028) 25%,transparent 25%),linear-gradient(45deg,transparent 75%,rgba(42,59,64,.028) 75%),linear-gradient(-45deg,transparent 75%,rgba(42,59,64,.028) 75%);background-position:0 0,0 16px,16px -16px,-16px 0;background-size:32px 32px;opacity:.18}a{color:var(--accent);font-weight:700;text-decoration:none}a:hover{color:var(--accent-deep)}a:active,.button:active{position:relative;top:1px;left:1px}.site-header{position:sticky;top:0;z-index:50;background:rgba(243,241,234,.92);backdrop-filter:blur(8px);border-bottom:1px solid var(--line)}.site-header-inner{max-width:var(--maxw);margin:auto;padding:10px 20px;display:flex;align-items:center;gap:16px}.brand{display:flex;align-items:center;gap:8px;color:var(--ink);font-size:15px;letter-spacing:.04em}.brand img{width:22px;height:22px;border-radius:5px;image-rendering:pixelated}.header-nav{display:flex;align-items:center;gap:18px;margin-left:auto}.header-nav>a,.header-nav span{color:var(--muted);font-size:13px}.header-nav .button{color:#fffdf8}.button,button.button{display:inline-flex;align-items:center;justify-content:center;gap:6px;padding:8px 14px;border:1px solid var(--line);border-radius:var(--radius-sm);background:var(--control);box-shadow:var(--bevel);color:var(--ink);font:700 13px var(--font);cursor:pointer}.button:hover{background:var(--surface);color:var(--accent)}.button.primary,.header-nav .button{background:var(--accent);border-color:var(--accent-deep);color:#fff}.button.secondary{background:var(--control)}.button.ghost{background:transparent}.button.small{padding:7px 12px}button:disabled{opacity:.45;cursor:not-allowed}
|
||||
.hero{max-width:var(--maxw);min-height:calc(100vh - 64px);margin:auto;padding:48px 20px 40px;display:grid;grid-template-columns:minmax(0,.9fr) minmax(360px,.8fr);gap:44px;align-items:center}.hero-icon{width:96px;height:96px;margin:4px 0 0;border:1px solid var(--line-strong);border-radius:8px;box-shadow:var(--bevel);image-rendering:pixelated}.eyebrow{display:flex;align-items:center;gap:8px;margin:0 0 12px;color:var(--accent);font-size:13px;font-weight:700;letter-spacing:.04em;text-transform:uppercase}.eyebrow:before{content:"";width:8px;height:8px;background:var(--accent);border:1px solid var(--accent-deep);border-radius:2px;box-shadow:1px 1px 0 rgba(0,0,0,.12)}h1,h2,h3{margin:0;color:var(--ink);line-height:1.15}h1{margin:14px 0 16px;font-size:clamp(42px,7vw,74px);line-height:.98}h1 span{color:var(--accent)}h2{margin-bottom:16px;font-size:clamp(26px,4vw,40px)}h3{font-size:16px}.lede{max-width:700px;color:var(--muted);font-size:17px}.actions{display:flex;flex-wrap:wrap;gap:12px;margin-top:24px}.preview,.generator-card{overflow:hidden;background:var(--surface);border:1px solid var(--line-strong);border-radius:var(--radius);box-shadow:0 1px 0 var(--control-hi),inset 1px 1px 0 var(--control-hi),0 18px 46px rgba(0,0,0,.10)}.preview-head{display:flex;align-items:center;gap:8px;padding:10px 12px;background:var(--control);border-bottom:1px solid var(--line)}.preview-head i{width:10px;height:10px;background:var(--accent);border:1px solid var(--accent-deep);border-radius:3px}.preview-head span{margin-left:6px;color:var(--muted);font-size:12px}.preview-body{padding:16px}.preview label,.generator-card>label{display:block;margin:12px 0 6px;color:var(--muted);font-size:13px}.fake-input,.password,output{padding:12px;background:var(--card);border:1px solid var(--line);border-radius:var(--radius-sm);box-shadow:var(--bevel)}.password{color:var(--accent);font-size:18px;letter-spacing:.12em}.privacy-line{margin-top:16px;color:var(--muted);font-size:12px}
|
||||
.hero{max-width:var(--maxw);min-height:calc(100vh - 64px);margin:auto;padding:48px 20px 40px;display:grid;grid-template-columns:minmax(0,.9fr) minmax(360px,.8fr);gap:44px;align-items:center}.hero-icon{width:96px;height:96px;margin:4px 0 0;border:1px solid var(--line-strong);border-radius:8px;box-shadow:var(--bevel);image-rendering:pixelated}.eyebrow{display:flex;align-items:center;gap:8px;margin:0 0 12px;color:var(--accent);font-size:13px;font-weight:700;letter-spacing:.04em;text-transform:uppercase}.eyebrow:before{content:"";width:8px;height:8px;background:var(--accent);border:1px solid var(--accent-deep);border-radius:2px;box-shadow:1px 1px 0 rgba(0,0,0,.12)}h1,h2,h3{margin:0;color:var(--ink);line-height:1.15}h1{margin:14px 0 16px;font-size:clamp(42px,7vw,74px);line-height:.98}h1 span{color:var(--accent)}h2{margin-bottom:16px;font-size:clamp(26px,4vw,40px)}h3{font-size:16px}.lede{max-width:700px;color:var(--muted);font-size:17px}.actions{display:flex;flex-wrap:wrap;gap:12px;margin-top:24px}.preview,.generator-card{overflow:hidden;background:var(--surface);border:1px solid var(--line-strong);border-radius:var(--radius);box-shadow:0 1px 0 var(--control-hi),inset 1px 1px 0 var(--control-hi),0 18px 46px rgba(0,0,0,.10)}.preview-head{display:flex;align-items:center;gap:8px;padding:10px 12px;background:var(--control);border-bottom:1px solid var(--line)}.preview-head i{width:10px;height:10px;background:var(--accent);border:1px solid var(--accent-deep);border-radius:3px}.preview-head span{margin-left:6px;color:var(--muted);font-size:12px}.preview-body{padding:16px}.generator-card>label{display:block;margin:12px 0 6px;color:var(--muted);font-size:13px}output{padding:12px;background:var(--card);border:1px solid var(--line);border-radius:var(--radius-sm);box-shadow:var(--bevel)}.privacy-line{margin-top:16px;color:var(--muted);font-size:12px}
|
||||
main>section:not(.hero){max-width:var(--maxw);margin:0 auto;padding:56px 20px}.cards{display:grid;grid-template-columns:repeat(3,1fr);gap:14px}.cards article,.privacy{padding:16px;background:var(--card);border:1px solid var(--line);border-radius:var(--radius-sm);box-shadow:var(--bevel)}.cards h3{margin:8px 0}.cards p,.privacy p{color:var(--muted);font-size:14px}.tag{color:var(--accent);font-size:12px;font-weight:700}.links{display:flex;flex-wrap:wrap;gap:12px;margin-top:18px}footer{max-width:var(--maxw);margin:auto;padding:16px 20px 28px;text-align:center;color:var(--muted);font-size:13px}.generator-shell{max-width:820px;margin:48px auto;padding:0 20px}.generator-card{padding:24px}.generator-card h1{font-size:clamp(34px,6vw,52px)}.form-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:18px}.form-grid label,fieldset legend{color:var(--muted);font-size:13px}.form-grid input:not([type=checkbox]){display:block;width:100%;margin-top:7px;padding:11px 12px;background:var(--card);border:1px solid var(--line);border-radius:var(--radius-sm);color:var(--ink);font:inherit;outline:none}.form-grid input:focus{border-color:var(--accent)}.wide{grid-column:1/-1}.password-wrap{display:flex;gap:8px}.password-wrap input{flex:1}.inline{margin-top:7px;border:1px solid var(--line);background:var(--control);border-radius:var(--radius-sm);color:var(--ink);font:inherit;padding:0 12px}fieldset{display:flex;gap:20px;border:0;padding:0}fieldset legend{margin-bottom:10px}fieldset label{color:var(--ink)!important}output{display:block;min-height:68px;font-size:17px;overflow-wrap:anywhere}.status{min-height:20px;margin:0;color:var(--muted)}#runtime-status{font-size:12px}
|
||||
@media(max-width:760px){.header-nav>a:not(.button){display:none}.hero{grid-template-columns:1fr;min-height:0;gap:36px}.cards{grid-template-columns:1fr}.form-grid{grid-template-columns:1fr 1fr}}@media(max-width:520px){.site-header-inner{padding:10px 14px}.hero,.generator-shell{padding-left:14px;padding-right:14px}.form-grid{grid-template-columns:1fr}.wide{grid-column:1}fieldset{display:grid;grid-template-columns:1fr 1fr}.actions .button{flex:1}.generator-card{padding:18px}}
|
||||
.preview .form-grid{grid-template-columns:1fr 1fr;gap:14px}.preview fieldset{display:grid;grid-template-columns:1fr 1fr;gap:8px 16px}.preview fieldset legend{grid-column:1/-1;margin-bottom:2px}.preview .actions{margin-top:0;gap:10px}.preview .actions .button{flex:1}.preview output{min-height:52px;font-size:15px}
|
||||
@media(max-width:760px){.header-nav>a:not(.button){display:none}.hero{grid-template-columns:1fr;min-height:0;gap:36px}.cards{grid-template-columns:1fr}.form-grid{grid-template-columns:1fr 1fr}}@media(max-width:520px){.site-header-inner{padding:10px 14px}.hero,.generator-shell{padding-left:14px;padding-right:14px}.form-grid,.preview .form-grid{grid-template-columns:1fr}.wide{grid-column:1}fieldset{display:grid;grid-template-columns:1fr 1fr}.actions .button{flex:1}.generator-card{padding:18px}}
|
||||
Reference in new issue
Block a user