Merge branch 'e2ee'

This commit is contained in:
Tulir Asokan 2020-05-06 20:06:35 +03:00
commit 5b3e91524e
17 changed files with 472 additions and 187 deletions

View File

@ -7,3 +7,6 @@ end_of_line = lf
charset = utf-8 charset = utf-8
trim_trailing_whitespace = true trim_trailing_whitespace = true
insert_final_newline = true insert_final_newline = true
[.gitlab-ci.yml]
indent_size = 2

View File

@ -1,65 +1,41 @@
image: golang:alpine build:
variables:
CGO_ENABLED: "0"
stages:
- modules
- build
cache:
paths:
- .cache
default:
before_script:
- apk add git
- mkdir -p .cache
- export GOPATH="$CI_PROJECT_DIR/.cache"
modules:
stage: modules
script:
- go get
.build: &build
stage: build stage: build
image: debian:bullseye
cache: cache:
paths: paths:
- .cache - .cache
before_script:
- apt-get update
- apt-get install -y git libolm-dev golang-go
- mkdir -p .cache
- export GOPATH="$CI_PROJECT_DIR/.cache"
script: script:
- echo "Building... $GOPATH $CGO_ENABLED $GOOS $GOARCH" - go build -o gomuks_linux_amd64
- go build -o gomuks
artifacts: artifacts:
paths: paths:
- gomuks - gomuks_linux_amd64
build_linux_amd64: build_static:
<<: *build stage: build
image: golang:alpine
cache:
paths:
- .cache
before_script:
- mkdir -p .cache
- export GOPATH="$CI_PROJECT_DIR/.cache"
variables: variables:
GOOS: linux CGO_ENABLED: "0"
GOARCH: amd64 script:
- GOOS=linux GOARCH=amd64 go build -o gomuks_linux_amd64
build_linux_386: - GOOS=linux GOARCH=386 go build -o gomuks_linux_386
<<: *build - GOOS=linux GOARCH=arm go build -o gomuks_linux_arm
variables: - GOOS=linux GOARCH=arm64 go build -o gomuks_linux_arm64
GOOS: linux - GOOS=darwin GOARCH=amd64 go build -o gomuks_darwin_amd64
GOARCH: "386" artifacts:
paths:
build_linux_arm: - gomuks_linux_amd64
<<: *build - gomuks_linux_386
variables: - gomuks_linux_arm
GOOS: linux - gomuks_linux_arm64
GOARCH: arm - gomuks_darwin_amd64
build_linux_arm64:
<<: *build
variables:
GOOS: linux
GOARCH: arm64
build_darwin_amd64:
<<: *build
variables:
GOOS: darwin
GOARCH: amd64

View File

