all: Remove dead code, fix lost msgLen checks (#6129)

This commit is contained in:
Audrius Butkevicius 2019-11-06 06:09:58 +00:00 committed by Jakob Borg
parent 31569debeb
commit 98a1adebe1
9 changed files with 42 additions and 111 deletions

View File

@ -12,7 +12,6 @@ import (
"io/ioutil" "io/ioutil"
"net/http" "net/http"
"os" "os"
"text/tabwriter"
"github.com/syncthing/syncthing/lib/config" "github.com/syncthing/syncthing/lib/config"
"github.com/urfave/cli" "github.com/urfave/cli"
@ -45,12 +44,6 @@ func dumpOutput(url string) cli.ActionFunc {
} }
} }
func newTableWriter() *tabwriter.Writer {
writer := new(tabwriter.Writer)
writer.Init(os.Stdout, 0, 8, 0, '\t', 0)
return writer
}
func getConfig(c *APIClient) (config.Configuration, error) { func getConfig(c *APIClient) (config.Configuration, error) {
cfg := config.Configuration{} cfg := config.Configuration{}
response, err := c.Get("system/config") response, err := c.Get("system/config")

View File

@ -45,19 +45,7 @@ import (
) )
const ( const (
exitSuccess = 0
exitError = 1
exitNoUpgradeAvailable = 2
exitRestarting = 3
exitUpgrading = 4
)
const (
bepProtocolName = "bep/1.0"
tlsDefaultCommonName = "syncthing" tlsDefaultCommonName = "syncthing"
maxSystemErrors = 5
initialSystemLog = 10
maxSystemLog = 250
deviceCertLifetimeDays = 20 * 365 deviceCertLifetimeDays = 20 * 365
) )
@ -272,7 +260,7 @@ func main() {
// default location // default location
if options.noRestart && (options.logFile != "" && options.logFile != "-") { if options.noRestart && (options.logFile != "" && options.logFile != "-") {
l.Warnln("-logfile may not be used with -no-restart or STNORESTART") l.Warnln("-logfile may not be used with -no-restart or STNORESTART")
os.Exit(exitError) os.Exit(syncthing.ExitError.AsInt())
} }
if options.hideConsole { if options.hideConsole {
@ -286,12 +274,12 @@ func main() {
options.confDir, err = filepath.Abs(options.confDir) options.confDir, err = filepath.Abs(options.confDir)
if err != nil { if err != nil {
l.Warnln("Failed to make options path absolute:", err) l.Warnln("Failed to make options path absolute:", err)
os.Exit(exitError) os.Exit(syncthing.ExitError.AsInt())
} }
} }
if err := locations.SetBaseDir(locations.ConfigBaseDir, options.confDir); err != nil { if err := locations.SetBaseDir(locations.ConfigBaseDir, options.confDir); err != nil {
l.Warnln(err) l.Warnln(err)
os.Exit(exitError) os.Exit(syncthing.ExitError.AsInt())
} }
} }
@ -329,7 +317,7 @@ func main() {
) )
if err != nil { if err != nil {
l.Warnln("Error reading device ID:", err) l.Warnln("Error reading device ID:", err)
os.Exit(exitError) os.Exit(syncthing.ExitError.AsInt())
} }
fmt.Println(protocol.NewDeviceID(cert.Certificate[0])) fmt.Println(protocol.NewDeviceID(cert.Certificate[0]))
@ -339,7 +327,7 @@ func main() {
if options.browserOnly { if options.browserOnly {
if err := openGUI(protocol.EmptyDeviceID); err != nil { if err := openGUI(protocol.EmptyDeviceID); err != nil {
l.Warnln("Failed to open web UI:", err) l.Warnln("Failed to open web UI:", err)
os.Exit(exitError) os.Exit(syncthing.ExitError.AsInt())
} }
return return
} }
@ -347,7 +335,7 @@ func main() {
if options.generateDir != "" { if options.generateDir != "" {
if err := generate(options.generateDir); err != nil { if err := generate(options.generateDir); err != nil {
l.Warnln("Failed to generate config and keys:", err) l.Warnln("Failed to generate config and keys:", err)
os.Exit(exitError) os.Exit(syncthing.ExitError.AsInt())
} }
return return
} }
@ -355,14 +343,14 @@ func main() {
// Ensure that our home directory exists. // Ensure that our home directory exists.
if err := ensureDir(locations.GetBaseDir(locations.ConfigBaseDir), 0700); err != nil { if err := ensureDir(locations.GetBaseDir(locations.ConfigBaseDir), 0700); err != nil {
l.Warnln("Failure on home directory:", err) l.Warnln("Failure on home directory:", err)
os.Exit(exitError) os.Exit(syncthing.ExitError.AsInt())
} }
if options.upgradeTo != "" { if options.upgradeTo != "" {
err := upgrade.ToURL(options.upgradeTo) err := upgrade.ToURL(options.upgradeTo)
if err != nil { if err != nil {
l.Warnln("Error while Upgrading:", err) l.Warnln("Error while Upgrading:", err)
os.Exit(exitError) os.Exit(syncthing.ExitError.AsInt())
} }
l.Infoln("Upgraded from", options.upgradeTo) l.Infoln("Upgraded from", options.upgradeTo)
return return
@ -382,7 +370,7 @@ func main() {
if options.resetDatabase { if options.resetDatabase {
if err := resetDB(); err != nil { if err := resetDB(); err != nil {
l.Warnln("Resetting database:", err) l.Warnln("Resetting database:", err)
os.Exit(exitError) os.Exit(syncthing.ExitError.AsInt())
} }
return return
} }
@ -477,13 +465,13 @@ func checkUpgrade() upgrade.Release {
release, err := upgrade.LatestRelease(opts.ReleasesURL, build.Version, opts.UpgradeToPreReleases) release, err := upgrade.LatestRelease(opts.ReleasesURL, build.Version, opts.UpgradeToPreReleases)
if err != nil { if err != nil {
l.Warnln("Upgrade:", err) l.Warnln("Upgrade:", err)
os.Exit(exitError) os.Exit(syncthing.ExitError.AsInt())
} }
if upgrade.CompareVersions(release.Tag, build.Version) <= 0 { if upgrade.CompareVersions(release.Tag, build.Version) <= 0 {
noUpgradeMessage := "No upgrade available (current %q >= latest %q)." noUpgradeMessage := "No upgrade available (current %q >= latest %q)."
l.Infof(noUpgradeMessage, build.Version, release.Tag) l.Infof(noUpgradeMessage, build.Version, release.Tag)
os.Exit(exitNoUpgradeAvailable) os.Exit(syncthing.ExitNoUpgradeAvailable.AsInt())
} }
l.Infof("Upgrade available (current %q < latest %q)", build.Version, release.Tag) l.Infof("Upgrade available (current %q < latest %q)", build.Version, release.Tag)
@ -497,7 +485,7 @@ func performUpgrade(release upgrade.Release) {
err = upgrade.To(release) err = upgrade.To(release)
if err != nil { if err != nil {
l.Warnln("Upgrade:", err) l.Warnln("Upgrade:", err)
os.Exit(exitError) os.Exit(syncthing.ExitError.AsInt())
} }
l.Infof("Upgraded to %q", release.Tag) l.Infof("Upgraded to %q", release.Tag)
} else { } else {
@ -505,10 +493,10 @@ func performUpgrade(release upgrade.Release) {
err = upgradeViaRest() err = upgradeViaRest()
if err != nil { if err != nil {
l.Warnln("Upgrade:", err) l.Warnln("Upgrade:", err)
os.Exit(exitError) os.Exit(syncthing.ExitError.AsInt())
} }
l.Infoln("Syncthing upgrading") l.Infoln("Syncthing upgrading")
os.Exit(exitUpgrading) os.Exit(syncthing.ExitUpgrade.AsInt())
} }
} }
@ -574,7 +562,7 @@ func syncthingMain(runtimeOptions RuntimeOptions) {
cfg, err := syncthing.LoadConfigAtStartup(locations.Get(locations.ConfigFile), cert, evLogger, runtimeOptions.allowNewerConfig, noDefaultFolder) cfg, err := syncthing.LoadConfigAtStartup(locations.Get(locations.ConfigFile), cert, evLogger, runtimeOptions.allowNewerConfig, noDefaultFolder)
if err != nil { if err != nil {
l.Warnln("Failed to initialize config:", err) l.Warnln("Failed to initialize config:", err)
os.Exit(exitError) os.Exit(syncthing.ExitError.AsInt())
} }
if runtimeOptions.unpaused { if runtimeOptions.unpaused {
@ -611,11 +599,11 @@ func syncthingMain(runtimeOptions RuntimeOptions) {
f, err := os.Create(fmt.Sprintf("cpu-%d.pprof", os.Getpid())) f, err := os.Create(fmt.Sprintf("cpu-%d.pprof", os.Getpid()))
if err != nil { if err != nil {
l.Warnln("Creating profile:", err) l.Warnln("Creating profile:", err)
os.Exit(exitError) os.Exit(syncthing.ExitError.AsInt())
} }
if err := pprof.StartCPUProfile(f); err != nil { if err := pprof.StartCPUProfile(f); err != nil {
l.Warnln("Starting profile:", err) l.Warnln("Starting profile:", err)
os.Exit(exitError) os.Exit(syncthing.ExitError.AsInt())
} }
} }
@ -649,7 +637,7 @@ func syncthingMain(runtimeOptions RuntimeOptions) {
} }
if err := app.Start(); err != nil { if err := app.Start(); err != nil {
os.Exit(int(syncthing.ExitError)) os.Exit(syncthing.ExitError.AsInt())
} }
cleanConfigDirectory() cleanConfigDirectory()
@ -724,7 +712,7 @@ func auditWriter(auditFile string) io.Writer {
fd, err = os.OpenFile(auditFile, auditFlags, 0600) fd, err = os.OpenFile(auditFile, auditFlags, 0600)
if err != nil { if err != nil {
l.Warnln("Audit:", err) l.Warnln("Audit:", err)
os.Exit(exitError) os.Exit(syncthing.ExitError.AsInt())
} }
auditDest = auditFile auditDest = auditFile
} }
@ -900,6 +888,6 @@ func setPauseState(cfg config.Wrapper, paused bool) {
} }
if _, err := cfg.Replace(raw); err != nil { if _, err := cfg.Replace(raw); err != nil {
l.Warnln("Cannot adjust paused state:", err) l.Warnln("Cannot adjust paused state:", err)
os.Exit(exitError) os.Exit(syncthing.ExitError.AsInt())
} }
} }

View File

@ -23,6 +23,7 @@ import (
"github.com/syncthing/syncthing/lib/osutil" "github.com/syncthing/syncthing/lib/osutil"
"github.com/syncthing/syncthing/lib/protocol" "github.com/syncthing/syncthing/lib/protocol"
"github.com/syncthing/syncthing/lib/sync" "github.com/syncthing/syncthing/lib/sync"
"github.com/syncthing/syncthing/lib/syncthing"
) )
var ( var (
@ -81,7 +82,7 @@ func monitorMain(runtimeOptions RuntimeOptions) {
if t := time.Since(restarts[0]); t < loopThreshold { if t := time.Since(restarts[0]); t < loopThreshold {
l.Warnf("%d restarts in %v; not retrying further", countRestarts, t) l.Warnf("%d restarts in %v; not retrying further", countRestarts, t)
os.Exit(exitError) os.Exit(syncthing.ExitError.AsInt())
} }
copy(restarts[0:], restarts[1:]) copy(restarts[0:], restarts[1:])
@ -152,7 +153,7 @@ func monitorMain(runtimeOptions RuntimeOptions) {
} else if exiterr, ok := err.(*exec.ExitError); ok { } else if exiterr, ok := err.(*exec.ExitError); ok {
if status, ok := exiterr.Sys().(syscall.WaitStatus); ok { if status, ok := exiterr.Sys().(syscall.WaitStatus); ok {
switch status.ExitStatus() { switch status.ExitStatus() {
case exitUpgrading: case syncthing.ExitUpgrade.AsInt():
// Restart the monitor process to release the .old // Restart the monitor process to release the .old
// binary as part of the upgrade process. // binary as part of the upgrade process.
l.Infoln("Restarting monitor...") l.Infoln("Restarting monitor...")

View File

@ -7,37 +7,9 @@
package osutil package osutil
import ( import (
"bytes"
"net" "net"
) )
// ResolveInterfaceAddresses returns available addresses of the given network
// type for a given interface.
func ResolveInterfaceAddresses(network, nameOrMac string) []string {
intf, err := net.InterfaceByName(nameOrMac)
if err == nil {
return interfaceAddresses(network, intf)
}
mac, err := net.ParseMAC(nameOrMac)
if err != nil {
return []string{nameOrMac}
}
intfs, err := net.Interfaces()
if err != nil {
return []string{nameOrMac}
}
for _, intf := range intfs {
if bytes.Equal(intf.HardwareAddr, mac) {
return interfaceAddresses(network, &intf)
}
}
return []string{nameOrMac}
}
func interfaceAddresses(network string, intf *net.Interface) []string { func interfaceAddresses(network string, intf *net.Interface) []string {
var out []string var out []string
addrs, err := intf.Addrs() addrs, err := intf.Addrs()

View File

@ -79,28 +79,6 @@ const (
stateReady stateReady
) )
// Request message flags
const (
FlagFromTemporary uint32 = 1 << iota
)
// ClusterConfigMessage.Folders flags
const (
FlagFolderReadOnly uint32 = 1 << 0
FlagFolderIgnorePerms = 1 << 1
FlagFolderIgnoreDelete = 1 << 2
FlagFolderDisabledTempIndexes = 1 << 3
FlagFolderAll = 1<<4 - 1
)
// ClusterConfigMessage.Folders.Devices flags
const (
FlagShareTrusted uint32 = 1 << 0
FlagShareReadOnly = 1 << 1
FlagIntroducer = 1 << 2
FlagShareBits = 0x000000ff
)
// FileInfo.LocalFlags flags // FileInfo.LocalFlags flags
const ( const (
FlagLocalUnsupported = 1 << 0 // The kind is unsupported, e.g. symlinks on Windows FlagLocalUnsupported = 1 << 0 // The kind is unsupported, e.g. symlinks on Windows
@ -122,7 +100,6 @@ const (
var ( var (
ErrClosed = errors.New("connection closed") ErrClosed = errors.New("connection closed")
ErrTimeout = errors.New("read timeout") ErrTimeout = errors.New("read timeout")
ErrSwitchingConnections = errors.New("switching connections")
errUnknownMessage = errors.New("unknown message") errUnknownMessage = errors.New("unknown message")
errInvalidFilename = errors.New("filename is invalid") errInvalidFilename = errors.New("filename is invalid")
errUncleanFilename = errors.New("filename not in canonical format") errUncleanFilename = errors.New("filename not in canonical format")
@ -491,6 +468,8 @@ func (c *rawConnection) readMessageAfterHeader(hdr Header, fourByteBuf []byte) (
msgLen := int32(binary.BigEndian.Uint32(fourByteBuf)) msgLen := int32(binary.BigEndian.Uint32(fourByteBuf))
if msgLen < 0 { if msgLen < 0 {
return nil, fmt.Errorf("negative message length %d", msgLen) return nil, fmt.Errorf("negative message length %d", msgLen)
} else if msgLen > MaxMessageLen {
return nil, fmt.Errorf("message length %d exceeds maximum %d", msgLen, MaxMessageLen)
} }
// Then comes the message // Then comes the message

View File

@ -16,7 +16,6 @@ var (
ResponseSuccess = Response{0, "success"} ResponseSuccess = Response{0, "success"}
ResponseNotFound = Response{1, "not found"} ResponseNotFound = Response{1, "not found"}
ResponseAlreadyConnected = Response{2, "already connected"} ResponseAlreadyConnected = Response{2, "already connected"}
ResponseInternalError = Response{99, "internal error"}
ResponseUnexpectedMessage = Response{100, "unexpected message"} ResponseUnexpectedMessage = Response{100, "unexpected message"}
) )

View File

@ -28,11 +28,6 @@ const (
minioImpl = "minio/sha256-simd" minioImpl = "minio/sha256-simd"
) )
const (
BlockSize = cryptoSha256.BlockSize
Size = cryptoSha256.Size
)
// May be switched out for another implementation // May be switched out for another implementation
var ( var (
New = cryptoSha256.New New = cryptoSha256.New

View File

@ -47,9 +47,14 @@ const (
type ExitStatus int type ExitStatus int
func (s ExitStatus) AsInt() int {
return int(s)
}
const ( const (
ExitSuccess ExitStatus = 0 ExitSuccess ExitStatus = 0
ExitError ExitStatus = 1 ExitError ExitStatus = 1
ExitNoUpgradeAvailable ExitStatus = 2
ExitRestart ExitStatus = 3 ExitRestart ExitStatus = 3
ExitUpgrade ExitStatus = 4 ExitUpgrade ExitStatus = 4
) )

View File

@ -37,7 +37,6 @@ type Asset struct {
} }
var ( var (
ErrVersionUpToDate = errors.New("current version is up to date")
ErrNoReleaseDownload = errors.New("couldn't find a release to download") ErrNoReleaseDownload = errors.New("couldn't find a release to download")
ErrNoVersionToSelect = errors.New("no version to select") ErrNoVersionToSelect = errors.New("no version to select")
ErrUpgradeUnsupported = errors.New("upgrade unsupported") ErrUpgradeUnsupported = errors.New("upgrade unsupported")