Skip to content

Commit

Permalink
fix overflow integer conversion lint warning from gosec (#399)
Browse files Browse the repository at this point in the history
* fix overflow integer conversion lint warning from gosec

* fix integer conversion for linux and windows builds

* fix type in tests

* use binary shift to compute power of 2
  • Loading branch information
creativeprojects authored Aug 25, 2024
1 parent 3612b51 commit 4181d9e
Show file tree
Hide file tree
Showing 17 changed files with 107 additions and 40 deletions.
19 changes: 19 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -278,10 +278,12 @@ generate-config-reference: build
LAYOUT_UPLINK="[go to top](#reference)" \
$(abspath $(BINARY)) generate --config-reference --to $(CONFIG_REFERENCE_DIR)

.PHONY: documentation
documentation: generate-jsonschema generate-config-reference
@echo "[*] $@"
cd docs && hugo --minify

.PHONY: syslog-ng
syslog-ng:
@echo "[*] $@"
docker run -d \
Expand All @@ -300,6 +302,23 @@ checkdoc:
@echo "[*] $@"
$(GOCMD) run ./config/checkdoc -r docs/content

.PHONY: checklinks
checklinks:
@echo "[*] $@"
muffet -b 8192 --exclude="(linux.die.net|stackoverflow.com)" http://localhost:1313/resticprofile/

.PHONY: lint
lint:
@echo "[*] $@"
GOOS=darwin golangci-lint run
GOOS=linux golangci-lint run
GOOS=windows golangci-lint run

.PHONY: fix
fix:
@echo "[*] $@"
$(GOCMD) mod tidy
$(GOCMD) fix ./...
GOOS=darwin golangci-lint run --fix
GOOS=linux golangci-lint run --fix
GOOS=windows golangci-lint run --fix
2 changes: 1 addition & 1 deletion filesearch/filesearch_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,7 @@ func TestShellExpand(t *testing.T) {
func TestFindConfigurationIncludes(t *testing.T) {
t.Parallel()

testID := fmt.Sprintf("%d", uint32(time.Now().UnixNano()))
testID := fmt.Sprintf("%x", time.Now().UnixNano())
tempDir := os.TempDir()
files := []string{
filepath.Join(tempDir, "base."+testID+".conf"),
Expand Down
6 changes: 3 additions & 3 deletions lock/lock.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import (
)

// SetPID is a callback that writes the PID in the lockfile
type SetPID func(pid int)
type SetPID func(pid int32)

// Lock prevents code to run at the same time by using a lockfile
type Lock struct {
Expand Down Expand Up @@ -83,7 +83,7 @@ func (l *Lock) Who() (string, error) {

// SetPID writes down the PID in the lock file.
// You can run the method as many times as you want when the PID changes
func (l *Lock) SetPID(pid int) {
func (l *Lock) SetPID(pid int32) {
if !l.locked {
return
}
Expand All @@ -109,7 +109,7 @@ func (l *Lock) LastPID() (int32, error) {
if contents[i] != "" {
pid, err := strconv.ParseInt(contents[i], 10, 32)
if err == nil {
return int32(pid), nil
return int32(pid), nil //nolint:gosec
}
}
}
Expand Down
10 changes: 5 additions & 5 deletions lock/lock_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,24 +130,24 @@ func TestSetMorePID(t *testing.T) {
func TestProcessPID(t *testing.T) {
t.Parallel()

childPID := 0
var childPID int32
buffer := &bytes.Buffer{}

// use the lock helper binary (we only need to wait for some time, we don't need the locking part)
cmd := shell.NewCommand(helperBinary, []string{"-wait", "200", "-lock", filepath.Join(t.TempDir(), t.Name())})
cmd.Stdout = buffer
// SetPID method is called right after we forked and have a PID available
cmd.SetPID = func(pid int) {
cmd.SetPID = func(pid int32) {
childPID = pid
running, err := process.PidExists(int32(childPID))
running, err := process.PidExists(childPID)
assert.NoError(t, err)
assert.True(t, running)
}
_, _, err := cmd.Run()
require.NoError(t, err)

// at that point, the child process should be finished
running, err := process.PidExists(int32(childPID))
running, err := process.PidExists(childPID)
assert.NoError(t, err)
assert.False(t, running)
}
Expand Down Expand Up @@ -220,7 +220,7 @@ func TestForceLockWithRunningPID(t *testing.T) {

// user the lock helper binary (we only need to wait for some time, we don't need the locking part)
cmd := shell.NewCommand(helperBinary, []string{"-wait", "100", "-lock", filepath.Join(t.TempDir(), t.Name())})
cmd.SetPID = func(pid int) {
cmd.SetPID = func(pid int32) {
lock.SetPID(pid)
// make sure we cannot break the lock right now
other := NewLock(tempfile)
Expand Down
6 changes: 3 additions & 3 deletions priority/ioprio_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,9 @@ func getIOPrio(who IOPrioWho) (IOPrioClass, int, error) {
if errno != 0 {
return 0, 0, errnoToError(errno)
}
class := r1 >> IOPrioClassShift
value := r1 & IOPrioMask
return IOPrioClass(class), int(value), nil
class := IOPrioClass(r1 >> IOPrioClassShift) //nolint:gosec
value := int(r1 & IOPrioMask) //nolint:gosec
return class, value, nil
}

func setIOPrio(who IOPrioWho, class IOPrioClass, value int) error {
Expand Down
2 changes: 1 addition & 1 deletion schedule/tree_darwin.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//+build darwin
//go:build darwin

package schedule

Expand Down
1 change: 0 additions & 1 deletion schedule/tree_darwin_test.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
//go:build darwin
// +build darwin

package schedule

Expand Down
27 changes: 15 additions & 12 deletions schtasks/taskscheduler.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ package schtasks
import (
"errors"
"fmt"
"math"
"os/user"
"strings"
"text/tabwriter"
Expand Down Expand Up @@ -589,18 +588,18 @@ func compileDifferences(recurrences []time.Time) ([]time.Duration, []time.Durati
return differences, compactDifferences
}

func convertWeekdaysToBitmap(weekdays []int) int {
func convertWeekdaysToBitmap(weekdays []int) uint16 {
if len(weekdays) == 0 {
return 0
}
bitmap := 0
var bitmap uint16
for _, weekday := range weekdays {
bitmap |= getWeekdayBit(weekday)
}
return bitmap
}

func getWeekdayBit(weekday int) int {
func getWeekdayBit(weekday int) uint16 {
switch weekday {
case 0:
return 1
Expand All @@ -623,32 +622,36 @@ func getWeekdayBit(weekday int) int {
return 0
}

func convertMonthsToBitmap(months []int) int {
func convertMonthsToBitmap(months []int) uint16 {
if months == nil {
return 0
}
if len(months) == 0 {
// all values
return int(math.Exp2(12)) - 1
return (1 << 12) - 1
}
bitmap := 0
var bitmap uint16
for _, month := range months {
bitmap |= int(math.Exp2(float64(month - 1)))
if month > 0 && month <= 12 {
bitmap |= 1 << (month - 1)
}
}
return bitmap
}

func convertDaysToBitmap(days []int) int {
func convertDaysToBitmap(days []int) uint32 {
if days == nil {
return 0
}
if len(days) == 0 {
// every day
return int(math.Exp2(31)) - 1
return (1 << 31) - 1
}
bitmap := 0
var bitmap uint32
for _, day := range days {
bitmap |= int(math.Exp2(float64(day - 1)))
if day > 0 && day <= 31 {
bitmap |= 1 << (day - 1)
}
}
return bitmap
}
Expand Down
47 changes: 45 additions & 2 deletions schtasks/taskscheduler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ package schtasks

import (
"bytes"
"math"
"os/exec"
"regexp"
"strconv"
Expand All @@ -22,7 +23,7 @@ import (
func TestConversionWeekdaysToBitmap(t *testing.T) {
testData := []struct {
weekdays []int
bitmap int
bitmap uint16
}{
{nil, 0},
{[]int{}, 0},
Expand All @@ -40,6 +41,48 @@ func TestConversionWeekdaysToBitmap(t *testing.T) {
}
}

func TestConversionMonthsToBitmap(t *testing.T) {
testData := []struct {
months []int
bitmap uint16
}{
{nil, 0},
{[]int{}, 4095}, // every month
{[]int{0}, 0},
{[]int{1}, 1},
{[]int{2}, 2},
{[]int{7}, 64},
{[]int{1, 2, 3, 4, 5, 6, 7}, 127},
{[]int{0, 1, 2, 3, 4, 5, 6, 7}, 127},
{[]int{1, 2, 3, 4, 5, 6}, 63},
}

for _, testItem := range testData {
assert.Equal(t, testItem.bitmap, convertMonthsToBitmap(testItem.months))
}
}

func TestConversionDaysToBitmap(t *testing.T) {
testData := []struct {
days []int
bitmap uint32
}{
{nil, 0},
{[]int{}, math.MaxInt32}, // every day
{[]int{0}, 0},
{[]int{1}, 1},
{[]int{2}, 2},
{[]int{7}, 64},
{[]int{1, 2, 3, 4, 5, 6, 7}, 127},
{[]int{0, 1, 2, 3, 4, 5, 6, 7}, 127},
{[]int{1, 2, 3, 4, 5, 6}, 63},
}

for _, testItem := range testData {
assert.Equal(t, testItem.bitmap, convertDaysToBitmap(testItem.days))
}
}

func TestCompileDifferences(t *testing.T) {
testData := []struct {
input string
Expand Down Expand Up @@ -111,7 +154,7 @@ func TestTaskSchedulerConversion(t *testing.T) {
// 3rd task will be a weekly recurring
weeklyEvent, ok := task.Triggers[2].(taskmaster.WeeklyTrigger)
require.True(t, ok)
assert.Equal(t, getWeekdayBit(int(time.Saturday))+getWeekdayBit(int(time.Sunday)), int(weeklyEvent.DaysOfWeek))
assert.Equal(t, getWeekdayBit(int(time.Saturday))+getWeekdayBit(int(time.Sunday)), uint16(weeklyEvent.DaysOfWeek))

// 4th task will be a monthly recurring
monthlyEvent, ok := task.Triggers[3].(taskmaster.MonthlyTrigger)
Expand Down
4 changes: 2 additions & 2 deletions shell/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ const (
)

// SetPID is a callback to send the PID of the current child process
type SetPID func(pid int)
type SetPID func(pid int32)

// ScanOutput is a callback to scan the default output of the command
// The implementation is expected to send everything read from the reader back to the writer
Expand Down Expand Up @@ -124,7 +124,7 @@ func (c *Command) Run() (monitor.Summary, string, error) {
}
if c.SetPID != nil {
// send the PID back (to write down in a lockfile)
c.SetPID(cmd.Process.Pid)
c.SetPID(int32(cmd.Process.Pid)) //nolint:gosec
}
// setup the OS signalling if we need it (typically used for unixes but not windows)
if c.sigChan != nil {
Expand Down
4 changes: 2 additions & 2 deletions shell/command_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -399,7 +399,7 @@ func TestSetPIDCallback(t *testing.T) {
buffer := &bytes.Buffer{}
cmd := NewCommand("echo", []string{t.Name()})
cmd.Stdout = buffer
cmd.SetPID = func(pid int) {
cmd.SetPID = func(pid int32) {
called++
}
_, _, err := cmd.Run()
Expand All @@ -420,7 +420,7 @@ func TestSetPIDCallbackWithSignalling(t *testing.T) {

cmd := NewSignalledCommand("echo", []string{t.Name()}, c)
cmd.Stdout = buffer
cmd.SetPID = func(pid int) {
cmd.SetPID = func(pid int32) {
called++
}
_, _, err := cmd.Run()
Expand Down
2 changes: 1 addition & 1 deletion shell_command.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ type shellCommandDefinition struct {
}

// newShellCommand creates a new shell command definition
func newShellCommand(command string, args, env, shell []string, dryRun bool, sigChan chan os.Signal, setPID func(pid int)) shellCommandDefinition {
func newShellCommand(command string, args, env, shell []string, dryRun bool, sigChan chan os.Signal, setPID func(pid int32)) shellCommandDefinition {
if env == nil {
env = make([]string, 0)
}
Expand Down
10 changes: 7 additions & 3 deletions term/term.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ func AskYesNo(reader io.Reader, message string, defaultAnswer bool) bool {

// ReadPassword reads a password without echoing it to the terminal.
func ReadPassword() (string, error) {
stdin := int(os.Stdin.Fd())
stdin := fdToInt(os.Stdin.Fd())
if !term.IsTerminal(stdin) {
return ReadLine()
}
Expand All @@ -82,13 +82,13 @@ func ReadLine() (string, error) {

// OsStdoutIsTerminal returns true as os.Stdout is a terminal session
func OsStdoutIsTerminal() bool {
fd := int(os.Stdout.Fd())
fd := fdToInt(os.Stdout.Fd())
return term.IsTerminal(fd)
}

// OsStdoutIsTerminal returns true as os.Stdout is a terminal session
func OsStdoutTerminalSize() (width, height int) {
fd := int(os.Stdout.Fd())
fd := fdToInt(os.Stdout.Fd())
var err error
width, height, err = term.GetSize(fd)
if err != nil {
Expand All @@ -97,6 +97,10 @@ func OsStdoutTerminalSize() (width, height int) {
return
}

func fdToInt(fd uintptr) int {
return int(fd) //nolint:gosec
}

type LockedWriter struct {
writer io.Writer
mutex *sync.Mutex
Expand Down
2 changes: 1 addition & 1 deletion util/templates/functions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ func TestTemplateFuncs(t *testing.T) {
})

t.Run("envFileFunc", func(t *testing.T) {
profileKey := fmt.Sprintf("prof-%d", int(rand.Uint64()))
profileKey := fmt.Sprintf("prof-%x", rand.Uint64())
expectedFile := TempFile(fmt.Sprintf("%s.env", profileKey))

var received []string
Expand Down
2 changes: 1 addition & 1 deletion win/other.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// +build !windows
//go:build !windows

package win

Expand Down
1 change: 0 additions & 1 deletion win/windows.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
//go:build windows
// +build windows

package win

Expand Down
2 changes: 1 addition & 1 deletion wrapper.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ type resticWrapper struct {
command string
moreArgs []string
sigChan chan os.Signal
setPID func(pid int)
setPID func(pid int32)
stdin io.ReadCloser
progress []monitor.Receiver
sender *hook.Sender
Expand Down

0 comments on commit 4181d9e

Please sign in to comment.