@ -54,9 +54,10 @@ type UserPreferences struct {
// Config contains the main config of gomuks. // Config contains the main config of gomuks.
type Config struct { type Config struct {
UserID id.UserID `yaml:"mxid"` UserID id.UserID `yaml:"mxid"`
AccessToken string `yaml:"access_token"` DeviceID id.DeviceID `yaml:"device_id"`
HS string `yaml:"homeserver"` AccessToken string `yaml:"access_token"`
HS string `yaml:"homeserver"`
RoomCacheSize int `yaml:"room_cache_size"` RoomCacheSize int `yaml:"room_cache_size"`
RoomCacheAge int64 `yaml:"room_cache_age"` RoomCacheAge int64 `yaml:"room_cache_age"`
@ -64,6 +65,7 @@ type Config struct {
NotifySound bool `yaml:"notify_sound"` NotifySound bool `yaml:"notify_sound"`
Dir string `yaml:"-"` Dir string `yaml:"-"`
DataDir string `yaml:"data_dir"`
CacheDir string `yaml:"cache_dir"` CacheDir string `yaml:"cache_dir"`
HistoryPath string `yaml:"history_path"` HistoryPath string `yaml:"history_path"`
RoomListPath string `yaml:"room_list_path"` RoomListPath string `yaml:"room_list_path"`
@ -80,9 +82,10 @@ type Config struct {
} }
// NewConfig creates a config that loads data from the given directory. // NewConfig creates a config that loads data from the given directory.
func NewConfig(configDir, cacheDir, downloadDir string) *Config { func NewConfig(configDir, dataDir, cacheDir, downloadDir string) *Config {
return &Config{ return &Config{
Dir: configDir, Dir: configDir,
DataDir: dataDir,
CacheDir: cacheDir, CacheDir: cacheDir,
DownloadDir: downloadDir, DownloadDir: downloadDir,
HistoryPath: filepath.Join(cacheDir, "history.db"), HistoryPath: filepath.Join(cacheDir, "history.db"),
@ -107,8 +110,14 @@ func (config *Config) Clear() {
config.nosave = true config.nosave = true
} }
// ClearData clears non-temporary session data.
func (config *Config) ClearData() {
_ = os.RemoveAll(config.DataDir)
}
func (config *Config) CreateCacheDirs() { func (config *Config) CreateCacheDirs() {
_ = os.MkdirAll(config.CacheDir, 0700) _ = os.MkdirAll(config.CacheDir, 0700)
_ = os.MkdirAll(config.DataDir, 0700)
_ = os.MkdirAll(config.StateDir, 0700) _ = os.MkdirAll(config.StateDir, 0700)
_ = os.MkdirAll(config.MediaDir, 0700) _ = os.MkdirAll(config.MediaDir, 0700)
} }
@ -117,9 +126,11 @@ func (config *Config) DeleteSession() {
config.AuthCache.NextBatch = "" config.AuthCache.NextBatch = ""
config.AuthCache.InitialSyncDone = false config.AuthCache.InitialSyncDone = false
config.AccessToken = "" config.AccessToken = ""
config.DeviceID = ""
config.Rooms = rooms.NewRoomCache(config.RoomListPath, config.StateDir, config.RoomCacheSize, config.RoomCacheAge, config.GetUserID) config.Rooms = rooms.NewRoomCache(config.RoomListPath, config.StateDir, config.RoomCacheSize, config.RoomCacheAge, config.GetUserID)
config.PushRules = nil config.PushRules = nil
config.ClearData()
config.Clear() config.Clear()
config.nosave = false config.nosave = false
config.CreateCacheDirs() config.CreateCacheDirs()

18
go.mod
View File

@ -3,12 +3,12 @@ module maunium.net/go/gomuks
go 1.14 go 1.14
require ( require (
github.com/alecthomas/chroma v0.7.1 github.com/alecthomas/chroma v0.7.2
github.com/disintegration/imaging v1.6.2 github.com/disintegration/imaging v1.6.2
github.com/kyokomi/emoji v2.1.0+incompatible github.com/kyokomi/emoji v2.2.2+incompatible
github.com/lithammer/fuzzysearch v1.1.0 github.com/lithammer/fuzzysearch v1.1.0
github.com/lucasb-eyer/go-colorful v1.0.3 github.com/lucasb-eyer/go-colorful v1.0.3
github.com/mattn/go-runewidth v0.0.8 github.com/mattn/go-runewidth v0.0.9
github.com/petermattis/goid v0.0.0-20180202154549-b0b1615b78e5 // indirect github.com/petermattis/goid v0.0.0-20180202154549-b0b1615b78e5 // indirect
github.com/pkg/errors v0.9.1 github.com/pkg/errors v0.9.1
github.com/rivo/uniseg v0.1.0 github.com/rivo/uniseg v0.1.0
@ -16,12 +16,12 @@ require (
github.com/sasha-s/go-deadlock v0.2.0 github.com/sasha-s/go-deadlock v0.2.0
github.com/shurcooL/sanitized_anchor_name v1.0.0 // indirect github.com/shurcooL/sanitized_anchor_name v1.0.0 // indirect
github.com/stretchr/testify v1.5.1 github.com/stretchr/testify v1.5.1
go.etcd.io/bbolt v1.3.3 go.etcd.io/bbolt v1.3.4
golang.org/x/image v0.0.0-20200119044424-58c23975cae1 golang.org/x/image v0.0.0-20200430140353-33d19683fad8
golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e golang.org/x/net v0.0.0-20200505041828-1ed23360d12c
gopkg.in/toast.v1 v1.0.0-20180812000517-0a84660828b2 gopkg.in/toast.v1 v1.0.0-20180812000517-0a84660828b2
gopkg.in/yaml.v2 v2.2.8 gopkg.in/yaml.v2 v2.2.8
maunium.net/go/mautrix v0.2.0-beta.4 maunium.net/go/mautrix v0.3.1
maunium.net/go/mauview v0.1.0 maunium.net/go/mauview v0.1.1
maunium.net/go/tcell v0.1.0 maunium.net/go/tcell v0.2.0
) )

50
go.sum
View File

@ -1,6 +1,6 @@
github.com/alecthomas/assert v0.0.0-20170929043011-405dbfeb8e38/go.mod h1:r7bzyVFMNntcxPZXK3/+KdruV1H5KSlyVY0gc+NgInI= github.com/alecthomas/assert v0.0.0-20170929043011-405dbfeb8e38/go.mod h1:r7bzyVFMNntcxPZXK3/+KdruV1H5KSlyVY0gc+NgInI=
github.com/alecthomas/chroma v0.7.1 h1:G1i02OhUbRi2nJxcNkwJaY/J1gHXj9tt72qN6ZouLFQ= github.com/alecthomas/chroma v0.7.2 h1:B76NU/zbQYIUhUowbi4fmvREmDUJLsUzKWTZmQd3ABY=
github.com/alecthomas/chroma v0.7.1/go.mod h1:gHw09mkX1Qp80JlYbmN9L3+4R5o6DJJ3GRShh+AICNc= github.com/alecthomas/chroma v0.7.2/go.mod h1:fv5SzZPFJbwp2NXJWpFIX7DZS4HgV1K4ew4Pc2OZD9s=
github.com/alecthomas/colour v0.0.0-20160524082231-60882d9e2721/go.mod h1:QO9JBoKquHd+jz9nshCh40fOfO+JzsoXy8qTHF68zU0= github.com/alecthomas/colour v0.0.0-20160524082231-60882d9e2721/go.mod h1:QO9JBoKquHd+jz9nshCh40fOfO+JzsoXy8qTHF68zU0=
github.com/alecthomas/kong v0.2.1-0.20190708041108-0548c6b1afae/go.mod h1:+inYUSluD+p4L8KdviBSgzcqEjUQOfC5fQDRFuc36lI= github.com/alecthomas/kong v0.2.1-0.20190708041108-0548c6b1afae/go.mod h1:+inYUSluD+p4L8KdviBSgzcqEjUQOfC5fQDRFuc36lI=
github.com/alecthomas/repr v0.0.0-20180818092828-117648cd9897/go.mod h1:xTS7Pm1pD1mvyM075QCDSRqH6qRLXylzS24ZTpRiSzQ= github.com/alecthomas/repr v0.0.0-20180818092828-117648cd9897/go.mod h1:xTS7Pm1pD1mvyM075QCDSRqH6qRLXylzS24ZTpRiSzQ=
@ -16,8 +16,9 @@ github.com/fatih/structs v1.1.0 h1:Q7juDM0QtcnhCpeyLGQKyg4TOIghuNXrkL32pHAUMxo=
github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M= github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M=
github.com/gdamore/encoding v1.0.0 h1:+7OoQ1Bc6eTm5niUzBa0Ctsh6JbMW6Ra+YNuAtDBdko= github.com/gdamore/encoding v1.0.0 h1:+7OoQ1Bc6eTm5niUzBa0Ctsh6JbMW6Ra+YNuAtDBdko=
github.com/gdamore/encoding v1.0.0/go.mod h1:alR0ol34c49FCSBLjhosxzcPHQbf2trDkoo5dl+VrEg= github.com/gdamore/encoding v1.0.0/go.mod h1:alR0ol34c49FCSBLjhosxzcPHQbf2trDkoo5dl+VrEg=
github.com/kyokomi/emoji v2.1.0+incompatible h1:+DYU2RgpI6OHG4oQkM5KlqD3Wd3UPEsX8jamTo1Mp6o= github.com/kyokomi/emoji v1.5.1 h1:qp9dub1mW7C4MlvoRENH6EAENb9skEFOvIEbp1Waj38=
github.com/kyokomi/emoji v2.1.0+incompatible/go.mod h1:mZ6aGCD7yk8j6QY6KICwnZ2pxoszVseX1DNoGtU2tBA= github.com/kyokomi/emoji v2.2.2+incompatible h1:gaQFbK2+uSxOR4iGZprJAbpmtqTrHhSdgOyIMD6Oidc=
github.com/kyokomi/emoji v2.2.2+incompatible/go.mod h1:mZ6aGCD7yk8j6QY6KICwnZ2pxoszVseX1DNoGtU2tBA=
github.com/lithammer/fuzzysearch v1.1.0 h1:go9v8tLCrNTTlH42OAaq4eHFe81TDHEnlrMEb6R4f+A= github.com/lithammer/fuzzysearch v1.1.0 h1:go9v8tLCrNTTlH42OAaq4eHFe81TDHEnlrMEb6R4f+A=
github.com/lithammer/fuzzysearch v1.1.0/go.mod h1:Bqx4wo8lTOFcJr3ckpY6HA9lEIOO0H5HrkJ5CsN56HQ= github.com/lithammer/fuzzysearch v1.1.0/go.mod h1:Bqx4wo8lTOFcJr3ckpY6HA9lEIOO0H5HrkJ5CsN56HQ=
github.com/lucasb-eyer/go-colorful v1.0.3 h1:QIbQXiugsb+q10B+MI+7DI1oQLdmnep86tWFlaaUAac= github.com/lucasb-eyer/go-colorful v1.0.3 h1:QIbQXiugsb+q10B+MI+7DI1oQLdmnep86tWFlaaUAac=
@ -25,8 +26,9 @@ github.com/lucasb-eyer/go-colorful v1.0.3/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i
github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU=
github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4=
github.com/mattn/go-runewidth v0.0.7/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= github.com/mattn/go-runewidth v0.0.7/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
github.com/mattn/go-runewidth v0.0.8 h1:3tS41NlGYSmhhe/8fhGRzc+z3AYCw1Fe1WAyLuujKs0=
github.com/mattn/go-runewidth v0.0.8/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= github.com/mattn/go-runewidth v0.0.8/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0=
github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
github.com/petermattis/goid v0.0.0-20180202154549-b0b1615b78e5 h1:q2e307iGHPdTGp0hoxKjt1H5pDo6utceo3dQVK3I5XQ= github.com/petermattis/goid v0.0.0-20180202154549-b0b1615b78e5 h1:q2e307iGHPdTGp0hoxKjt1H5pDo6utceo3dQVK3I5XQ=
github.com/petermattis/goid v0.0.0-20180202154549-b0b1615b78e5/go.mod h1:jvVRKCrJTQWu0XVbaOlby/2lO20uSCHEMzzplHXte1o= github.com/petermattis/goid v0.0.0-20180202154549-b0b1615b78e5/go.mod h1:jvVRKCrJTQWu0XVbaOlby/2lO20uSCHEMzzplHXte1o=
@ -47,23 +49,37 @@ github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/tidwall/gjson v1.6.0 h1:9VEQWz6LLMUsUl6PueE49ir4Ka6CzLymOAZDxpFsTDc=
github.com/tidwall/gjson v1.6.0/go.mod h1:P256ACg0Mn+j1RXIDXoss50DeIABTYK1PULOJHhxOls=
github.com/tidwall/match v1.0.1 h1:PnKP62LPNxHKTwvHHZZzdOAOCtsJTjo6dZLCwpKm5xc=
github.com/tidwall/match v1.0.1/go.mod h1:LujAq0jyVjBy028G1WhWfIzbpQfMO8bBZ6Tyb0+pL9E=
github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk=
github.com/tidwall/pretty v1.0.1 h1:WE4RBSZ1x6McVVC8S/Md+Qse8YUv6HRObAx6ke00NY8=
github.com/tidwall/pretty v1.0.1/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk=
github.com/tidwall/sjson v1.1.1 h1:7h1vk049Jnd5EH9NyzNiEuwYW4b5qgreBbqRC19AS3U=
github.com/tidwall/sjson v1.1.1/go.mod h1:yvVuSnpEQv5cYIrO+AT6kw4QVfd5SDZoGIS7/5+fZFs=
github.com/zyedidia/clipboard v0.0.0-20190823154308-241f98e9b197 h1:gYTNnAW6azuB3BbA6QYWO/H4F2ABSOjjw3Z03tlXd2c= github.com/zyedidia/clipboard v0.0.0-20190823154308-241f98e9b197 h1:gYTNnAW6azuB3BbA6QYWO/H4F2ABSOjjw3Z03tlXd2c=
github.com/zyedidia/clipboard v0.0.0-20190823154308-241f98e9b197/go.mod h1:WDk3p8GiZV9+xFWlSo8qreeoLhW6Ik692rqXk+cNeRY= github.com/zyedidia/clipboard v0.0.0-20190823154308-241f98e9b197/go.mod h1:WDk3p8GiZV9+xFWlSo8qreeoLhW6Ik692rqXk+cNeRY=
github.com/zyedidia/clipboard v0.0.0-20200421031010-7c45b8673834 h1:0nOfq3JwYRiY3+nwfWVQYEaXDmGCQgj3RKoqTifLzP4=
github.com/zyedidia/clipboard v0.0.0-20200421031010-7c45b8673834/go.mod h1:zykFnZUXX0ErxqvYLUFEq7QDJKId8rmh2FgD0/Y8cjA=
github.com/zyedidia/poller v1.0.1/go.mod h1:vZXJOHGDcuK08GXhF6IAY0ZFd2WcgOR5DOTp84Uk5eE= github.com/zyedidia/poller v1.0.1/go.mod h1:vZXJOHGDcuK08GXhF6IAY0ZFd2WcgOR5DOTp84Uk5eE=
go.etcd.io/bbolt v1.3.3 h1:MUGmc65QhB3pIlaQ5bB4LwqSj6GIonVJXpZiaKNyaKk= go.etcd.io/bbolt v1.3.4 h1:hi1bXHMVrlQh6WwxAy+qZCV/SYIlqo+Ushwdpa4tAKg=
go.etcd.io/bbolt v1.3.3/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= go.etcd.io/bbolt v1.3.4/go.mod h1:G5EMThwa9y8QZGBClrRx5EY+Yw9kAhnjy3bSjsnlVTQ=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/image v0.0.0-20200119044424-58c23975cae1 h1:5h3ngYt7+vXCDZCup/HkCQgW5XwmSvR/nA2JmJ0RErg= golang.org/x/image v0.0.0-20200430140353-33d19683fad8 h1:6WW6V3x1P/jokJBpRQYUJnMHRP6isStQwCozxnU7XQw=
golang.org/x/image v0.0.0-20200119044424-58c23975cae1/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= golang.org/x/image v0.0.0-20200430140353-33d19683fad8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e h1:3G+cUijn7XD+S4eJFddp53Pv7+slrESplyjG25HgL+k= golang.org/x/net v0.0.0-20200505041828-1ed23360d12c h1:zJ0mtu4jCalhKg6Oaukv6iIkb+cOvDrajDH9DH46Q4M=
golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= golang.org/x/net v0.0.0-20200505041828-1ed23360d12c/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
golang.org/x/sys v0.0.0-20181128092732-4ed8d59d0b35/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181128092732-4ed8d59d0b35/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190626150813-e07cf5db2756/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190626150813-e07cf5db2756/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200202164722-d101bd2416d5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd h1:xhmwyvizuTgC2qz7ZlMluP20uW+C3Rm0FD/WLDX8884= golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd h1:xhmwyvizuTgC2qz7ZlMluP20uW+C3Rm0FD/WLDX8884=
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200501145240-bc7a7d42d5c3 h1:5B6i6EAiSYyejWfvc5Rc9BbI3rzIsrrXfAQBWnYfn+w=
golang.org/x/sys v0.0.0-20200501145240-bc7a7d42d5c3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs= golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
@ -73,11 +89,15 @@ gopkg.in/toast.v1 v1.0.0-20180812000517-0a84660828b2/go.mod h1:s1Sn2yZos05Qfs7NK
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10= gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
maunium.net/go/mautrix v0.2.0-beta.3 h1:pm5MQszvzYaLyCEGjyUau4DvzrOw5dT45UAvDLz5zBo= maunium.net/go/mautrix v0.3.0 h1:Ij8O3JY5zL/8TqXYSYm0YGe2RFO3HgG/BAfdy9CFFo8=
maunium.net/go/mautrix v0.2.0-beta.3/go.mod h1:WeTUYKrM3/4LZK2bXQ9NRIXnRWKsa+6+OA1gw0nf5G8= maunium.net/go/mautrix v0.3.0/go.mod h1:SkGZzch8CvU2qKtNpYxtzZ0sQxfVEJ3IsVVLSUBUx9Y=
maunium.net/go/mautrix v0.2.0-beta.4 h1:L7Jpc+8GGc+Qo0DdamACEeU1Ci9G1mergJpsTTgDOUA= maunium.net/go/mautrix v0.3.1 h1:zDhN4PYdWavbssA+9JVoCsUmu/u0LtdHeE647oh3W8c=
maunium.net/go/mautrix v0.2.0-beta.4/go.mod h1:WeTUYKrM3/4LZK2bXQ9NRIXnRWKsa+6+OA1gw0nf5G8= maunium.net/go/mautrix v0.3.1/go.mod h1:SkGZzch8CvU2qKtNpYxtzZ0sQxfVEJ3IsVVLSUBUx9Y=
maunium.net/go/mauview v0.1.0 h1:x2WdkKI2zdriJuPAB0CKlwmnHGE7W9xfM5z6RgG+IIg= maunium.net/go/mauview v0.1.0 h1:x2WdkKI2zdriJuPAB0CKlwmnHGE7W9xfM5z6RgG+IIg=
maunium.net/go/mauview v0.1.0/go.mod h1:og9WbzmWe9SNYNyOFlCv8qa9zMcOvG2nzRJ5vYyud9U= maunium.net/go/mauview v0.1.0/go.mod h1:og9WbzmWe9SNYNyOFlCv8qa9zMcOvG2nzRJ5vYyud9U=
maunium.net/go/mauview v0.1.1 h1:wfTXyPx3LGAGpTskh+UbBv/QItUWnEpaneHmywoYnfY=
maunium.net/go/mauview v0.1.1/go.mod h1:3QBUiuLct9moP1LgDhCGIg0Ovxn38Bd2sGndnUOuj4o=
maunium.net/go/tcell v0.1.0 h1:XzsEoGCvOw5nac+tlkSLzQcliLYTN4PrtA7ar2ptjSM= maunium.net/go/tcell v0.1.0 h1:XzsEoGCvOw5nac+tlkSLzQcliLYTN4PrtA7ar2ptjSM=
maunium.net/go/tcell v0.1.0/go.mod h1:Ru7KmI5AU7xHUx6hGltgJvknrS+8jlGGMKK15pZuc9k= maunium.net/go/tcell v0.1.0/go.mod h1:Ru7KmI5AU7xHUx6hGltgJvknrS+8jlGGMKK15pZuc9k=
maunium.net/go/tcell v0.2.0 h1:1Q0kN3wCOGAIGu1r3QHADsjSUOPDylKREvCv3EzJpVg=
maunium.net/go/tcell v0.2.0/go.mod h1:9Apcb3lNNS6C6lCqKT9UFp7BTRzHXfWE+/tgufsAMho=

View File

@ -38,12 +38,12 @@ type Gomuks struct {
// NewGomuks creates a new Gomuks instance with everything initialized, // NewGomuks creates a new Gomuks instance with everything initialized,
// but does not start it. // but does not start it.
func NewGomuks(uiProvider ifc.UIProvider, configDir, cacheDir, downloadDir string) *Gomuks { func NewGomuks(uiProvider ifc.UIProvider, configDir, dataDir, cacheDir, downloadDir string) *Gomuks {
gmx := &Gomuks{ gmx := &Gomuks{
stop: make(chan bool, 1), stop: make(chan bool, 1),
} }
gmx.config = config.NewConfig(configDir, cacheDir, downloadDir) gmx.config = config.NewConfig(configDir, dataDir, cacheDir, downloadDir)
gmx.ui = uiProvider(gmx) gmx.ui = uiProvider(gmx)
gmx.matrix = matrix.NewContainer(gmx) gmx.matrix = matrix.NewContainer(gmx)

View File

@ -18,6 +18,7 @@ package ifc
import ( import (
"maunium.net/go/mautrix" "maunium.net/go/mautrix"
"maunium.net/go/mautrix/crypto/attachment"
"maunium.net/go/mautrix/event" "maunium.net/go/mautrix/event"
"maunium.net/go/mautrix/id" "maunium.net/go/mautrix/id"
@ -59,8 +60,8 @@ type MatrixContainer interface {
GetRoom(roomID id.RoomID) *rooms.Room GetRoom(roomID id.RoomID) *rooms.Room
GetOrCreateRoom(roomID id.RoomID) *rooms.Room GetOrCreateRoom(roomID id.RoomID) *rooms.Room
Download(uri id.ContentURI) ([]byte, error) Download(uri id.ContentURI, file *attachment.EncryptedFile) ([]byte, error)
DownloadToDisk(uri id.ContentURI, target string) (string, error) DownloadToDisk(uri id.ContentURI, file *attachment.EncryptedFile, target string) (string, error)
GetDownloadURL(uri id.ContentURI) string GetDownloadURL(uri id.ContentURI) string
GetCachePath(uri id.ContentURI) string GetCachePath(uri id.ContentURI) string
} }

86
main.go
View File

@ -48,24 +48,32 @@ func main() {
debug.Initialize() debug.Initialize()
defer debug.Recover() defer debug.Recover()
configDir, err := UserConfigDir() var configDir, dataDir, cacheDir, downloadDir string
var err error
configDir, err = UserConfigDir()
if err != nil { if err != nil {
fmt.Fprintln(os.Stderr, "Failed to get config directory:", err) _, _ = fmt.Fprintln(os.Stderr, "Failed to get config directory:", err)
os.Exit(3) os.Exit(3)
} }
cacheDir, err := UserCacheDir() dataDir, err = UserDataDir()
if err != nil { if err != nil {
fmt.Fprintln(os.Stderr, "Failed to get cache directory:", err) _, _ = fmt.Fprintln(os.Stderr, "Failed to get data directory:", err)
os.Exit(3) os.Exit(3)
} }
downloadDir, err := UserDownloadDir() cacheDir, err = UserCacheDir()
if err != nil { if err != nil {
fmt.Fprintln(os.Stderr, "Failed to get download directory:", err) _, _ = fmt.Fprintln(os.Stderr, "Failed to get cache directory:", err)
os.Exit(3)
}
downloadDir, err = UserDownloadDir()
if err != nil {
_, _ = fmt.Fprintln(os.Stderr, "Failed to get download directory:", err)
os.Exit(3) os.Exit(3)
} }
gmx := NewGomuks(MainUIProvider, configDir, cacheDir, downloadDir) gmx := NewGomuks(MainUIProvider, configDir, dataDir, cacheDir, downloadDir)
gmx.Start() gmx.Start()
// We use os.Exit() everywhere, so exiting by returning from Start() shouldn't happen. // We use os.Exit() everywhere, so exiting by returning from Start() shouldn't happen.
@ -74,8 +82,19 @@ func main() {
os.Exit(2) os.Exit(2)
} }
func getRootDir(subdir string) string {
rootDir := os.Getenv("GOMUKS_ROOT")
if rootDir == "" {
return ""
}
return filepath.Join(rootDir, subdir)
}
func UserCacheDir() (dir string, err error) { func UserCacheDir() (dir string, err error) {
dir = os.Getenv("GOMUKS_CACHE_HOME") dir = os.Getenv("GOMUKS_CACHE_HOME")
if dir == "" {
dir = getRootDir("cache")
}
if dir == "" { if dir == "" {
dir, err = os.UserCacheDir() dir, err = os.UserCacheDir()
dir = filepath.Join(dir, "gomuks") dir = filepath.Join(dir, "gomuks")
@ -83,34 +102,43 @@ func UserCacheDir() (dir string, err error) {
return return
} }
func UserDownloadDir() (dir string, err error) { func UserDataDir() (dir string, err error) {
dir = os.Getenv("HOME") dir = os.Getenv("GOMUKS_DATA_HOME")
return filepath.Join(dir, "Downloads"), nil
}
func UserConfigDir() (dir string, err error) {
dir = os.Getenv("GOMUKS_CONFIG_HOME")
if dir != "" { if dir != "" {
return return
} }
if runtime.GOOS == "windows" { if runtime.GOOS == "windows" || runtime.GOOS == "darwin" {
dir = os.Getenv("AppData") return UserConfigDir()
}
dir = os.Getenv("XDG_DATA_HOME")
if dir == "" {
dir = getRootDir("data")
}
if dir == "" {
dir = os.Getenv("HOME")
if dir == "" { if dir == "" {
err = errors.New("%AppData% is not defined") return "", errors.New("neither $XDG_CACHE_HOME nor $HOME are defined")
}
} else {
dir = os.Getenv("XDG_CONFIG_HOME")
if dir == "" {
dir = os.Getenv("HOME")
if dir == "" {
err = errors.New("neither $XDG_CONFIG_HOME nor $HOME are defined")
} else if runtime.GOOS == "darwin" {
dir = filepath.Join(dir, "Library", "Application Support")
} else {
dir = filepath.Join(dir, ".config")
}
} }
dir = filepath.Join(dir, ".local", "share")
} }
dir = filepath.Join(dir, "gomuks") dir = filepath.Join(dir, "gomuks")
return return
} }
func UserDownloadDir() (dir string, err error) {
dir, err = os.UserHomeDir()
dir = filepath.Join(dir, "Downloads")
return
}
func UserConfigDir() (dir string, err error) {
dir = os.Getenv("GOMUKS_CONFIG_HOME")
if dir == "" {
dir = getRootDir("cache")
}
if dir == "" {
dir, err = os.UserConfigDir()
dir = filepath.Join(dir, "gomuks")
}
return
}

62
matrix/crypto.go Normal file
View File

@ -0,0 +1,62 @@
// gomuks - A terminal Matrix client written in Go.
// Copyright (C) 2020 Tulir Asokan
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
// +build cgo
package matrix
import (
"path/filepath"
"maunium.net/go/mautrix/crypto"
"maunium.net/go/gomuks/debug"
)
type cryptoLogger struct{}
func (c cryptoLogger) Error(message string, args ...interface{}) {
debug.Printf("[Crypto/Error] "+message, args...)
}
func (c cryptoLogger) Warn(message string, args ...interface{}) {
debug.Printf("[Crypto/Warn] "+message, args...)
}
func (c cryptoLogger) Debug(message string, args ...interface{}) {
debug.Printf("[Crypto/Debug] "+message, args...)
}
func (c cryptoLogger) Trace(message string, args ...interface{}) {
debug.Printf("[Crypto/Trace] "+message, args...)
}
func isBadEncryptError(err error) bool {
return err != crypto.SessionExpired && err != crypto.SessionNotShared && err != crypto.NoGroupSession
}
func (c *Container) initCrypto() error {
cryptoStore, err := crypto.NewGobStore(filepath.Join(c.config.DataDir, "crypto.gob"))
if err != nil {
return err
}
c.crypto = crypto.NewOlmMachine(c.client, cryptoLogger{}, cryptoStore, c.config.Rooms)
err = c.crypto.Load()
if err != nil {
return err
}
return nil
}

View File

@ -17,7 +17,6 @@
package matrix package matrix
import ( import (
"bytes"
"context" "context"
"crypto/tls" "crypto/tls"
"encoding/gob" "encoding/gob"
@ -37,6 +36,7 @@ import (
"github.com/pkg/errors" "github.com/pkg/errors"
"maunium.net/go/mautrix" "maunium.net/go/mautrix"
"maunium.net/go/mautrix/crypto/attachment"
"maunium.net/go/mautrix/event" "maunium.net/go/mautrix/event"
"maunium.net/go/mautrix/format" "maunium.net/go/mautrix/format"
"maunium.net/go/mautrix/id" "maunium.net/go/mautrix/id"
@ -55,6 +55,7 @@ import (
// It is used for all Matrix calls from the UI and Matrix event handlers. // It is used for all Matrix calls from the UI and Matrix event handlers.
type Container struct { type Container struct {
client *mautrix.Client client *mautrix.Client
crypto CryptoInterface
syncer *GomuksSyncer syncer *GomuksSyncer
gmx ifc.Gomuks gmx ifc.Gomuks
ui ifc.GomuksUI ui ifc.GomuksUI
@ -88,6 +89,16 @@ func (log mxLogger) Debugfln(message string, args ...interface{}) {
debug.Printf("[Matrix] "+message, args...) debug.Printf("[Matrix] "+message, args...)
} }
type CryptoInterface interface {
Load() error
FlushStore() error
ProcessSyncResponse(resp *mautrix.RespSync, since string)
HandleMemberEvent(*event.Event)
DecryptMegolmEvent(*event.Event) (*event.Event, error)
EncryptMegolmEvent(id.RoomID, event.Type, event.Content) (*event.EncryptedEventContent, error)
ShareGroupSession(id.RoomID, []id.UserID) error
}
// InitClient initializes the mautrix client and connects to the homeserver specified in the config. // InitClient initializes the mautrix client and connects to the homeserver specified in the config.
func (c *Container) InitClient() error { func (c *Container) InitClient() error {
if len(c.config.HS) == 0 { if len(c.config.HS) == 0 {
@ -97,6 +108,7 @@ func (c *Container) InitClient() error {
if c.client != nil { if c.client != nil {
c.Stop() c.Stop()
c.client = nil c.client = nil
c.crypto = nil
} }
var mxid id.UserID var mxid id.UserID
@ -112,6 +124,12 @@ func (c *Container) InitClient() error {
return err return err
} }
c.client.Logger = mxLogger{} c.client.Logger = mxLogger{}
c.client.DeviceID = c.config.DeviceID
err = c.initCrypto()
if err != nil {
return err
}
if c.history == nil { if c.history == nil {
c.history, err = NewHistoryManager(c.config.HistoryPath) c.history, err = NewHistoryManager(c.config.HistoryPath)
@ -159,7 +177,9 @@ func (c *Container) PasswordLogin(user, password string) error {
func (c *Container) finishLogin(resp *mautrix.RespLogin) { func (c *Container) finishLogin(resp *mautrix.RespLogin) {
c.client.SetCredentials(resp.UserID, resp.AccessToken) c.client.SetCredentials(resp.UserID, resp.AccessToken)
c.client.DeviceID = resp.DeviceID
c.config.UserID = resp.UserID c.config.UserID = resp.UserID
c.config.DeviceID = resp.DeviceID
c.config.AccessToken = resp.AccessToken c.config.AccessToken = resp.AccessToken
c.config.Save() c.config.Save()
@ -247,9 +267,10 @@ func (c *Container) Login(user, password string) error {
// Logout revokes the access token, stops the syncer and calls the OnLogout() method of the UI. // Logout revokes the access token, stops the syncer and calls the OnLogout() method of the UI.
func (c *Container) Logout() { func (c *Container) Logout() {
c.client.Logout() c.client.Logout()
c.config.DeleteSession()
c.Stop() c.Stop()
c.config.DeleteSession()
c.client = nil c.client = nil
c.crypto = nil
c.ui.OnLogout() c.ui.OnLogout()
} }
@ -265,6 +286,13 @@ func (c *Container) Stop() {
debug.Print("Error closing history manager:", err) debug.Print("Error closing history manager:", err)
} }
c.history = nil c.history = nil
if c.crypto != nil {
debug.Print("Flushing crypto store")
err = c.crypto.FlushStore()
if err != nil {
debug.Print("Error flushing crypto store:", err)
}
}
} }
} }
@ -315,8 +343,20 @@ func (c *Container) OnLogin() {
debug.Print("Initializing syncer") debug.Print("Initializing syncer")
c.syncer = NewGomuksSyncer(c.config.Rooms) c.syncer = NewGomuksSyncer(c.config.Rooms)
if c.crypto != nil {
c.syncer.OnSync(c.crypto.ProcessSyncResponse)
c.syncer.OnEventType(event.StateMember, func(source EventSource, evt *event.Event) {
// Don't spam the crypto module with member events of an initial sync
// TODO invalidate all group sessions when clearing cache?
if c.config.AuthCache.InitialSyncDone {
c.crypto.HandleMemberEvent(evt)
}
})
c.syncer.OnEventType(event.EventEncrypted, c.HandleEncrypted)
} else {
c.syncer.OnEventType(event.EventEncrypted, c.HandleMessage)
}
c.syncer.OnEventType(event.EventMessage, c.HandleMessage) c.syncer.OnEventType(event.EventMessage, c.HandleMessage)
c.syncer.OnEventType(event.EventEncrypted, c.HandleMessage)
c.syncer.OnEventType(event.EventSticker, c.HandleMessage) c.syncer.OnEventType(event.EventSticker, c.HandleMessage)
c.syncer.OnEventType(event.EventReaction, c.HandleMessage) c.syncer.OnEventType(event.EventReaction, c.HandleMessage)
c.syncer.OnEventType(event.EventRedaction, c.HandleRedaction) c.syncer.OnEventType(event.EventRedaction, c.HandleRedaction)
@ -516,6 +556,17 @@ func (c *Container) HandleReaction(room *rooms.Room, reactsTo id.EventID, reactE
} }
} }
func (c *Container) HandleEncrypted(source EventSource, mxEvent *event.Event) {
evt, err := c.crypto.DecryptMegolmEvent(mxEvent)
if err != nil {
debug.Print("Failed to decrypt event:", err)
// TODO add decryption failed message instead of passing through directly
c.HandleMessage(source, mxEvent)
return
}
c.HandleMessage(source, evt)
}
// HandleMessage is the event handler for the m.room.message timeline event. // HandleMessage is the event handler for the m.room.message timeline event.
func (c *Container) HandleMessage(source EventSource, mxEvent *event.Event) { func (c *Container) HandleMessage(source EventSource, mxEvent *event.Event) {
room := c.GetOrCreateRoom(mxEvent.RoomID) room := c.GetOrCreateRoom(mxEvent.RoomID)
@ -526,13 +577,16 @@ func (c *Container) HandleMessage(source EventSource, mxEvent *event.Event) {
return return
} }
rel := mxEvent.Content.AsMessage().GetRelatesTo() relatable, ok := mxEvent.Content.Parsed.(event.Relatable)
if editID := rel.GetReplaceID(); len(editID) > 0 { if ok {
c.HandleEdit(room, editID, muksevt.Wrap(mxEvent)) rel := relatable.GetRelatesTo()
return if editID := rel.GetReplaceID(); len(editID) > 0 {
} else if reactionID := rel.GetAnnotationID(); mxEvent.Type == event.EventReaction && len(reactionID) > 0 { c.HandleEdit(room, editID, muksevt.Wrap(mxEvent))
c.HandleReaction(room, reactionID, muksevt.Wrap(mxEvent)) return
return } else if reactionID := rel.GetAnnotationID(); mxEvent.Type == event.EventReaction && len(reactionID) > 0 {
c.HandleReaction(room, reactionID, muksevt.Wrap(mxEvent))
return
}
} }
events, err := c.history.Append(room, []*event.Event{mxEvent}) events, err := c.history.Append(room, []*event.Event{mxEvent})
@ -824,8 +878,28 @@ func (c *Container) Redact(roomID id.RoomID, eventID id.EventID, reason string)
func (c *Container) SendEvent(evt *muksevt.Event) (id.EventID, error) { func (c *Container) SendEvent(evt *muksevt.Event) (id.EventID, error) {
defer debug.Recover() defer debug.Recover()
c.client.UserTyping(evt.RoomID, false, 0) _, _ = c.client.UserTyping(evt.RoomID, false, 0)
c.typing = 0 c.typing = 0
room := c.GetRoom(evt.RoomID)
if room != nil && room.Encrypted && c.crypto != nil && evt.Type != event.EventReaction {
encrypted, err := c.crypto.EncryptMegolmEvent(evt.RoomID, evt.Type, evt.Content)
if err != nil {
if isBadEncryptError(err) {
return "", err
}
debug.Print("Got", err, "while trying to encrypt message, sharing group session and trying again...")
err = c.crypto.ShareGroupSession(room.ID, room.GetMemberList())
if err != nil {
return "", err
}
encrypted, err = c.crypto.EncryptMegolmEvent(evt.RoomID, evt.Type, evt.Content)
if err != nil {
return "", err
}
}
evt.Type = event.EventEncrypted
evt.Content = event.Content{Parsed: encrypted}
}
resp, err := c.client.SendMessageEvent(evt.RoomID, evt.Type, &evt.Content, mautrix.ReqSendEvent{TransactionID: evt.Unsigned.TransactionID}) resp, err := c.client.SendMessageEvent(evt.RoomID, evt.Type, &evt.Content, mautrix.ReqSendEvent{TransactionID: evt.Unsigned.TransactionID})
if err != nil { if err != nil {
return "", err return "", err
@ -923,11 +997,21 @@ func (c *Container) GetHistory(room *rooms.Room, limit int) ([]*muksevt.Event, e
return nil, err return nil, err
} }
debug.Printf("Loaded %d events for %s from server from %s to %s", len(resp.Chunk), room.ID, resp.Start, resp.End) debug.Printf("Loaded %d events for %s from server from %s to %s", len(resp.Chunk), room.ID, resp.Start, resp.End)
for _, evt := range resp.Chunk { for i, evt := range resp.Chunk {
err := evt.Content.ParseRaw(evt.Type) err := evt.Content.ParseRaw(evt.Type)
if err != nil { if err != nil {
debug.Printf("Failed to unmarshal content of event %s (type %s) by %s in %s: %v\n%s", evt.ID, evt.Type.Repr(), evt.Sender, evt.RoomID, err, string(evt.Content.VeryRaw)) debug.Printf("Failed to unmarshal content of event %s (type %s) by %s in %s: %v\n%s", evt.ID, evt.Type.Repr(), evt.Sender, evt.RoomID, err, string(evt.Content.VeryRaw))
} }
if c.crypto != nil && evt.Type == event.EventEncrypted {
decrypted, err := c.crypto.DecryptMegolmEvent(evt)
if err != nil {
debug.Print("Failed to decrypt event:", err)
// TODO add decryption failed message instead of passing through directly
} else {
resp.Chunk[i] = decrypted
}
}
} }
for _, evt := range resp.State { for _, evt := range resp.State {
room.UpdateState(evt) room.UpdateState(evt)
@ -991,7 +1075,7 @@ func cp(src, dst string) error {
return out.Close() return out.Close()
} }
func (c *Container) DownloadToDisk(uri id.ContentURI, target string) (fullPath string, err error) { func (c *Container) DownloadToDisk(uri id.ContentURI, file *attachment.EncryptedFile, target string) (fullPath string, err error) {
cachePath := c.GetCachePath(uri) cachePath := c.GetCachePath(uri)
if target == "" { if target == "" {
fullPath = cachePath fullPath = cachePath
@ -1002,21 +1086,27 @@ func (c *Container) DownloadToDisk(uri id.ContentURI, target string) (fullPath s
} }
if _, statErr := os.Stat(cachePath); os.IsNotExist(statErr) { if _, statErr := os.Stat(cachePath); os.IsNotExist(statErr) {
var file *os.File
file, err = os.OpenFile(cachePath, os.O_CREATE|os.O_WRONLY, 0600)
if err != nil {
return
}
defer file.Close()
var body io.ReadCloser var body io.ReadCloser
body, err = c.client.Download(uri) body, err = c.client.Download(uri)
if err != nil { if err != nil {
return return
} }
defer body.Close()
_, err = io.Copy(file, body) var data []byte
data, err = ioutil.ReadAll(body)
_ = body.Close()
if err != nil {
return
}
if file != nil {
data, err = file.Decrypt(data)
if err != nil {
return
}
}
err = ioutil.WriteFile(cachePath, data, 0600)
if err != nil { if err != nil {
return return
} }
@ -1036,7 +1126,7 @@ func (c *Container) DownloadToDisk(uri id.ContentURI, target string) (fullPath s
// Download fetches the given Matrix content (mxc) URL and returns the data, homeserver, file ID and potential errors. // Download fetches the given Matrix content (mxc) URL and returns the data, homeserver, file ID and potential errors.
// //
// The file will be either read from the media cache (if found) or downloaded from the server. // The file will be either read from the media cache (if found) or downloaded from the server.
func (c *Container) Download(uri id.ContentURI) (data []byte, err error) { func (c *Container) Download(uri id.ContentURI, file *attachment.EncryptedFile) (data []byte, err error) {
cacheFile := c.GetCachePath(uri) cacheFile := c.GetCachePath(uri)
var info os.FileInfo var info os.FileInfo
if info, err = os.Stat(cacheFile); err == nil && !info.IsDir() { if info, err = os.Stat(cacheFile); err == nil && !info.IsDir() {
@ -1046,7 +1136,7 @@ func (c *Container) Download(uri id.ContentURI) (data []byte, err error) {
} }
} }
data, err = c.download(uri, cacheFile) data, err = c.download(uri, file, cacheFile)
return return
} }
@ -1054,21 +1144,25 @@ func (c *Container) GetDownloadURL(uri id.ContentURI) string {
return c.client.GetDownloadURL(uri) return c.client.GetDownloadURL(uri)
} }
func (c *Container) download(uri id.ContentURI, cacheFile string) (data []byte, err error) { func (c *Container) download(uri id.ContentURI, file *attachment.EncryptedFile, cacheFile string) (data []byte, err error) {
var body io.ReadCloser var body io.ReadCloser
body, err = c.client.Download(uri) body, err = c.client.Download(uri)
if err != nil { if err != nil {
return return
} }
defer body.Close()
var buf bytes.Buffer data, err = ioutil.ReadAll(body)
_, err = io.Copy(&buf, body) _ = body.Close()
if err != nil { if err != nil {
return return
} }
data = buf.Bytes() if file != nil {
data, err = file.Decrypt(data)
if err != nil {
return
}
}
err = ioutil.WriteFile(cacheFile, data, 0600) err = ioutil.WriteFile(cacheFile, data, 0600)
return return

13
matrix/nocrypto.go Normal file
View File

@ -0,0 +1,13 @@
// This contains no-op stubs of the methods in crypto.go for non-cgo builds with crypto disabled.
// +build !cgo
package matrix
func isBadEncryptError(err error) bool {
return false
}
func (c *Container) initCrypto() error {
return nil
}

View File

@ -412,7 +412,7 @@ func (room *Room) UpdateState(evt *event.Event) {
case *event.TopicEventContent: case *event.TopicEventContent:
room.topicCache = content.Topic room.topicCache = content.Topic
case *event.EncryptionEventContent: case *event.EncryptionEventContent:
if content.Algorithm == event.AlgorithmMegolmV1 { if content.Algorithm == id.AlgorithmMegolmV1 {
room.Encrypted = true room.Encrypted = true
} }
} }
@ -650,6 +650,17 @@ func (room *Room) GetMembers() map[id.UserID]*Member {
return room.memberCache return room.memberCache
} }
func (room *Room) GetMemberList() []id.UserID {
members := room.GetMembers()
memberList := make([]id.UserID, len(members))
index := 0
for userID, _ := range members {
memberList[index] = userID
index++
}
return memberList
}
// GetMember returns the member with the given MXID. // GetMember returns the member with the given MXID.
// If the member doesn't exist, nil is returned. // If the member doesn't exist, nil is returned.
func (room *Room) GetMember(userID id.UserID) *Member { func (room *Room) GetMember(userID id.UserID) *Member {

View File

@ -27,6 +27,7 @@ import (
sync "github.com/sasha-s/go-deadlock" sync "github.com/sasha-s/go-deadlock"
"maunium.net/go/gomuks/debug" "maunium.net/go/gomuks/debug"
"maunium.net/go/mautrix/event"
"maunium.net/go/mautrix/id" "maunium.net/go/mautrix/id"
) )
@ -67,6 +68,29 @@ func (cache *RoomCache) EnableUnloading() {
cache.noUnload = false cache.noUnload = false
} }
func (cache *RoomCache) IsEncrypted(roomID id.RoomID) bool {
room := cache.Get(roomID)
return room != nil && room.Encrypted
}
func (cache *RoomCache) FindSharedRooms(userID id.UserID) (shared []id.RoomID) {
// FIXME this disables unloading so TouchNode wouldn't try to double-lock
cache.DisableUnloading()
cache.Lock()
for _, room := range cache.Map {
if !room.Encrypted {
continue
}
member, ok := room.GetMembers()[userID]
if ok && member.Membership == event.MembershipJoin {
shared = append(shared, room.ID)
}
}
cache.Unlock()
cache.EnableUnloading()
return
}
func (cache *RoomCache) LoadList() error { func (cache *RoomCache) LoadList() error {
cache.Lock() cache.Lock()
defer cache.Unlock() defer cache.Unlock()

View File

@ -83,9 +83,11 @@ func (es EventSource) String() string {
} }
type EventHandler func(source EventSource, event *event.Event) type EventHandler func(source EventSource, event *event.Event)
type SyncHandler func(resp *mautrix.RespSync, since string)
type GomuksSyncer struct { type GomuksSyncer struct {
rooms *rooms.RoomCache rooms *rooms.RoomCache
globalListeners []SyncHandler
listeners map[event.Type][]EventHandler // event type to listeners array listeners map[event.Type][]EventHandler // event type to listeners array
FirstSyncDone bool FirstSyncDone bool
InitDoneCallback func() InitDoneCallback func()
@ -96,10 +98,11 @@ type GomuksSyncer struct {
// NewGomuksSyncer returns an instantiated GomuksSyncer // NewGomuksSyncer returns an instantiated GomuksSyncer
func NewGomuksSyncer(rooms *rooms.RoomCache) *GomuksSyncer { func NewGomuksSyncer(rooms *rooms.RoomCache) *GomuksSyncer {
return &GomuksSyncer{ return &GomuksSyncer{
rooms: rooms, rooms: rooms,
listeners: make(map[event.Type][]EventHandler), globalListeners: []SyncHandler{},
FirstSyncDone: false, listeners: make(map[event.Type][]EventHandler),
Progress: StubSyncingModal{}, FirstSyncDone: false,
Progress: StubSyncingModal{},
} }
} }
@ -109,23 +112,26 @@ func (s *GomuksSyncer) ProcessResponse(res *mautrix.RespSync, since string) (err
s.rooms.DisableUnloading() s.rooms.DisableUnloading()
} }
debug.Print("Received sync response") debug.Print("Received sync response")
s.Progress.SetMessage("Processing sync response")
steps := len(res.Rooms.Join) + len(res.Rooms.Invite) + len(res.Rooms.Leave) steps := len(res.Rooms.Join) + len(res.Rooms.Invite) + len(res.Rooms.Leave)
s.Progress.SetSteps(steps + 2) s.Progress.SetSteps(steps + 2 + len(s.globalListeners))
s.Progress.SetMessage("Processing global events")
wait := &sync.WaitGroup{}
callback := func() {
wait.Done()
s.Progress.Step()
}
wait.Add(len(s.globalListeners))
s.notifyGlobalListeners(res, since, callback)
wait.Wait()
s.processSyncEvents(nil, res.Presence.Events, EventSourcePresence) s.processSyncEvents(nil, res.Presence.Events, EventSourcePresence)
s.Progress.Step() s.Progress.Step()
s.processSyncEvents(nil, res.AccountData.Events, EventSourceAccountData) s.processSyncEvents(nil, res.AccountData.Events, EventSourceAccountData)
s.Progress.Step() s.Progress.Step()
wait := &sync.WaitGroup{}
wait.Add(steps) wait.Add(steps)
callback := func() {
wait.Done()
s.Progress.Step()
}
s.Progress.SetMessage("Processing room events")
for roomID, roomData := range res.Rooms.Join { for roomID, roomData := range res.Rooms.Join {
go s.processJoinedRoom(roomID, roomData, callback) go s.processJoinedRoom(roomID, roomData, callback)
} }
@ -152,6 +158,15 @@ func (s *GomuksSyncer) ProcessResponse(res *mautrix.RespSync, since string) (err
return return
} }
func (s *GomuksSyncer) notifyGlobalListeners(res *mautrix.RespSync, since string, callback func()) {
for _, listener := range s.globalListeners {
go func(listener SyncHandler) {
listener(res, since)
callback()
}(listener)
}
}
func (s *GomuksSyncer) processJoinedRoom(roomID id.RoomID, roomData mautrix.SyncJoinedRoom, callback func()) { func (s *GomuksSyncer) processJoinedRoom(roomID id.RoomID, roomData mautrix.SyncJoinedRoom, callback func()) {
defer debug.Recover() defer debug.Recover()
room := s.rooms.GetOrCreate(roomID) room := s.rooms.GetOrCreate(roomID)
@ -239,6 +254,10 @@ func (s *GomuksSyncer) OnEventType(eventType event.Type, callback EventHandler)
s.listeners[eventType] = append(s.listeners[eventType], callback) s.listeners[eventType] = append(s.listeners[eventType], callback)
} }
func (s *GomuksSyncer) OnSync(callback SyncHandler) {
s.globalListeners = append(s.globalListeners, callback)
}
func (s *GomuksSyncer) notifyListeners(source EventSource, evt *event.Event) { func (s *GomuksSyncer) notifyListeners(source EventSource, evt *event.Event) {
listeners, exists := s.listeners[evt.Type] listeners, exists := s.listeners[evt.Type]
if !exists { if !exists {
@ -269,6 +288,7 @@ func (s *GomuksSyncer) GetFilterJSON(_ id.UserID) *mautrix.Filter {
event.StateCanonicalAlias, event.StateCanonicalAlias,
event.StatePowerLevels, event.StatePowerLevels,
event.StateTombstone, event.StateTombstone,
event.StateEncryption,
}, },
}, },
Timeline: mautrix.FilterPart{ Timeline: mautrix.FilterPart{

View File

@ -22,7 +22,7 @@ import (
"image" "image"
"image/color" "image/color"
"maunium.net/go/gomuks/matrix/muksevt" "maunium.net/go/mautrix/crypto/attachment"
"maunium.net/go/mautrix/event" "maunium.net/go/mautrix/event"
"maunium.net/go/mautrix/id" "maunium.net/go/mautrix/id"
"maunium.net/go/mauview" "maunium.net/go/mauview"
@ -32,14 +32,19 @@ import (
"maunium.net/go/gomuks/debug" "maunium.net/go/gomuks/debug"
"maunium.net/go/gomuks/interface" "maunium.net/go/gomuks/interface"
"maunium.net/go/gomuks/lib/ansimage" "maunium.net/go/gomuks/lib/ansimage"
"maunium.net/go/gomuks/matrix/muksevt"
"maunium.net/go/gomuks/ui/messages/tstring" "maunium.net/go/gomuks/ui/messages/tstring"
) )
type FileMessage struct { type FileMessage struct {
Type event.MessageType Type event.MessageType
Body string Body string
URL id.ContentURI
Thumbnail id.ContentURI URL id.ContentURI
File *attachment.EncryptedFile
Thumbnail id.ContentURI
ThumbnailFile *attachment.EncryptedFile
imageData []byte imageData []byte
buffer []tstring.TString buffer []tstring.TString
@ -49,14 +54,23 @@ type FileMessage struct {
// NewFileMessage creates a new FileMessage object with the provided values and the default state. // NewFileMessage creates a new FileMessage object with the provided values and the default state.
func NewFileMessage(matrix ifc.MatrixContainer, evt *muksevt.Event, displayname string) *UIMessage { func NewFileMessage(matrix ifc.MatrixContainer, evt *muksevt.Event, displayname string) *UIMessage {
content := evt.Content.AsMessage() content := evt.Content.AsMessage()
url, _ := content.URL.Parse() var file, thumbnailFile *attachment.EncryptedFile
thumbnail, _ := content.GetInfo().ThumbnailURL.Parse() if content.File != nil {
file = &content.File.EncryptedFile
content.URL = content.File.URL
}
if content.GetInfo().ThumbnailFile != nil {
thumbnailFile = &content.Info.ThumbnailFile.EncryptedFile
content.Info.ThumbnailURL = content.Info.ThumbnailFile.URL
}
return newUIMessage(evt, displayname, &FileMessage{ return newUIMessage(evt, displayname, &FileMessage{
Type: content.MsgType, Type: content.MsgType,
Body: content.Body, Body: content.Body,
URL: url, URL: content.URL.ParseOrIgnore(),
Thumbnail: thumbnail, File: file,
matrix: matrix, Thumbnail: content.GetInfo().ThumbnailURL.ParseOrIgnore(),
ThumbnailFile: thumbnailFile,
matrix: matrix,
}) })
} }
@ -96,17 +110,20 @@ func (msg *FileMessage) String() string {
} }
func (msg *FileMessage) DownloadPreview() { func (msg *FileMessage) DownloadPreview() {
url := msg.Thumbnail var url id.ContentURI
if url.IsEmpty() { var file *attachment.EncryptedFile
if msg.Type == event.MsgImage && !msg.URL.IsEmpty() { if !msg.Thumbnail.IsEmpty() {
msg.Thumbnail = msg.URL url = msg.Thumbnail
url = msg.Thumbnail file = msg.ThumbnailFile
} else { } else if msg.Type == event.MsgImage && !msg.URL.IsEmpty() {
return msg.Thumbnail = msg.URL
} url = msg.URL
file = msg.File
} else {
return
} }
debug.Print("Loading file:", url) debug.Print("Loading file:", url)
data, err := msg.matrix.Download(url) data, err := msg.matrix.Download(url, file)
if err != nil { if err != nil {
debug.Printf("Failed to download file %s: %v", url, err) debug.Printf("Failed to download file %s: %v", url, err)
return return

View File

@ -20,13 +20,13 @@ import (
"fmt" "fmt"
"strings" "strings"
"maunium.net/go/gomuks/debug"
"maunium.net/go/gomuks/matrix/muksevt"
"maunium.net/go/mautrix/event" "maunium.net/go/mautrix/event"
"maunium.net/go/mautrix/id" "maunium.net/go/mautrix/id"
"maunium.net/go/tcell" "maunium.net/go/tcell"
"maunium.net/go/gomuks/debug"
"maunium.net/go/gomuks/interface" "maunium.net/go/gomuks/interface"
"maunium.net/go/gomuks/matrix/muksevt"
"maunium.net/go/gomuks/matrix/rooms" "maunium.net/go/gomuks/matrix/rooms"
"maunium.net/go/gomuks/ui/messages/html" "maunium.net/go/gomuks/ui/messages/html"
"maunium.net/go/gomuks/ui/messages/tstring" "maunium.net/go/gomuks/ui/messages/tstring"
@ -82,7 +82,7 @@ func directParseEvent(matrix ifc.MatrixContainer, room *rooms.Room, evt *muksevt
} }
return ParseMessage(matrix, room, evt, displayname) return ParseMessage(matrix, room, evt, displayname)
case *event.EncryptedEventContent: case *event.EncryptedEventContent:
return NewExpandedTextMessage(evt, displayname, tstring.NewStyleTString("Encrypted messages are not yet supported", tcell.StyleDefault.Italic(true))) return NewExpandedTextMessage(evt, displayname, tstring.NewStyleTString("Decryption failed or gomuks not built with encryption support", tcell.StyleDefault.Italic(true)))
case *event.TopicEventContent, *event.RoomNameEventContent, *event.CanonicalAliasEventContent: case *event.TopicEventContent, *event.RoomNameEventContent, *event.CanonicalAliasEventContent:
return ParseStateEvent(evt, displayname) return ParseStateEvent(evt, displayname)
case *event.MemberEventContent: case *event.MemberEventContent:

View File

@ -26,6 +26,7 @@ import (
"github.com/kyokomi/emoji" "github.com/kyokomi/emoji"
"github.com/mattn/go-runewidth" "github.com/mattn/go-runewidth"
"maunium.net/go/mautrix/crypto/attachment"
"maunium.net/go/mauview" "maunium.net/go/mauview"
"maunium.net/go/tcell" "maunium.net/go/tcell"
@ -122,6 +123,10 @@ func NewRoomView(parent *MainView, room *rooms.Room) *RoomView {
SetPressKeyUpAtStartFunc(view.EditPrevious). SetPressKeyUpAtStartFunc(view.EditPrevious).
SetPressKeyDownAtEndFunc(view.EditNext) SetPressKeyDownAtEndFunc(view.EditNext)
if room.Encrypted {
view.input.SetPlaceholder("Send an encrypted message...")
}
view.topic. view.topic.
SetTextColor(tcell.ColorWhite). SetTextColor(tcell.ColorWhite).
SetBackgroundColor(tcell.ColorDarkGreen) SetBackgroundColor(tcell.ColorDarkGreen)
@ -202,7 +207,7 @@ func (view *RoomView) OnSelect(message *messages.UIMessage) {
} else if view.selectReason == SelectDownload { } else if view.selectReason == SelectDownload {
path = msg.Body path = msg.Body
} }
go view.Download(msg.URL, path, view.selectReason == SelectOpen) go view.Download(msg.URL, msg.File, path, view.selectReason == SelectOpen)
} }
} }
view.selecting = false view.selecting = false
@ -624,8 +629,8 @@ func (view *RoomView) InputSubmit(text string) {
view.SetInputText("") view.SetInputText("")
} }
func (view *RoomView) Download(url id.ContentURI, filename string, openFile bool) { func (view *RoomView) Download(url id.ContentURI, file *attachment.EncryptedFile, filename string, openFile bool) {
path, err := view.parent.matrix.DownloadToDisk(url, filename) path, err := view.parent.matrix.DownloadToDisk(url, file, filename)
if err != nil { if err != nil {
view.AddServiceMessage(fmt.Sprintf("Failed to download media: %v", err)) view.AddServiceMessage(fmt.Sprintf("Failed to download media: %v", err))
view.parent.parent.Render() view.parent.parent.Render()