From 7d3cc06204e5bfe7f389feb902a11574313d15c8 Mon Sep 17 00:00:00 2001 From: Gaylor Bosson Date: Sun, 3 Dec 2023 19:07:55 +0100 Subject: [PATCH] Fix some possible bad array indexes --- error.go | 4 +++- parser.go | 15 ++++++++++++++- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/error.go b/error.go index cc3b680..2b06f66 100644 --- a/error.go +++ b/error.go @@ -6,6 +6,8 @@ import ( ) var ( + ErrMalformedExpression = errors.New("expression is malformed") + ErrMalformedField = errors.New("unexpected field value") ErrMultipleNotSpecified = errors.New("only one `?` is supported") ErrValueOutsideRange = errors.New("values are outside the supported range") ) @@ -52,5 +54,5 @@ const ( var kinds = []string{"seconds", "minutes", "hours", "days", "months", "week days"} func (k TimeUnitKind) String() string { - return kinds[k] + return kinds[int(k)%len(kinds)] } diff --git a/parser.go b/parser.go index 5af3046..5bbf19e 100644 --- a/parser.go +++ b/parser.go @@ -11,6 +11,9 @@ type Parser struct{} func (p Parser) Parse(expression string) (schedule Schedule, err error) { matches := strings.Split(expression, " ") + if len(matches) != 6 { + return schedule, ErrMalformedExpression + } weekdays, err := p.parse(matches[5], convertWeekDay, 0, 6) if err != nil { @@ -90,6 +93,11 @@ func (Parser) parse(expr string, convFn converterFn, min, max int) (fields []exp func parseRange(expr string, convFn converterFn) (r rangeExpr, err error) { parts := strings.Split(expr, "-") + if len(parts) != 2 { + err = ErrMalformedField + return + } + r.from, err = convFn(parts[0]) if err != nil { return @@ -104,6 +112,10 @@ func parseRange(expr string, convFn converterFn) (r rangeExpr, err error) { func parseInterval(expr string, convFn converterFn, min, max int) (i intervalExpr, err error) { parts := strings.Split(expr, "/") + if len(parts) != 2 { + err = ErrMalformedField + return + } i.incr, err = strconv.Atoi(parts[1]) if err != nil { @@ -277,7 +289,8 @@ func (l lastWeekDayOfMonthExpr) Value(t time.Time, _ int) int { lastDayOfMonth := findLastDayOfMonth(t) diff := int(lastDayOfMonth.Weekday() - l.weekday) if diff < 0 { - diff += 7 + // Add a week length to get a positive value. + diff += int(time.Saturday) + 1 } return lastDayOfMonth.Day() - diff }