At a high level, this is what I've done and why:
- I'm moving the protobuf generation for the `protocol`, `discovery` and
`db` packages to the modern alternatives, and using `buf` to generate
because it's nice and simple.
- After trying various approaches on how to integrate the new types with
the existing code, I opted for splitting off our own data model types
from the on-the-wire generated types. This means we can have a
`FileInfo` type with nicer ergonomics and lots of methods, while the
protobuf generated type stays clean and close to the wire protocol. It
does mean copying between the two when required, which certainly adds a
small amount of inefficiency. If we want to walk this back in the future
and use the raw generated type throughout, that's possible, this however
makes the refactor smaller (!) as it doesn't change everything about the
type for everyone at the same time.
- I have simply removed in cold blood a significant number of old
database migrations. These depended on previous generations of generated
messages of various kinds and were annoying to support in the new
fashion. The oldest supported database version now is the one from
Syncthing 1.9.0 from Sep 7, 2020.
- I changed config structs to be regular manually defined structs.
For the sake of discussion, some things I tried that turned out not to
work...
### Embedding / wrapping
Embedding the protobuf generated structs in our existing types as a data
container and keeping our methods and stuff:
```
package protocol
type FileInfo struct {
*generated.FileInfo
}
```
This generates a lot of problems because the internal shape of the
generated struct is quite different (different names, different types,
more pointers), because initializing it doesn't work like you'd expect
(i.e., you end up with an embedded nil pointer and a panic), and because
the types of child types don't get wrapped. That is, even if we also
have a similar wrapper around a `Vector`, that's not the type you get
when accessing `someFileInfo.Version`, you get the `*generated.Vector`
that doesn't have methods, etc.
### Aliasing
```
package protocol
type FileInfo = generated.FileInfo
```
Doesn't help because you can't attach methods to it, plus all the above.
### Generating the types into the target package like we do now and
attaching methods
This fails because of the different shape of the generated type (as in
the embedding case above) plus the generated struct already has a bunch
of methods that we can't necessarily override properly (like `String()`
and a bunch of getters).
### Methods to functions
I considered just moving all the methods we attach to functions in a
specific package, so that for example
```
package protocol
func (f FileInfo) Equal(other FileInfo) bool
```
would become
```
package fileinfos
func Equal(a, b *generated.FileInfo) bool
```
and this would mostly work, but becomes quite verbose and cumbersome,
and somewhat limits discoverability (you can't see what methods are
available on the type in auto completions, etc). In the end I did this
in some cases, like in the database layer where a lot of things like
`func (fv *FileVersion) IsEmpty() bool` becomes `func fvIsEmpty(fv
*generated.FileVersion)` because they were anyway just internal methods.
Fixes #8247
156 lines
5.4 KiB
Go
156 lines
5.4 KiB
Go
// Copyright (C) 2014 The Syncthing Authors.
|
|
//
|
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
|
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
|
|
// You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
|
|
package syncthing
|
|
|
|
import (
|
|
"crypto/tls"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
|
|
"github.com/syncthing/syncthing/lib/config"
|
|
"github.com/syncthing/syncthing/lib/db/backend"
|
|
"github.com/syncthing/syncthing/lib/events"
|
|
"github.com/syncthing/syncthing/lib/fs"
|
|
"github.com/syncthing/syncthing/lib/locations"
|
|
"github.com/syncthing/syncthing/lib/protocol"
|
|
"github.com/syncthing/syncthing/lib/tlsutil"
|
|
)
|
|
|
|
func EnsureDir(dir string, mode fs.FileMode) error {
|
|
fs := fs.NewFilesystem(fs.FilesystemTypeBasic, dir)
|
|
err := fs.MkdirAll(".", mode)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if fi, err := fs.Stat("."); err == nil {
|
|
// Apparently the stat may fail even though the mkdirall passed. If it
|
|
// does, we'll just assume things are in order and let other things
|
|
// fail (like loading or creating the config...).
|
|
currentMode := fi.Mode() & 0o777
|
|
if currentMode != mode {
|
|
err := fs.Chmod(".", mode)
|
|
// This can fail on crappy filesystems, nothing we can do about it.
|
|
if err != nil {
|
|
l.Warnln(err)
|
|
}
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func LoadOrGenerateCertificate(certFile, keyFile string) (tls.Certificate, error) {
|
|
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
|
|
if err != nil {
|
|
return GenerateCertificate(certFile, keyFile)
|
|
}
|
|
return cert, nil
|
|
}
|
|
|
|
func GenerateCertificate(certFile, keyFile string) (tls.Certificate, error) {
|
|
l.Infof("Generating ECDSA key and certificate for %s...", tlsDefaultCommonName)
|
|
return tlsutil.NewCertificate(certFile, keyFile, tlsDefaultCommonName, deviceCertLifetimeDays)
|
|
}
|
|
|
|
func DefaultConfig(path string, myID protocol.DeviceID, evLogger events.Logger, noDefaultFolder, skipPortProbing bool) (config.Wrapper, error) {
|
|
newCfg := config.New(myID)
|
|
|
|
if skipPortProbing {
|
|
l.Infoln("Using default network port numbers instead of probing for free ports")
|
|
// Record address override initially
|
|
newCfg.GUI.RawAddress = newCfg.GUI.Address()
|
|
} else if err := newCfg.ProbeFreePorts(); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if noDefaultFolder {
|
|
l.Infoln("We will skip creation of a default folder on first start")
|
|
return config.Wrap(path, newCfg, myID, evLogger), nil
|
|
}
|
|
|
|
fcfg := newCfg.Defaults.Folder.Copy()
|
|
fcfg.ID = "default"
|
|
fcfg.Label = "Default Folder"
|
|
fcfg.FilesystemType = config.FilesystemTypeBasic
|
|
fcfg.Path = locations.Get(locations.DefFolder)
|
|
newCfg.Folders = append(newCfg.Folders, fcfg)
|
|
l.Infoln("Default folder created and/or linked to new config")
|
|
return config.Wrap(path, newCfg, myID, evLogger), nil
|
|
}
|
|
|
|
// LoadConfigAtStartup loads an existing config. If it doesn't yet exist, it
|
|
// creates a default one, without the default folder if noDefaultFolder is true.
|
|
// Otherwise it checks the version, and archives and upgrades the config if
|
|
// necessary or returns an error, if the version isn't compatible.
|
|
func LoadConfigAtStartup(path string, cert tls.Certificate, evLogger events.Logger, allowNewerConfig, noDefaultFolder, skipPortProbing bool) (config.Wrapper, error) {
|
|
myID := protocol.NewDeviceID(cert.Certificate[0])
|
|
cfg, originalVersion, err := config.Load(path, myID, evLogger)
|
|
if fs.IsNotExist(err) {
|
|
cfg, err = DefaultConfig(path, myID, evLogger, noDefaultFolder, skipPortProbing)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to generate default config: %w", err)
|
|
}
|
|
err = cfg.Save()
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to save default config: %w", err)
|
|
}
|
|
l.Infof("Default config saved. Edit %s to taste (with Syncthing stopped) or use the GUI", cfg.ConfigPath())
|
|
} else if err == io.EOF {
|
|
return nil, errors.New("failed to load config: unexpected end of file. Truncated or empty configuration?")
|
|
} else if err != nil {
|
|
return nil, fmt.Errorf("failed to load config: %w", err)
|
|
}
|
|
|
|
if originalVersion != config.CurrentVersion {
|
|
if originalVersion == config.CurrentVersion+1101 {
|
|
l.Infof("Now, THAT's what we call a config from the future! Don't worry. As long as you hit that wire with the connecting hook at precisely eighty-eight miles per hour the instant the lightning strikes the tower... everything will be fine.")
|
|
}
|
|
if originalVersion > config.CurrentVersion && !allowNewerConfig {
|
|
return nil, fmt.Errorf("config file version (%d) is newer than supported version (%d). If this is expected, use --allow-newer-config to override.", originalVersion, config.CurrentVersion)
|
|
}
|
|
err = archiveAndSaveConfig(cfg, originalVersion)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("config archive: %w", err)
|
|
}
|
|
}
|
|
|
|
return cfg, nil
|
|
}
|
|
|
|
func archiveAndSaveConfig(cfg config.Wrapper, originalVersion int) error {
|
|
// Copy the existing config to an archive copy
|
|
archivePath := cfg.ConfigPath() + fmt.Sprintf(".v%d", originalVersion)
|
|
l.Infoln("Archiving a copy of old config file format at:", archivePath)
|
|
if err := copyFile(cfg.ConfigPath(), archivePath); err != nil {
|
|
return err
|
|
}
|
|
|
|
// Do a regular atomic config sve
|
|
return cfg.Save()
|
|
}
|
|
|
|
func copyFile(src, dst string) error {
|
|
bs, err := os.ReadFile(src)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if err := os.WriteFile(dst, bs, 0o600); err != nil {
|
|
// Attempt to clean up
|
|
os.Remove(dst)
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func OpenDBBackend(path string, tuning config.Tuning) (backend.Backend, error) {
|
|
return backend.Open(path, backend.Tuning(tuning))
|
|
}
|