Skip to content

Commit

Permalink
global variable to control NaN allowed
Browse files Browse the repository at this point in the history
  • Loading branch information
chilagrow committed Aug 2, 2024
1 parent 0d5623f commit 531c946
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 3 deletions.
18 changes: 15 additions & 3 deletions op_msg.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ import (
"github.com/FerretDB/wire/wirebson"
)

// AllowNan false returns error when float64 nan is present in wire messages.
var AllowNan = true

// OpMsg is the main wire protocol message type.
type OpMsg struct {
// The order of fields is weird to make the struct smaller due to alignment.
Expand Down Expand Up @@ -72,7 +75,7 @@ func (msg *OpMsg) SetSections(sections ...OpMsgSection) error {

msg.sections = sections

if debugbuild {
if debugbuild || !AllowNan {
if err := msg.check(); err != nil {
return lazyerrors.Error(err)
}
Expand Down Expand Up @@ -135,9 +138,18 @@ func (msg *OpMsg) msgbody() {}
func (msg *OpMsg) check() error {
for _, s := range msg.sections {
for _, d := range s.documents {
if _, err := d.DecodeDeep(); err != nil {
doc, err := d.DecodeDeep()
if err != nil {
return lazyerrors.Error(err)
}

if AllowNan {
continue
}

if err = validateNan(doc); err != nil {
return err
}
}
}

Expand Down Expand Up @@ -241,7 +253,7 @@ func (msg *OpMsg) UnmarshalBinaryNocopy(b []byte) error {
return lazyerrors.Error(err)
}

if debugbuild {
if debugbuild || !AllowNan {
if err := msg.check(); err != nil {
return lazyerrors.Error(err)
}
Expand Down
47 changes: 47 additions & 0 deletions validation.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
// Copyright 2021 FerretDB Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package wire

import (
"errors"
"github.com/FerretDB/wire/wirebson"
"math"
)

// validateNan returns error if float Nan was encountered.
func validateNan(v any) error {
switch v := v.(type) {
case *wirebson.Document:
for _, f := range v.FieldNames() {
if err := validateNan(v.Get(f)); err != nil {
return err
}
}

case *wirebson.Array:
for i := range v.Len() {
if err := validateNan(v.Get(i)); err != nil {
return err
}
}

case float64:
if math.IsNaN(v) {
return errors.New("NaN is not supported")
}
}

return nil
}

0 comments on commit 531c946

Please sign in to comment.