decode.go 103 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318
  1. // Copyright (c) Faye Amacker. All rights reserved.
  2. // Licensed under the MIT License. See LICENSE in the project root for license information.
  3. package cbor
  4. import (
  5. "bytes"
  6. "encoding"
  7. "encoding/base64"
  8. "encoding/binary"
  9. "encoding/hex"
  10. "errors"
  11. "fmt"
  12. "io"
  13. "math"
  14. "math/big"
  15. "reflect"
  16. "strconv"
  17. "strings"
  18. "time"
  19. "unicode/utf8"
  20. "github.com/x448/float16"
  21. )
  22. // Unmarshal parses the CBOR-encoded data into the value pointed to by v
  23. // using default decoding options. If v is nil, not a pointer, or
  24. // a nil pointer, Unmarshal returns an error.
  25. //
  26. // To unmarshal CBOR into a value implementing the Unmarshaler interface,
  27. // Unmarshal calls that value's UnmarshalCBOR method with a valid
  28. // CBOR value.
  29. //
  30. // To unmarshal CBOR byte string into a value implementing the
  31. // encoding.BinaryUnmarshaler interface, Unmarshal calls that value's
  32. // UnmarshalBinary method with decoded CBOR byte string.
  33. //
  34. // To unmarshal CBOR into a pointer, Unmarshal sets the pointer to nil
  35. // if CBOR data is null (0xf6) or undefined (0xf7). Otherwise, Unmarshal
  36. // unmarshals CBOR into the value pointed to by the pointer. If the
  37. // pointer is nil, Unmarshal creates a new value for it to point to.
  38. //
  39. // To unmarshal CBOR into an empty interface value, Unmarshal uses the
  40. // following rules:
  41. //
  42. // CBOR booleans decode to bool.
  43. // CBOR positive integers decode to uint64.
  44. // CBOR negative integers decode to int64 (big.Int if value overflows).
  45. // CBOR floating points decode to float64.
  46. // CBOR byte strings decode to []byte.
  47. // CBOR text strings decode to string.
  48. // CBOR arrays decode to []interface{}.
  49. // CBOR maps decode to map[interface{}]interface{}.
  50. // CBOR null and undefined values decode to nil.
  51. // CBOR times (tag 0 and 1) decode to time.Time.
  52. // CBOR bignums (tag 2 and 3) decode to big.Int.
  53. // CBOR tags with an unrecognized number decode to cbor.Tag
  54. //
  55. // To unmarshal a CBOR array into a slice, Unmarshal allocates a new slice
  56. // if the CBOR array is empty or slice capacity is less than CBOR array length.
  57. // Otherwise Unmarshal overwrites existing elements, and sets slice length
  58. // to CBOR array length.
  59. //
  60. // To unmarshal a CBOR array into a Go array, Unmarshal decodes CBOR array
  61. // elements into Go array elements. If the Go array is smaller than the
  62. // CBOR array, the extra CBOR array elements are discarded. If the CBOR
  63. // array is smaller than the Go array, the extra Go array elements are
  64. // set to zero values.
  65. //
  66. // To unmarshal a CBOR array into a struct, struct must have a special field "_"
  67. // with struct tag `cbor:",toarray"`. Go array elements are decoded into struct
  68. // fields. Any "omitempty" struct field tag option is ignored in this case.
  69. //
  70. // To unmarshal a CBOR map into a map, Unmarshal allocates a new map only if the
  71. // map is nil. Otherwise Unmarshal reuses the existing map and keeps existing
  72. // entries. Unmarshal stores key-value pairs from the CBOR map into Go map.
  73. // See DecOptions.DupMapKey to enable duplicate map key detection.
  74. //
  75. // To unmarshal a CBOR map into a struct, Unmarshal matches CBOR map keys to the
  76. // keys in the following priority:
  77. //
  78. // 1. "cbor" key in struct field tag,
  79. // 2. "json" key in struct field tag,
  80. // 3. struct field name.
  81. //
  82. // Unmarshal tries an exact match for field name, then a case-insensitive match.
  83. // Map key-value pairs without corresponding struct fields are ignored. See
  84. // DecOptions.ExtraReturnErrors to return error at unknown field.
  85. //
  86. // To unmarshal a CBOR text string into a time.Time value, Unmarshal parses text
  87. // string formatted in RFC3339. To unmarshal a CBOR integer/float into a
  88. // time.Time value, Unmarshal creates an unix time with integer/float as seconds
  89. // and fractional seconds since January 1, 1970 UTC. As a special case, Infinite
  90. // and NaN float values decode to time.Time's zero value.
  91. //
  92. // To unmarshal CBOR null (0xf6) and undefined (0xf7) values into a
  93. // slice/map/pointer, Unmarshal sets Go value to nil. Because null is often
  94. // used to mean "not present", unmarshaling CBOR null and undefined value
  95. // into any other Go type has no effect and returns no error.
  96. //
  97. // Unmarshal supports CBOR tag 55799 (self-describe CBOR), tag 0 and 1 (time),
  98. // and tag 2 and 3 (bignum).
  99. //
  100. // Unmarshal returns ExtraneousDataError error (without decoding into v)
  101. // if there are any remaining bytes following the first valid CBOR data item.
  102. // See UnmarshalFirst, if you want to unmarshal only the first
  103. // CBOR data item without ExtraneousDataError caused by remaining bytes.
  104. func Unmarshal(data []byte, v any) error {
  105. return defaultDecMode.Unmarshal(data, v)
  106. }
  107. // UnmarshalFirst parses the first CBOR data item into the value pointed to by v
  108. // using default decoding options. Any remaining bytes are returned in rest.
  109. //
  110. // If v is nil, not a pointer, or a nil pointer, UnmarshalFirst returns an error.
  111. //
  112. // See the documentation for Unmarshal for details.
  113. func UnmarshalFirst(data []byte, v any) (rest []byte, err error) {
  114. return defaultDecMode.UnmarshalFirst(data, v)
  115. }
  116. // Valid checks whether data is a well-formed encoded CBOR data item and
  117. // that it complies with default restrictions such as MaxNestedLevels,
  118. // MaxArrayElements, MaxMapPairs, etc.
  119. //
  120. // If there are any remaining bytes after the CBOR data item,
  121. // an ExtraneousDataError is returned.
  122. //
  123. // WARNING: Valid doesn't check if encoded CBOR data item is valid (i.e. validity)
  124. // and RFC 8949 distinctly defines what is "Valid" and what is "Well-formed".
  125. //
  126. // Deprecated: Valid is kept for compatibility and should not be used.
  127. // Use Wellformed instead because it has a more appropriate name.
  128. func Valid(data []byte) error {
  129. return defaultDecMode.Valid(data)
  130. }
  131. // Wellformed checks whether data is a well-formed encoded CBOR data item and
  132. // that it complies with default restrictions such as MaxNestedLevels,
  133. // MaxArrayElements, MaxMapPairs, etc.
  134. //
  135. // If there are any remaining bytes after the CBOR data item,
  136. // an ExtraneousDataError is returned.
  137. func Wellformed(data []byte) error {
  138. return defaultDecMode.Wellformed(data)
  139. }
  140. // Unmarshaler is the interface implemented by types that wish to unmarshal
  141. // CBOR data themselves. The input is a valid CBOR value. UnmarshalCBOR
  142. // must copy the CBOR data if it needs to use it after returning.
  143. type Unmarshaler interface {
  144. UnmarshalCBOR([]byte) error
  145. }
  146. type unmarshaler interface {
  147. unmarshalCBOR([]byte) error
  148. }
  149. // InvalidUnmarshalError describes an invalid argument passed to Unmarshal.
  150. type InvalidUnmarshalError struct {
  151. s string
  152. }
  153. func (e *InvalidUnmarshalError) Error() string {
  154. return e.s
  155. }
  156. // UnmarshalTypeError describes a CBOR value that can't be decoded to a Go type.
  157. type UnmarshalTypeError struct {
  158. CBORType string // type of CBOR value
  159. GoType string // type of Go value it could not be decoded into
  160. StructFieldName string // name of the struct field holding the Go value (optional)
  161. errorMsg string // additional error message (optional)
  162. }
  163. func (e *UnmarshalTypeError) Error() string {
  164. var s string
  165. if e.StructFieldName != "" {
  166. s = "cbor: cannot unmarshal " + e.CBORType + " into Go struct field " + e.StructFieldName + " of type " + e.GoType
  167. } else {
  168. s = "cbor: cannot unmarshal " + e.CBORType + " into Go value of type " + e.GoType
  169. }
  170. if e.errorMsg != "" {
  171. s += " (" + e.errorMsg + ")"
  172. }
  173. return s
  174. }
  175. // InvalidMapKeyTypeError describes invalid Go map key type when decoding CBOR map.
  176. // For example, Go doesn't allow slice as map key.
  177. type InvalidMapKeyTypeError struct {
  178. GoType string
  179. }
  180. func (e *InvalidMapKeyTypeError) Error() string {
  181. return "cbor: invalid map key type: " + e.GoType
  182. }
  183. // DupMapKeyError describes detected duplicate map key in CBOR map.
  184. type DupMapKeyError struct {
  185. Key any
  186. Index int
  187. }
  188. func (e *DupMapKeyError) Error() string {
  189. return fmt.Sprintf("cbor: found duplicate map key %#v at map element index %d", e.Key, e.Index)
  190. }
  191. // UnknownFieldError describes detected unknown field in CBOR map when decoding to Go struct.
  192. type UnknownFieldError struct {
  193. Index int
  194. }
  195. func (e *UnknownFieldError) Error() string {
  196. return fmt.Sprintf("cbor: found unknown field at map element index %d", e.Index)
  197. }
  198. // UnacceptableDataItemError is returned when unmarshaling a CBOR input that contains a data item
  199. // that is not acceptable to a specific CBOR-based application protocol ("invalid or unexpected" as
  200. // described in RFC 8949 Section 5 Paragraph 3).
  201. type UnacceptableDataItemError struct {
  202. CBORType string
  203. Message string
  204. }
  205. func (e UnacceptableDataItemError) Error() string {
  206. return fmt.Sprintf("cbor: data item of cbor type %s is not accepted by protocol: %s", e.CBORType, e.Message)
  207. }
  208. // ByteStringExpectedFormatError is returned when unmarshaling CBOR byte string fails when
  209. // using non-default ByteStringExpectedFormat decoding option that makes decoder expect
  210. // a specified format such as base64, hex, etc.
  211. type ByteStringExpectedFormatError struct {
  212. expectedFormatOption ByteStringExpectedFormatMode
  213. err error
  214. }
  215. func newByteStringExpectedFormatError(expectedFormatOption ByteStringExpectedFormatMode, err error) *ByteStringExpectedFormatError {
  216. return &ByteStringExpectedFormatError{expectedFormatOption, err}
  217. }
  218. func (e *ByteStringExpectedFormatError) Error() string {
  219. switch e.expectedFormatOption {
  220. case ByteStringExpectedBase64URL:
  221. return fmt.Sprintf("cbor: failed to decode base64url from byte string: %s", e.err)
  222. case ByteStringExpectedBase64:
  223. return fmt.Sprintf("cbor: failed to decode base64 from byte string: %s", e.err)
  224. case ByteStringExpectedBase16:
  225. return fmt.Sprintf("cbor: failed to decode hex from byte string: %s", e.err)
  226. default:
  227. return fmt.Sprintf("cbor: failed to decode byte string in expected format %d: %s", e.expectedFormatOption, e.err)
  228. }
  229. }
  230. func (e *ByteStringExpectedFormatError) Unwrap() error {
  231. return e.err
  232. }
  233. // InadmissibleTagContentTypeError is returned when unmarshaling built-in CBOR tags
  234. // fails because of inadmissible type for tag content. Currently, the built-in
  235. // CBOR tags in this codec are tags 0-3 and 21-23.
  236. // See "Tag validity" in RFC 8949 Section 5.3.2.
  237. type InadmissibleTagContentTypeError struct {
  238. s string
  239. tagNum int
  240. expectedTagContentType string
  241. gotTagContentType string
  242. }
  243. func newInadmissibleTagContentTypeError(
  244. tagNum int,
  245. expectedTagContentType string,
  246. gotTagContentType string,
  247. ) *InadmissibleTagContentTypeError {
  248. return &InadmissibleTagContentTypeError{
  249. tagNum: tagNum,
  250. expectedTagContentType: expectedTagContentType,
  251. gotTagContentType: gotTagContentType,
  252. }
  253. }
  254. func newInadmissibleTagContentTypeErrorf(s string) *InadmissibleTagContentTypeError {
  255. return &InadmissibleTagContentTypeError{s: "cbor: " + s} //nolint:goconst // ignore "cbor"
  256. }
  257. func (e *InadmissibleTagContentTypeError) Error() string {
  258. if e.s == "" {
  259. return fmt.Sprintf(
  260. "cbor: tag number %d must be followed by %s, got %s",
  261. e.tagNum,
  262. e.expectedTagContentType,
  263. e.gotTagContentType,
  264. )
  265. }
  266. return e.s
  267. }
  268. // DupMapKeyMode specifies how to enforce duplicate map key. Two map keys are considered duplicates if:
  269. // 1. When decoding into a struct, both keys match the same struct field. The keys are also
  270. // considered duplicates if neither matches any field and decoding to interface{} would produce
  271. // equal (==) values for both keys.
  272. // 2. When decoding into a map, both keys are equal (==) when decoded into values of the
  273. // destination map's key type.
  274. type DupMapKeyMode int
  275. const (
  276. // DupMapKeyQuiet doesn't enforce duplicate map key. Decoder quietly (no error)
  277. // uses faster of "keep first" or "keep last" depending on Go data type and other factors.
  278. DupMapKeyQuiet DupMapKeyMode = iota
  279. // DupMapKeyEnforcedAPF enforces detection and rejection of duplicate map keys.
  280. // APF means "Allow Partial Fill" and the destination map or struct can be partially filled.
  281. // If a duplicate map key is detected, DupMapKeyError is returned without further decoding
  282. // of the map. It's the caller's responsibility to respond to DupMapKeyError by
  283. // discarding the partially filled result if their protocol requires it.
  284. // WARNING: using DupMapKeyEnforcedAPF will decrease performance and increase memory use.
  285. DupMapKeyEnforcedAPF
  286. maxDupMapKeyMode
  287. )
  288. func (dmkm DupMapKeyMode) valid() bool {
  289. return dmkm >= 0 && dmkm < maxDupMapKeyMode
  290. }
  291. // IndefLengthMode specifies whether to allow indefinite length items.
  292. type IndefLengthMode int
  293. const (
  294. // IndefLengthAllowed allows indefinite length items.
  295. IndefLengthAllowed IndefLengthMode = iota
  296. // IndefLengthForbidden disallows indefinite length items.
  297. IndefLengthForbidden
  298. maxIndefLengthMode
  299. )
  300. func (m IndefLengthMode) valid() bool {
  301. return m >= 0 && m < maxIndefLengthMode
  302. }
  303. // TagsMode specifies whether to allow CBOR tags.
  304. type TagsMode int
  305. const (
  306. // TagsAllowed allows CBOR tags.
  307. TagsAllowed TagsMode = iota
  308. // TagsForbidden disallows CBOR tags.
  309. TagsForbidden
  310. maxTagsMode
  311. )
  312. func (tm TagsMode) valid() bool {
  313. return tm >= 0 && tm < maxTagsMode
  314. }
  315. // IntDecMode specifies which Go type (int64, uint64, or big.Int) should
  316. // be used when decoding CBOR integers (major type 0 and 1) to Go interface{}.
  317. type IntDecMode int
  318. const (
  319. // IntDecConvertNone affects how CBOR integers (major type 0 and 1) decode to Go interface{}.
  320. // It decodes CBOR unsigned integer (major type 0) to:
  321. // - uint64
  322. // It decodes CBOR negative integer (major type 1) to:
  323. // - int64 if value fits
  324. // - big.Int or *big.Int (see BigIntDecMode) if value doesn't fit into int64
  325. IntDecConvertNone IntDecMode = iota
  326. // IntDecConvertSigned affects how CBOR integers (major type 0 and 1) decode to Go interface{}.
  327. // It decodes CBOR integers (major type 0 and 1) to:
  328. // - int64 if value fits
  329. // - big.Int or *big.Int (see BigIntDecMode) if value < math.MinInt64
  330. // - return UnmarshalTypeError if value > math.MaxInt64
  331. // Deprecated: IntDecConvertSigned should not be used.
  332. // Please use other options, such as IntDecConvertSignedOrError, IntDecConvertSignedOrBigInt, IntDecConvertNone.
  333. IntDecConvertSigned
  334. // IntDecConvertSignedOrFail affects how CBOR integers (major type 0 and 1) decode to Go interface{}.
  335. // It decodes CBOR integers (major type 0 and 1) to:
  336. // - int64 if value fits
  337. // - return UnmarshalTypeError if value doesn't fit into int64
  338. IntDecConvertSignedOrFail
  339. // IntDecConvertSignedOrBigInt affects how CBOR integers (major type 0 and 1) decode to Go interface{}.
  340. // It makes CBOR integers (major type 0 and 1) decode to:
  341. // - int64 if value fits
  342. // - big.Int or *big.Int (see BigIntDecMode) if value doesn't fit into int64
  343. IntDecConvertSignedOrBigInt
  344. maxIntDec
  345. )
  346. func (idm IntDecMode) valid() bool {
  347. return idm >= 0 && idm < maxIntDec
  348. }
  349. // MapKeyByteStringMode specifies how to decode CBOR byte string (major type 2)
  350. // as Go map key when decoding CBOR map key into an empty Go interface value.
  351. // Specifically, this option applies when decoding CBOR map into
  352. // - Go empty interface, or
  353. // - Go map with empty interface as key type.
  354. // The CBOR map key types handled by this option are
  355. // - byte string
  356. // - tagged byte string
  357. // - nested tagged byte string
  358. type MapKeyByteStringMode int
  359. const (
  360. // MapKeyByteStringAllowed allows CBOR byte string to be decoded as Go map key.
  361. // Since Go doesn't allow []byte as map key, CBOR byte string is decoded to
  362. // ByteString which has underlying string type.
  363. // This is the default setting.
  364. MapKeyByteStringAllowed MapKeyByteStringMode = iota
  365. // MapKeyByteStringForbidden forbids CBOR byte string being decoded as Go map key.
  366. // Attempting to decode CBOR byte string as map key into empty interface value
  367. // returns a decoding error.
  368. MapKeyByteStringForbidden
  369. maxMapKeyByteStringMode
  370. )
  371. func (mkbsm MapKeyByteStringMode) valid() bool {
  372. return mkbsm >= 0 && mkbsm < maxMapKeyByteStringMode
  373. }
  374. // ExtraDecErrorCond specifies extra conditions that should be treated as errors.
  375. type ExtraDecErrorCond uint
  376. // ExtraDecErrorNone indicates no extra error condition.
  377. const ExtraDecErrorNone ExtraDecErrorCond = 0
  378. const (
  379. // ExtraDecErrorUnknownField indicates error condition when destination
  380. // Go struct doesn't have a field matching a CBOR map key.
  381. ExtraDecErrorUnknownField ExtraDecErrorCond = 1 << iota
  382. maxExtraDecError
  383. )
  384. func (ec ExtraDecErrorCond) valid() bool {
  385. return ec < maxExtraDecError
  386. }
  387. // UTF8Mode option specifies if decoder should
  388. // decode CBOR Text containing invalid UTF-8 string.
  389. type UTF8Mode int
  390. const (
  391. // UTF8RejectInvalid rejects CBOR Text containing
  392. // invalid UTF-8 string.
  393. UTF8RejectInvalid UTF8Mode = iota
  394. // UTF8DecodeInvalid allows decoding CBOR Text containing
  395. // invalid UTF-8 string.
  396. UTF8DecodeInvalid
  397. maxUTF8Mode
  398. )
  399. func (um UTF8Mode) valid() bool {
  400. return um >= 0 && um < maxUTF8Mode
  401. }
  402. // FieldNameMatchingMode specifies how string keys in CBOR maps are matched to Go struct field names.
  403. type FieldNameMatchingMode int
  404. const (
  405. // FieldNameMatchingPreferCaseSensitive prefers to decode map items into struct fields whose names (or tag
  406. // names) exactly match the item's key. If there is no such field, a map item will be decoded into a field whose
  407. // name is a case-insensitive match for the item's key.
  408. FieldNameMatchingPreferCaseSensitive FieldNameMatchingMode = iota
  409. // FieldNameMatchingCaseSensitive decodes map items only into a struct field whose name (or tag name) is an
  410. // exact match for the item's key.
  411. FieldNameMatchingCaseSensitive
  412. maxFieldNameMatchingMode
  413. )
  414. func (fnmm FieldNameMatchingMode) valid() bool {
  415. return fnmm >= 0 && fnmm < maxFieldNameMatchingMode
  416. }
  417. // BigIntDecMode specifies how to decode CBOR bignum to Go interface{}.
  418. type BigIntDecMode int
  419. const (
  420. // BigIntDecodeValue makes CBOR bignum decode to big.Int (instead of *big.Int)
  421. // when unmarshaling into a Go interface{}.
  422. BigIntDecodeValue BigIntDecMode = iota
  423. // BigIntDecodePointer makes CBOR bignum decode to *big.Int when
  424. // unmarshaling into a Go interface{}.
  425. BigIntDecodePointer
  426. maxBigIntDecMode
  427. )
  428. func (bidm BigIntDecMode) valid() bool {
  429. return bidm >= 0 && bidm < maxBigIntDecMode
  430. }
  431. // ByteStringToStringMode specifies the behavior when decoding a CBOR byte string into a Go string.
  432. type ByteStringToStringMode int
  433. const (
  434. // ByteStringToStringForbidden generates an error on an attempt to decode a CBOR byte string into a Go string.
  435. ByteStringToStringForbidden ByteStringToStringMode = iota
  436. // ByteStringToStringAllowed permits decoding a CBOR byte string into a Go string.
  437. ByteStringToStringAllowed
  438. // ByteStringToStringAllowedWithExpectedLaterEncoding permits decoding a CBOR byte string
  439. // into a Go string. Also, if the byte string is enclosed (directly or indirectly) by one of
  440. // the "expected later encoding" tags (numbers 21 through 23), the destination string will
  441. // be populated by applying the designated text encoding to the contents of the input byte
  442. // string.
  443. ByteStringToStringAllowedWithExpectedLaterEncoding
  444. maxByteStringToStringMode
  445. )
  446. func (bstsm ByteStringToStringMode) valid() bool {
  447. return bstsm >= 0 && bstsm < maxByteStringToStringMode
  448. }
  449. // FieldNameByteStringMode specifies the behavior when decoding a CBOR byte string map key as a Go struct field name.
  450. type FieldNameByteStringMode int
  451. const (
  452. // FieldNameByteStringForbidden generates an error on an attempt to decode a CBOR byte string map key as a Go struct field name.
  453. FieldNameByteStringForbidden FieldNameByteStringMode = iota
  454. // FieldNameByteStringAllowed permits CBOR byte string map keys to be recognized as Go struct field names.
  455. FieldNameByteStringAllowed
  456. maxFieldNameByteStringMode
  457. )
  458. func (fnbsm FieldNameByteStringMode) valid() bool {
  459. return fnbsm >= 0 && fnbsm < maxFieldNameByteStringMode
  460. }
  461. // UnrecognizedTagToAnyMode specifies how to decode unrecognized CBOR tag into an empty interface (any).
  462. // Currently, recognized CBOR tag numbers are 0, 1, 2, 3, or registered by TagSet.
  463. type UnrecognizedTagToAnyMode int
  464. const (
  465. // UnrecognizedTagNumAndContentToAny decodes CBOR tag number and tag content to cbor.Tag
  466. // when decoding unrecognized CBOR tag into an empty interface.
  467. UnrecognizedTagNumAndContentToAny UnrecognizedTagToAnyMode = iota
  468. // UnrecognizedTagContentToAny decodes only CBOR tag content (into its default type)
  469. // when decoding unrecognized CBOR tag into an empty interface.
  470. UnrecognizedTagContentToAny
  471. maxUnrecognizedTagToAny
  472. )
  473. func (uttam UnrecognizedTagToAnyMode) valid() bool {
  474. return uttam >= 0 && uttam < maxUnrecognizedTagToAny
  475. }
  476. // TimeTagToAnyMode specifies how to decode CBOR tag 0 and 1 into an empty interface (any).
  477. // Based on the specified mode, Unmarshal can return a time.Time value or a time string in a specific format.
  478. type TimeTagToAnyMode int
  479. const (
  480. // TimeTagToTime decodes CBOR tag 0 and 1 into a time.Time value
  481. // when decoding tag 0 or 1 into an empty interface.
  482. TimeTagToTime TimeTagToAnyMode = iota
  483. // TimeTagToRFC3339 decodes CBOR tag 0 and 1 into a time string in RFC3339 format
  484. // when decoding tag 0 or 1 into an empty interface.
  485. TimeTagToRFC3339
  486. // TimeTagToRFC3339Nano decodes CBOR tag 0 and 1 into a time string in RFC3339Nano format
  487. // when decoding tag 0 or 1 into an empty interface.
  488. TimeTagToRFC3339Nano
  489. maxTimeTagToAnyMode
  490. )
  491. func (tttam TimeTagToAnyMode) valid() bool {
  492. return tttam >= 0 && tttam < maxTimeTagToAnyMode
  493. }
  494. // SimpleValueRegistry is a registry of unmarshaling behaviors for each possible CBOR simple value
  495. // number (0...23 and 32...255).
  496. type SimpleValueRegistry struct {
  497. rejected [256]bool
  498. }
  499. // WithRejectedSimpleValue registers the given simple value as rejected. If the simple value is
  500. // encountered in a CBOR input during unmarshaling, an UnacceptableDataItemError is returned.
  501. func WithRejectedSimpleValue(sv SimpleValue) func(*SimpleValueRegistry) error {
  502. return func(r *SimpleValueRegistry) error {
  503. if sv >= 24 && sv <= 31 {
  504. return fmt.Errorf("cbor: cannot set analog for reserved simple value %d", sv)
  505. }
  506. r.rejected[sv] = true
  507. return nil
  508. }
  509. }
  510. // Creates a new SimpleValueRegistry. The registry state is initialized by executing the provided
  511. // functions in order against a registry that is pre-populated with the defaults for all well-formed
  512. // simple value numbers.
  513. func NewSimpleValueRegistryFromDefaults(fns ...func(*SimpleValueRegistry) error) (*SimpleValueRegistry, error) {
  514. var r SimpleValueRegistry
  515. for _, fn := range fns {
  516. if err := fn(&r); err != nil {
  517. return nil, err
  518. }
  519. }
  520. return &r, nil
  521. }
  522. // NaNMode specifies how to decode floating-point values (major type 7, additional information 25
  523. // through 27) representing NaN (not-a-number).
  524. type NaNMode int
  525. const (
  526. // NaNDecodeAllowed will decode NaN values to Go float32 or float64.
  527. NaNDecodeAllowed NaNMode = iota
  528. // NaNDecodeForbidden will return an UnacceptableDataItemError on an attempt to decode a NaN value.
  529. NaNDecodeForbidden
  530. maxNaNDecode
  531. )
  532. func (ndm NaNMode) valid() bool {
  533. return ndm >= 0 && ndm < maxNaNDecode
  534. }
  535. // InfMode specifies how to decode floating-point values (major type 7, additional information 25
  536. // through 27) representing positive or negative infinity.
  537. type InfMode int
  538. const (
  539. // InfDecodeAllowed will decode infinite values to Go float32 or float64.
  540. InfDecodeAllowed InfMode = iota
  541. // InfDecodeForbidden will return an UnacceptableDataItemError on an attempt to decode an
  542. // infinite value.
  543. InfDecodeForbidden
  544. maxInfDecode
  545. )
  546. func (idm InfMode) valid() bool {
  547. return idm >= 0 && idm < maxInfDecode
  548. }
  549. // ByteStringToTimeMode specifies the behavior when decoding a CBOR byte string into a Go time.Time.
  550. type ByteStringToTimeMode int
  551. const (
  552. // ByteStringToTimeForbidden generates an error on an attempt to decode a CBOR byte string into a Go time.Time.
  553. ByteStringToTimeForbidden ByteStringToTimeMode = iota
  554. // ByteStringToTimeAllowed permits decoding a CBOR byte string into a Go time.Time.
  555. ByteStringToTimeAllowed
  556. maxByteStringToTimeMode
  557. )
  558. func (bttm ByteStringToTimeMode) valid() bool {
  559. return bttm >= 0 && bttm < maxByteStringToTimeMode
  560. }
  561. // ByteStringExpectedFormatMode specifies how to decode CBOR byte string into Go byte slice
  562. // when the byte string is NOT enclosed in CBOR tag 21, 22, or 23. An error is returned if
  563. // the CBOR byte string does not contain the expected format (e.g. base64) specified.
  564. // For tags 21-23, see "Expected Later Encoding for CBOR-to-JSON Converters"
  565. // in RFC 8949 Section 3.4.5.2.
  566. type ByteStringExpectedFormatMode int
  567. const (
  568. // ByteStringExpectedFormatNone copies the unmodified CBOR byte string into Go byte slice
  569. // if the byte string is not tagged by CBOR tag 21-23.
  570. ByteStringExpectedFormatNone ByteStringExpectedFormatMode = iota
  571. // ByteStringExpectedBase64URL expects CBOR byte strings to contain base64url-encoded bytes
  572. // if the byte string is not tagged by CBOR tag 21-23. The decoder will attempt to decode
  573. // the base64url-encoded bytes into Go slice.
  574. ByteStringExpectedBase64URL
  575. // ByteStringExpectedBase64 expects CBOR byte strings to contain base64-encoded bytes
  576. // if the byte string is not tagged by CBOR tag 21-23. The decoder will attempt to decode
  577. // the base64-encoded bytes into Go slice.
  578. ByteStringExpectedBase64
  579. // ByteStringExpectedBase16 expects CBOR byte strings to contain base16-encoded bytes
  580. // if the byte string is not tagged by CBOR tag 21-23. The decoder will attempt to decode
  581. // the base16-encoded bytes into Go slice.
  582. ByteStringExpectedBase16
  583. maxByteStringExpectedFormatMode
  584. )
  585. func (bsefm ByteStringExpectedFormatMode) valid() bool {
  586. return bsefm >= 0 && bsefm < maxByteStringExpectedFormatMode
  587. }
  588. // BignumTagMode specifies whether or not the "bignum" tags 2 and 3 (RFC 8949 Section 3.4.3) can be
  589. // decoded.
  590. type BignumTagMode int
  591. const (
  592. // BignumTagAllowed allows bignum tags to be decoded.
  593. BignumTagAllowed BignumTagMode = iota
  594. // BignumTagForbidden produces an UnacceptableDataItemError during Unmarshal if a bignum tag
  595. // is encountered in the input.
  596. BignumTagForbidden
  597. maxBignumTag
  598. )
  599. func (btm BignumTagMode) valid() bool {
  600. return btm >= 0 && btm < maxBignumTag
  601. }
  602. // BinaryUnmarshalerMode specifies how to decode into types that implement
  603. // encoding.BinaryUnmarshaler.
  604. type BinaryUnmarshalerMode int
  605. const (
  606. // BinaryUnmarshalerByteString will invoke UnmarshalBinary on the contents of a CBOR byte
  607. // string when decoding into a value that implements BinaryUnmarshaler.
  608. BinaryUnmarshalerByteString BinaryUnmarshalerMode = iota
  609. // BinaryUnmarshalerNone does not recognize BinaryUnmarshaler implementations during decode.
  610. BinaryUnmarshalerNone
  611. maxBinaryUnmarshalerMode
  612. )
  613. func (bum BinaryUnmarshalerMode) valid() bool {
  614. return bum >= 0 && bum < maxBinaryUnmarshalerMode
  615. }
  616. // TextUnmarshalerMode specifies how to decode into types that implement
  617. // encoding.TextUnmarshaler.
  618. type TextUnmarshalerMode int
  619. const (
  620. // TextUnmarshalerNone does not recognize TextUnmarshaler implementations during decode.
  621. TextUnmarshalerNone TextUnmarshalerMode = iota
  622. // TextUnmarshalerTextString will invoke UnmarshalText on the contents of a CBOR text
  623. // string when decoding into a value that implements TextUnmarshaler.
  624. TextUnmarshalerTextString
  625. maxTextUnmarshalerMode
  626. )
  627. func (tum TextUnmarshalerMode) valid() bool {
  628. return tum >= 0 && tum < maxTextUnmarshalerMode
  629. }
  630. // DecOptions specifies decoding options.
  631. type DecOptions struct {
  632. // DupMapKey specifies whether to enforce duplicate map key.
  633. DupMapKey DupMapKeyMode
  634. // TimeTag specifies whether or not untagged data items, or tags other
  635. // than tag 0 and tag 1, can be decoded to time.Time. If tag 0 or tag 1
  636. // appears in an input, the type of its content is always validated as
  637. // specified in RFC 8949. That behavior is not controlled by this
  638. // option. The behavior of the supported modes are:
  639. //
  640. // DecTagIgnored (default): Untagged text strings and text strings
  641. // enclosed in tags other than 0 and 1 are decoded as though enclosed
  642. // in tag 0. Untagged unsigned integers, negative integers, and
  643. // floating-point numbers (or those enclosed in tags other than 0 and
  644. // 1) are decoded as though enclosed in tag 1. Decoding a tag other
  645. // than 0 or 1 enclosing simple values null or undefined into a
  646. // time.Time does not modify the destination value.
  647. //
  648. // DecTagOptional: Untagged text strings are decoded as though
  649. // enclosed in tag 0. Untagged unsigned integers, negative integers,
  650. // and floating-point numbers are decoded as though enclosed in tag
  651. // 1. Tags other than 0 and 1 will produce an error on attempts to
  652. // decode them into a time.Time.
  653. //
  654. // DecTagRequired: Only tags 0 and 1 can be decoded to time.Time. Any
  655. // other input will produce an error.
  656. TimeTag DecTagMode
  657. // MaxNestedLevels specifies the max nested levels allowed for any combination of CBOR array, maps, and tags.
  658. // Default is 32 levels and it can be set to [4, 65535]. Note that higher maximum levels of nesting can
  659. // require larger amounts of stack to deserialize. Don't increase this higher than you require.
  660. MaxNestedLevels int
  661. // MaxArrayElements specifies the max number of elements for CBOR arrays.
  662. // Default is 128*1024=131072 and it can be set to [16, 2147483647]
  663. MaxArrayElements int
  664. // MaxMapPairs specifies the max number of key-value pairs for CBOR maps.
  665. // Default is 128*1024=131072 and it can be set to [16, 2147483647]
  666. MaxMapPairs int
  667. // IndefLength specifies whether to allow indefinite length CBOR items.
  668. IndefLength IndefLengthMode
  669. // TagsMd specifies whether to allow CBOR tags (major type 6).
  670. TagsMd TagsMode
  671. // IntDec specifies which Go integer type (int64, uint64, or [big.Int]) to use
  672. // when decoding CBOR int (major type 0 and 1) to Go interface{}.
  673. IntDec IntDecMode
  674. // MapKeyByteString specifies how to decode CBOR byte string as map key
  675. // when decoding CBOR map with byte string key into an empty interface value.
  676. // By default, an error is returned when attempting to decode CBOR byte string
  677. // as map key because Go doesn't allow []byte as map key.
  678. MapKeyByteString MapKeyByteStringMode
  679. // ExtraReturnErrors specifies extra conditions that should be treated as errors.
  680. ExtraReturnErrors ExtraDecErrorCond
  681. // DefaultMapType specifies Go map type to create and decode to
  682. // when unmarshaling CBOR into an empty interface value.
  683. // By default, unmarshal uses map[interface{}]interface{}.
  684. DefaultMapType reflect.Type
  685. // UTF8 specifies if decoder should decode CBOR Text containing invalid UTF-8.
  686. // By default, unmarshal rejects CBOR text containing invalid UTF-8.
  687. UTF8 UTF8Mode
  688. // FieldNameMatching specifies how string keys in CBOR maps are matched to Go struct field names.
  689. FieldNameMatching FieldNameMatchingMode
  690. // BigIntDec specifies how to decode CBOR bignum to Go interface{}.
  691. BigIntDec BigIntDecMode
  692. // DefaultByteStringType is the Go type that should be produced when decoding a CBOR byte
  693. // string into an empty interface value. Types to which a []byte is convertible are valid
  694. // for this option, except for array and pointer-to-array types. If nil, the default is
  695. // []byte.
  696. DefaultByteStringType reflect.Type
  697. // ByteStringToString specifies the behavior when decoding a CBOR byte string into a Go string.
  698. ByteStringToString ByteStringToStringMode
  699. // FieldNameByteString specifies the behavior when decoding a CBOR byte string map key as a
  700. // Go struct field name.
  701. FieldNameByteString FieldNameByteStringMode
  702. // UnrecognizedTagToAny specifies how to decode unrecognized CBOR tag into an empty interface.
  703. // Currently, recognized CBOR tag numbers are 0, 1, 2, 3, or registered by TagSet.
  704. UnrecognizedTagToAny UnrecognizedTagToAnyMode
  705. // TimeTagToAny specifies how to decode CBOR tag 0 and 1 into an empty interface (any).
  706. // Based on the specified mode, Unmarshal can return a time.Time value or a time string in a specific format.
  707. TimeTagToAny TimeTagToAnyMode
  708. // SimpleValues is an immutable mapping from each CBOR simple value to a corresponding
  709. // unmarshal behavior. If nil, the simple values false, true, null, and undefined are mapped
  710. // to the Go analog values false, true, nil, and nil, respectively, and all other simple
  711. // values N (except the reserved simple values 24 through 31) are mapped to
  712. // cbor.SimpleValue(N). In other words, all well-formed simple values can be decoded.
  713. //
  714. // Users may provide a custom SimpleValueRegistry constructed via
  715. // NewSimpleValueRegistryFromDefaults.
  716. SimpleValues *SimpleValueRegistry
  717. // NaN specifies how to decode floating-point values (major type 7, additional information
  718. // 25 through 27) representing NaN (not-a-number).
  719. NaN NaNMode
  720. // Inf specifies how to decode floating-point values (major type 7, additional information
  721. // 25 through 27) representing positive or negative infinity.
  722. Inf InfMode
  723. // ByteStringToTime specifies how to decode CBOR byte string into Go time.Time.
  724. ByteStringToTime ByteStringToTimeMode
  725. // ByteStringExpectedFormat specifies how to decode CBOR byte string into Go byte slice
  726. // when the byte string is NOT enclosed in CBOR tag 21, 22, or 23. An error is returned if
  727. // the CBOR byte string does not contain the expected format (e.g. base64) specified.
  728. // For tags 21-23, see "Expected Later Encoding for CBOR-to-JSON Converters"
  729. // in RFC 8949 Section 3.4.5.2.
  730. ByteStringExpectedFormat ByteStringExpectedFormatMode
  731. // BignumTag specifies whether or not the "bignum" tags 2 and 3 (RFC 8949 Section 3.4.3) can
  732. // be decoded. Unlike BigIntDec, this option applies to all bignum tags encountered in a
  733. // CBOR input, independent of the type of the destination value of a particular Unmarshal
  734. // operation.
  735. BignumTag BignumTagMode
  736. // BinaryUnmarshaler specifies how to decode into types that implement
  737. // encoding.BinaryUnmarshaler.
  738. BinaryUnmarshaler BinaryUnmarshalerMode
  739. // TextUnmarshaler specifies how to decode into types that implement
  740. // encoding.TextUnmarshaler.
  741. TextUnmarshaler TextUnmarshalerMode
  742. // JSONUnmarshalerTranscoder sets the transcoding scheme used to unmarshal types that
  743. // implement json.Unmarshaler but do not also implement cbor.Unmarshaler. If nil, decoding
  744. // behavior is not influenced by whether or not a type implements json.Unmarshaler.
  745. JSONUnmarshalerTranscoder Transcoder
  746. }
  747. // DecMode returns DecMode with immutable options and no tags (safe for concurrency).
  748. func (opts DecOptions) DecMode() (DecMode, error) { //nolint:gocritic // ignore hugeParam
  749. return opts.decMode()
  750. }
  751. // validForTags checks that the provided tag set is compatible with these options and returns a
  752. // non-nil error if and only if the provided tag set is incompatible.
  753. func (opts DecOptions) validForTags(tags TagSet) error { //nolint:gocritic // ignore hugeParam
  754. if opts.TagsMd == TagsForbidden {
  755. return errors.New("cbor: cannot create DecMode with TagSet when TagsMd is TagsForbidden")
  756. }
  757. if tags == nil {
  758. return errors.New("cbor: cannot create DecMode with nil value as TagSet")
  759. }
  760. if opts.ByteStringToString == ByteStringToStringAllowedWithExpectedLaterEncoding ||
  761. opts.ByteStringExpectedFormat != ByteStringExpectedFormatNone {
  762. for _, tagNum := range []uint64{
  763. tagNumExpectedLaterEncodingBase64URL,
  764. tagNumExpectedLaterEncodingBase64,
  765. tagNumExpectedLaterEncodingBase16,
  766. } {
  767. if rt := tags.getTypeFromTagNum([]uint64{tagNum}); rt != nil {
  768. return fmt.Errorf("cbor: DecMode with non-default StringExpectedEncoding or ByteSliceExpectedEncoding treats tag %d as built-in and conflicts with the provided TagSet's registration of %v", tagNum, rt)
  769. }
  770. }
  771. }
  772. return nil
  773. }
  774. // DecModeWithTags returns DecMode with options and tags that are both immutable (safe for concurrency).
  775. func (opts DecOptions) DecModeWithTags(tags TagSet) (DecMode, error) { //nolint:gocritic // ignore hugeParam
  776. if err := opts.validForTags(tags); err != nil {
  777. return nil, err
  778. }
  779. dm, err := opts.decMode()
  780. if err != nil {
  781. return nil, err
  782. }
  783. // Copy tags
  784. ts := tagSet(make(map[reflect.Type]*tagItem))
  785. syncTags := tags.(*syncTagSet)
  786. syncTags.RLock()
  787. for contentType, tag := range syncTags.t {
  788. if tag.opts.DecTag != DecTagIgnored {
  789. ts[contentType] = tag
  790. }
  791. }
  792. syncTags.RUnlock()
  793. if len(ts) > 0 {
  794. dm.tags = ts
  795. }
  796. return dm, nil
  797. }
  798. // DecModeWithSharedTags returns DecMode with immutable options and mutable shared tags (safe for concurrency).
  799. func (opts DecOptions) DecModeWithSharedTags(tags TagSet) (DecMode, error) { //nolint:gocritic // ignore hugeParam
  800. if err := opts.validForTags(tags); err != nil {
  801. return nil, err
  802. }
  803. dm, err := opts.decMode()
  804. if err != nil {
  805. return nil, err
  806. }
  807. dm.tags = tags
  808. return dm, nil
  809. }
  810. const (
  811. defaultMaxArrayElements = 131072
  812. minMaxArrayElements = 16
  813. maxMaxArrayElements = 2147483647
  814. defaultMaxMapPairs = 131072
  815. minMaxMapPairs = 16
  816. maxMaxMapPairs = 2147483647
  817. defaultMaxNestedLevels = 32
  818. minMaxNestedLevels = 4
  819. maxMaxNestedLevels = 65535
  820. )
  821. var defaultSimpleValues = func() *SimpleValueRegistry {
  822. registry, err := NewSimpleValueRegistryFromDefaults()
  823. if err != nil {
  824. panic(err)
  825. }
  826. return registry
  827. }()
  828. //nolint:gocyclo // Each option comes with some manageable boilerplate
  829. func (opts DecOptions) decMode() (*decMode, error) { //nolint:gocritic // ignore hugeParam
  830. if !opts.DupMapKey.valid() {
  831. return nil, errors.New("cbor: invalid DupMapKey " + strconv.Itoa(int(opts.DupMapKey)))
  832. }
  833. if !opts.TimeTag.valid() {
  834. return nil, errors.New("cbor: invalid TimeTag " + strconv.Itoa(int(opts.TimeTag)))
  835. }
  836. if !opts.IndefLength.valid() {
  837. return nil, errors.New("cbor: invalid IndefLength " + strconv.Itoa(int(opts.IndefLength)))
  838. }
  839. if !opts.TagsMd.valid() {
  840. return nil, errors.New("cbor: invalid TagsMd " + strconv.Itoa(int(opts.TagsMd)))
  841. }
  842. if !opts.IntDec.valid() {
  843. return nil, errors.New("cbor: invalid IntDec " + strconv.Itoa(int(opts.IntDec)))
  844. }
  845. if !opts.MapKeyByteString.valid() {
  846. return nil, errors.New("cbor: invalid MapKeyByteString " + strconv.Itoa(int(opts.MapKeyByteString)))
  847. }
  848. if opts.MaxNestedLevels == 0 {
  849. opts.MaxNestedLevels = defaultMaxNestedLevels
  850. } else if opts.MaxNestedLevels < minMaxNestedLevels || opts.MaxNestedLevels > maxMaxNestedLevels {
  851. return nil, errors.New("cbor: invalid MaxNestedLevels " + strconv.Itoa(opts.MaxNestedLevels) +
  852. " (range is [" + strconv.Itoa(minMaxNestedLevels) + ", " + strconv.Itoa(maxMaxNestedLevels) + "])")
  853. }
  854. if opts.MaxArrayElements == 0 {
  855. opts.MaxArrayElements = defaultMaxArrayElements
  856. } else if opts.MaxArrayElements < minMaxArrayElements || opts.MaxArrayElements > maxMaxArrayElements {
  857. return nil, errors.New("cbor: invalid MaxArrayElements " + strconv.Itoa(opts.MaxArrayElements) +
  858. " (range is [" + strconv.Itoa(minMaxArrayElements) + ", " + strconv.Itoa(maxMaxArrayElements) + "])")
  859. }
  860. if opts.MaxMapPairs == 0 {
  861. opts.MaxMapPairs = defaultMaxMapPairs
  862. } else if opts.MaxMapPairs < minMaxMapPairs || opts.MaxMapPairs > maxMaxMapPairs {
  863. return nil, errors.New("cbor: invalid MaxMapPairs " + strconv.Itoa(opts.MaxMapPairs) +
  864. " (range is [" + strconv.Itoa(minMaxMapPairs) + ", " + strconv.Itoa(maxMaxMapPairs) + "])")
  865. }
  866. if !opts.ExtraReturnErrors.valid() {
  867. return nil, errors.New("cbor: invalid ExtraReturnErrors " + strconv.Itoa(int(opts.ExtraReturnErrors)))
  868. }
  869. if opts.DefaultMapType != nil && opts.DefaultMapType.Kind() != reflect.Map {
  870. return nil, fmt.Errorf("cbor: invalid DefaultMapType %s", opts.DefaultMapType)
  871. }
  872. if !opts.UTF8.valid() {
  873. return nil, errors.New("cbor: invalid UTF8 " + strconv.Itoa(int(opts.UTF8)))
  874. }
  875. if !opts.FieldNameMatching.valid() {
  876. return nil, errors.New("cbor: invalid FieldNameMatching " + strconv.Itoa(int(opts.FieldNameMatching)))
  877. }
  878. if !opts.BigIntDec.valid() {
  879. return nil, errors.New("cbor: invalid BigIntDec " + strconv.Itoa(int(opts.BigIntDec)))
  880. }
  881. if opts.DefaultByteStringType != nil &&
  882. opts.DefaultByteStringType.Kind() != reflect.String &&
  883. (opts.DefaultByteStringType.Kind() != reflect.Slice || opts.DefaultByteStringType.Elem().Kind() != reflect.Uint8) {
  884. return nil, fmt.Errorf("cbor: invalid DefaultByteStringType: %s is not of kind string or []uint8", opts.DefaultByteStringType)
  885. }
  886. if !opts.ByteStringToString.valid() {
  887. return nil, errors.New("cbor: invalid ByteStringToString " + strconv.Itoa(int(opts.ByteStringToString)))
  888. }
  889. if !opts.FieldNameByteString.valid() {
  890. return nil, errors.New("cbor: invalid FieldNameByteString " + strconv.Itoa(int(opts.FieldNameByteString)))
  891. }
  892. if !opts.UnrecognizedTagToAny.valid() {
  893. return nil, errors.New("cbor: invalid UnrecognizedTagToAnyMode " + strconv.Itoa(int(opts.UnrecognizedTagToAny)))
  894. }
  895. simpleValues := opts.SimpleValues
  896. if simpleValues == nil {
  897. simpleValues = defaultSimpleValues
  898. }
  899. if !opts.TimeTagToAny.valid() {
  900. return nil, errors.New("cbor: invalid TimeTagToAny " + strconv.Itoa(int(opts.TimeTagToAny)))
  901. }
  902. if !opts.NaN.valid() {
  903. return nil, errors.New("cbor: invalid NaNDec " + strconv.Itoa(int(opts.NaN)))
  904. }
  905. if !opts.Inf.valid() {
  906. return nil, errors.New("cbor: invalid InfDec " + strconv.Itoa(int(opts.Inf)))
  907. }
  908. if !opts.ByteStringToTime.valid() {
  909. return nil, errors.New("cbor: invalid ByteStringToTime " + strconv.Itoa(int(opts.ByteStringToTime)))
  910. }
  911. if !opts.ByteStringExpectedFormat.valid() {
  912. return nil, errors.New("cbor: invalid ByteStringExpectedFormat " + strconv.Itoa(int(opts.ByteStringExpectedFormat)))
  913. }
  914. if !opts.BignumTag.valid() {
  915. return nil, errors.New("cbor: invalid BignumTag " + strconv.Itoa(int(opts.BignumTag)))
  916. }
  917. if !opts.BinaryUnmarshaler.valid() {
  918. return nil, errors.New("cbor: invalid BinaryUnmarshaler " + strconv.Itoa(int(opts.BinaryUnmarshaler)))
  919. }
  920. if !opts.TextUnmarshaler.valid() {
  921. return nil, errors.New("cbor: invalid TextUnmarshaler " + strconv.Itoa(int(opts.TextUnmarshaler)))
  922. }
  923. dm := decMode{
  924. dupMapKey: opts.DupMapKey,
  925. timeTag: opts.TimeTag,
  926. maxNestedLevels: opts.MaxNestedLevels,
  927. maxArrayElements: opts.MaxArrayElements,
  928. maxMapPairs: opts.MaxMapPairs,
  929. indefLength: opts.IndefLength,
  930. tagsMd: opts.TagsMd,
  931. intDec: opts.IntDec,
  932. mapKeyByteString: opts.MapKeyByteString,
  933. extraReturnErrors: opts.ExtraReturnErrors,
  934. defaultMapType: opts.DefaultMapType,
  935. utf8: opts.UTF8,
  936. fieldNameMatching: opts.FieldNameMatching,
  937. bigIntDec: opts.BigIntDec,
  938. defaultByteStringType: opts.DefaultByteStringType,
  939. byteStringToString: opts.ByteStringToString,
  940. fieldNameByteString: opts.FieldNameByteString,
  941. unrecognizedTagToAny: opts.UnrecognizedTagToAny,
  942. timeTagToAny: opts.TimeTagToAny,
  943. simpleValues: simpleValues,
  944. nanDec: opts.NaN,
  945. infDec: opts.Inf,
  946. byteStringToTime: opts.ByteStringToTime,
  947. byteStringExpectedFormat: opts.ByteStringExpectedFormat,
  948. bignumTag: opts.BignumTag,
  949. binaryUnmarshaler: opts.BinaryUnmarshaler,
  950. textUnmarshaler: opts.TextUnmarshaler,
  951. jsonUnmarshalerTranscoder: opts.JSONUnmarshalerTranscoder,
  952. }
  953. return &dm, nil
  954. }
  955. // DecMode is the main interface for CBOR decoding.
  956. type DecMode interface {
  957. // Unmarshal parses the CBOR-encoded data into the value pointed to by v
  958. // using the decoding mode. If v is nil, not a pointer, or a nil pointer,
  959. // Unmarshal returns an error.
  960. //
  961. // See the documentation for Unmarshal for details.
  962. Unmarshal(data []byte, v any) error
  963. // UnmarshalFirst parses the first CBOR data item into the value pointed to by v
  964. // using the decoding mode. Any remaining bytes are returned in rest.
  965. //
  966. // If v is nil, not a pointer, or a nil pointer, UnmarshalFirst returns an error.
  967. //
  968. // See the documentation for Unmarshal for details.
  969. UnmarshalFirst(data []byte, v any) (rest []byte, err error)
  970. // Valid checks whether data is a well-formed encoded CBOR data item and
  971. // that it complies with configurable restrictions such as MaxNestedLevels,
  972. // MaxArrayElements, MaxMapPairs, etc.
  973. //
  974. // If there are any remaining bytes after the CBOR data item,
  975. // an ExtraneousDataError is returned.
  976. //
  977. // WARNING: Valid doesn't check if encoded CBOR data item is valid (i.e. validity)
  978. // and RFC 8949 distinctly defines what is "Valid" and what is "Well-formed".
  979. //
  980. // Deprecated: Valid is kept for compatibility and should not be used.
  981. // Use Wellformed instead because it has a more appropriate name.
  982. Valid(data []byte) error
  983. // Wellformed checks whether data is a well-formed encoded CBOR data item and
  984. // that it complies with configurable restrictions such as MaxNestedLevels,
  985. // MaxArrayElements, MaxMapPairs, etc.
  986. //
  987. // If there are any remaining bytes after the CBOR data item,
  988. // an ExtraneousDataError is returned.
  989. Wellformed(data []byte) error
  990. // NewDecoder returns a new decoder that reads from r using dm DecMode.
  991. NewDecoder(r io.Reader) *Decoder
  992. // DecOptions returns user specified options used to create this DecMode.
  993. DecOptions() DecOptions
  994. }
  995. type decMode struct {
  996. tags tagProvider
  997. dupMapKey DupMapKeyMode
  998. timeTag DecTagMode
  999. maxNestedLevels int
  1000. maxArrayElements int
  1001. maxMapPairs int
  1002. indefLength IndefLengthMode
  1003. tagsMd TagsMode
  1004. intDec IntDecMode
  1005. mapKeyByteString MapKeyByteStringMode
  1006. extraReturnErrors ExtraDecErrorCond
  1007. defaultMapType reflect.Type
  1008. utf8 UTF8Mode
  1009. fieldNameMatching FieldNameMatchingMode
  1010. bigIntDec BigIntDecMode
  1011. defaultByteStringType reflect.Type
  1012. byteStringToString ByteStringToStringMode
  1013. fieldNameByteString FieldNameByteStringMode
  1014. unrecognizedTagToAny UnrecognizedTagToAnyMode
  1015. timeTagToAny TimeTagToAnyMode
  1016. simpleValues *SimpleValueRegistry
  1017. nanDec NaNMode
  1018. infDec InfMode
  1019. byteStringToTime ByteStringToTimeMode
  1020. byteStringExpectedFormat ByteStringExpectedFormatMode
  1021. bignumTag BignumTagMode
  1022. binaryUnmarshaler BinaryUnmarshalerMode
  1023. textUnmarshaler TextUnmarshalerMode
  1024. jsonUnmarshalerTranscoder Transcoder
  1025. }
  1026. var defaultDecMode, _ = DecOptions{}.decMode()
  1027. // DecOptions returns user specified options used to create this DecMode.
  1028. func (dm *decMode) DecOptions() DecOptions {
  1029. simpleValues := dm.simpleValues
  1030. if simpleValues == defaultSimpleValues {
  1031. // Users can't explicitly set this to defaultSimpleValues. It must have been nil in
  1032. // the original DecOptions.
  1033. simpleValues = nil
  1034. }
  1035. return DecOptions{
  1036. DupMapKey: dm.dupMapKey,
  1037. TimeTag: dm.timeTag,
  1038. MaxNestedLevels: dm.maxNestedLevels,
  1039. MaxArrayElements: dm.maxArrayElements,
  1040. MaxMapPairs: dm.maxMapPairs,
  1041. IndefLength: dm.indefLength,
  1042. TagsMd: dm.tagsMd,
  1043. IntDec: dm.intDec,
  1044. MapKeyByteString: dm.mapKeyByteString,
  1045. ExtraReturnErrors: dm.extraReturnErrors,
  1046. DefaultMapType: dm.defaultMapType,
  1047. UTF8: dm.utf8,
  1048. FieldNameMatching: dm.fieldNameMatching,
  1049. BigIntDec: dm.bigIntDec,
  1050. DefaultByteStringType: dm.defaultByteStringType,
  1051. ByteStringToString: dm.byteStringToString,
  1052. FieldNameByteString: dm.fieldNameByteString,
  1053. UnrecognizedTagToAny: dm.unrecognizedTagToAny,
  1054. TimeTagToAny: dm.timeTagToAny,
  1055. SimpleValues: simpleValues,
  1056. NaN: dm.nanDec,
  1057. Inf: dm.infDec,
  1058. ByteStringToTime: dm.byteStringToTime,
  1059. ByteStringExpectedFormat: dm.byteStringExpectedFormat,
  1060. BignumTag: dm.bignumTag,
  1061. BinaryUnmarshaler: dm.binaryUnmarshaler,
  1062. TextUnmarshaler: dm.textUnmarshaler,
  1063. JSONUnmarshalerTranscoder: dm.jsonUnmarshalerTranscoder,
  1064. }
  1065. }
  1066. // Unmarshal parses the CBOR-encoded data into the value pointed to by v
  1067. // using dm decoding mode. If v is nil, not a pointer, or a nil pointer,
  1068. // Unmarshal returns an error.
  1069. //
  1070. // See the documentation for Unmarshal for details.
  1071. func (dm *decMode) Unmarshal(data []byte, v any) error {
  1072. d := decoder{data: data, dm: dm}
  1073. // Check well-formedness.
  1074. off := d.off // Save offset before data validation
  1075. err := d.wellformed(false, false) // don't allow any extra data after valid data item.
  1076. d.off = off // Restore offset
  1077. if err != nil {
  1078. return err
  1079. }
  1080. return d.value(v)
  1081. }
  1082. // UnmarshalFirst parses the first CBOR data item into the value pointed to by v
  1083. // using dm decoding mode. Any remaining bytes are returned in rest.
  1084. //
  1085. // If v is nil, not a pointer, or a nil pointer, UnmarshalFirst returns an error.
  1086. //
  1087. // See the documentation for Unmarshal for details.
  1088. func (dm *decMode) UnmarshalFirst(data []byte, v any) (rest []byte, err error) {
  1089. d := decoder{data: data, dm: dm}
  1090. // check well-formedness.
  1091. off := d.off // Save offset before data validation
  1092. err = d.wellformed(true, false) // allow extra data after well-formed data item
  1093. d.off = off // Restore offset
  1094. // If it is well-formed, parse the value. This is structured like this to allow
  1095. // better test coverage
  1096. if err == nil {
  1097. err = d.value(v)
  1098. }
  1099. // If either wellformed or value returned an error, do not return rest bytes
  1100. if err != nil {
  1101. return nil, err
  1102. }
  1103. // Return the rest of the data slice (which might be len 0)
  1104. return d.data[d.off:], nil
  1105. }
  1106. // Valid checks whether data is a well-formed encoded CBOR data item and
  1107. // that it complies with configurable restrictions such as MaxNestedLevels,
  1108. // MaxArrayElements, MaxMapPairs, etc.
  1109. //
  1110. // If there are any remaining bytes after the CBOR data item,
  1111. // an ExtraneousDataError is returned.
  1112. //
  1113. // WARNING: Valid doesn't check if encoded CBOR data item is valid (i.e. validity)
  1114. // and RFC 8949 distinctly defines what is "Valid" and what is "Well-formed".
  1115. //
  1116. // Deprecated: Valid is kept for compatibility and should not be used.
  1117. // Use Wellformed instead because it has a more appropriate name.
  1118. func (dm *decMode) Valid(data []byte) error {
  1119. return dm.Wellformed(data)
  1120. }
  1121. // Wellformed checks whether data is a well-formed encoded CBOR data item and
  1122. // that it complies with configurable restrictions such as MaxNestedLevels,
  1123. // MaxArrayElements, MaxMapPairs, etc.
  1124. //
  1125. // If there are any remaining bytes after the CBOR data item,
  1126. // an ExtraneousDataError is returned.
  1127. func (dm *decMode) Wellformed(data []byte) error {
  1128. d := decoder{data: data, dm: dm}
  1129. return d.wellformed(false, false)
  1130. }
  1131. // NewDecoder returns a new decoder that reads from r using dm DecMode.
  1132. func (dm *decMode) NewDecoder(r io.Reader) *Decoder {
  1133. return &Decoder{r: r, d: decoder{dm: dm}}
  1134. }
  1135. type decoder struct {
  1136. data []byte
  1137. off int // next read offset in data
  1138. dm *decMode
  1139. // expectedLaterEncodingTags stores a stack of encountered "Expected Later Encoding" tags,
  1140. // if any.
  1141. //
  1142. // The "Expected Later Encoding" tags (21 to 23) are valid for any data item. When decoding
  1143. // byte strings, the effective encoding comes from the tag nearest to the byte string being
  1144. // decoded. For example, the effective encoding of the byte string 21(22(h'41')) would be
  1145. // controlled by tag 22,and in the data item 23(h'42', 22([21(h'43')])]) the effective
  1146. // encoding of the byte strings h'42' and h'43' would be controlled by tag 23 and 21,
  1147. // respectively.
  1148. expectedLaterEncodingTags []uint64
  1149. }
  1150. // value decodes CBOR data item into the value pointed to by v.
  1151. // If CBOR data item fails to be decoded into v,
  1152. // error is returned and offset is moved to the next CBOR data item.
  1153. // Precondition: d.data contains at least one well-formed CBOR data item.
  1154. func (d *decoder) value(v any) error {
  1155. // v can't be nil, non-pointer, or nil pointer value.
  1156. if v == nil {
  1157. return &InvalidUnmarshalError{"cbor: Unmarshal(nil)"}
  1158. }
  1159. rv := reflect.ValueOf(v)
  1160. if rv.Kind() != reflect.Pointer {
  1161. return &InvalidUnmarshalError{"cbor: Unmarshal(non-pointer " + rv.Type().String() + ")"}
  1162. } else if rv.IsNil() {
  1163. return &InvalidUnmarshalError{"cbor: Unmarshal(nil " + rv.Type().String() + ")"}
  1164. }
  1165. rv = rv.Elem()
  1166. return d.parseToValue(rv, getTypeInfo(rv.Type()))
  1167. }
  1168. // parseToValue decodes CBOR data to value. It assumes data is well-formed,
  1169. // and does not perform bounds checking.
  1170. func (d *decoder) parseToValue(v reflect.Value, tInfo *typeInfo) error { //nolint:gocyclo
  1171. // Decode CBOR nil or CBOR undefined to pointer value by setting pointer value to nil.
  1172. if d.nextCBORNil() && v.Kind() == reflect.Pointer {
  1173. d.skip()
  1174. v.SetZero()
  1175. return nil
  1176. }
  1177. if tInfo.spclType == specialTypeIface {
  1178. if !v.IsNil() {
  1179. // Use value type
  1180. v = v.Elem()
  1181. tInfo = getTypeInfo(v.Type())
  1182. } else { //nolint:gocritic
  1183. // Create and use registered type if CBOR data is registered tag
  1184. if d.dm.tags != nil && d.nextCBORType() == cborTypeTag {
  1185. off := d.off
  1186. var tagNums []uint64
  1187. for d.nextCBORType() == cborTypeTag {
  1188. _, _, tagNum := d.getHead()
  1189. tagNums = append(tagNums, tagNum)
  1190. }
  1191. d.off = off
  1192. registeredType := d.dm.tags.getTypeFromTagNum(tagNums)
  1193. if registeredType != nil {
  1194. if registeredType.Implements(tInfo.nonPtrType) ||
  1195. reflect.PointerTo(registeredType).Implements(tInfo.nonPtrType) {
  1196. v.Set(reflect.New(registeredType))
  1197. v = v.Elem()
  1198. tInfo = getTypeInfo(registeredType)
  1199. }
  1200. }
  1201. }
  1202. }
  1203. }
  1204. // Create new value for the pointer v to point to.
  1205. // At this point, CBOR value is not nil/undefined if v is a pointer.
  1206. for v.Kind() == reflect.Pointer {
  1207. if v.IsNil() {
  1208. if !v.CanSet() {
  1209. d.skip()
  1210. return errors.New("cbor: cannot set new value for " + v.Type().String())
  1211. }
  1212. v.Set(reflect.New(v.Type().Elem()))
  1213. }
  1214. v = v.Elem()
  1215. }
  1216. // Strip self-described CBOR tag number.
  1217. for d.nextCBORType() == cborTypeTag {
  1218. off := d.off
  1219. _, _, tagNum := d.getHead()
  1220. if tagNum != tagNumSelfDescribedCBOR {
  1221. d.off = off
  1222. break
  1223. }
  1224. }
  1225. // Check validity of supported built-in tags.
  1226. off := d.off
  1227. for d.nextCBORType() == cborTypeTag {
  1228. _, _, tagNum := d.getHead()
  1229. if err := validBuiltinTag(tagNum, d.data[d.off]); err != nil {
  1230. d.skip()
  1231. return err
  1232. }
  1233. }
  1234. d.off = off
  1235. if tInfo.spclType != specialTypeNone {
  1236. switch tInfo.spclType {
  1237. case specialTypeEmptyIface:
  1238. iv, err := d.parse(false) // Skipped self-described CBOR tag number already.
  1239. if iv != nil {
  1240. v.Set(reflect.ValueOf(iv))
  1241. }
  1242. return err
  1243. case specialTypeTag:
  1244. return d.parseToTag(v)
  1245. case specialTypeTime:
  1246. if d.nextCBORNil() {
  1247. // Decoding CBOR null and undefined to time.Time is no-op.
  1248. d.skip()
  1249. return nil
  1250. }
  1251. tm, ok, err := d.parseToTime()
  1252. if err != nil {
  1253. return err
  1254. }
  1255. if ok {
  1256. v.Set(reflect.ValueOf(tm))
  1257. }
  1258. return nil
  1259. case specialTypeUnmarshalerIface:
  1260. return d.parseToUnmarshaler(v)
  1261. case specialTypeUnexportedUnmarshalerIface:
  1262. return d.parseToUnexportedUnmarshaler(v)
  1263. case specialTypeJSONUnmarshalerIface:
  1264. // This special type implies that the type does not also implement
  1265. // cbor.Umarshaler.
  1266. if d.dm.jsonUnmarshalerTranscoder == nil {
  1267. break
  1268. }
  1269. return d.parseToJSONUnmarshaler(v)
  1270. }
  1271. }
  1272. // Check registered tag number
  1273. if tagItem := d.getRegisteredTagItem(tInfo.nonPtrType); tagItem != nil {
  1274. t := d.nextCBORType()
  1275. if t != cborTypeTag {
  1276. if tagItem.opts.DecTag == DecTagRequired {
  1277. d.skip() // Required tag number is absent, skip entire tag
  1278. return &UnmarshalTypeError{
  1279. CBORType: t.String(),
  1280. GoType: tInfo.typ.String(),
  1281. errorMsg: "expect CBOR tag value"}
  1282. }
  1283. } else if err := d.validRegisteredTagNums(tagItem); err != nil {
  1284. d.skip() // Skip tag content
  1285. return err
  1286. }
  1287. }
  1288. t := d.nextCBORType()
  1289. switch t {
  1290. case cborTypePositiveInt:
  1291. _, _, val := d.getHead()
  1292. return fillPositiveInt(t, val, v)
  1293. case cborTypeNegativeInt:
  1294. _, _, val := d.getHead()
  1295. if val > math.MaxInt64 {
  1296. // CBOR negative integer overflows int64, use big.Int to store value.
  1297. bi := new(big.Int)
  1298. bi.SetUint64(val)
  1299. bi.Add(bi, big.NewInt(1))
  1300. bi.Neg(bi)
  1301. if tInfo.nonPtrType == typeBigInt {
  1302. v.Set(reflect.ValueOf(*bi))
  1303. return nil
  1304. }
  1305. return &UnmarshalTypeError{
  1306. CBORType: t.String(),
  1307. GoType: tInfo.nonPtrType.String(),
  1308. errorMsg: bi.String() + " overflows Go's int64",
  1309. }
  1310. }
  1311. nValue := int64(-1) ^ int64(val)
  1312. return fillNegativeInt(t, nValue, v)
  1313. case cborTypeByteString:
  1314. b, copied := d.parseByteString()
  1315. b, converted, err := d.applyByteStringTextConversion(b, v.Type())
  1316. if err != nil {
  1317. return err
  1318. }
  1319. copied = copied || converted
  1320. return fillByteString(t, b, !copied, v, d.dm.byteStringToString, d.dm.binaryUnmarshaler, d.dm.textUnmarshaler)
  1321. case cborTypeTextString:
  1322. b, err := d.parseTextString()
  1323. if err != nil {
  1324. return err
  1325. }
  1326. return fillTextString(t, b, v, d.dm.textUnmarshaler)
  1327. case cborTypePrimitives:
  1328. _, ai, val := d.getHead()
  1329. switch ai {
  1330. case additionalInformationAsFloat16:
  1331. f := float64(float16.Frombits(uint16(val)).Float32())
  1332. return fillFloat(t, f, v)
  1333. case additionalInformationAsFloat32:
  1334. f := float64(math.Float32frombits(uint32(val)))
  1335. return fillFloat(t, f, v)
  1336. case additionalInformationAsFloat64:
  1337. f := math.Float64frombits(val)
  1338. return fillFloat(t, f, v)
  1339. default: // ai <= 24
  1340. if d.dm.simpleValues.rejected[SimpleValue(val)] {
  1341. return &UnacceptableDataItemError{
  1342. CBORType: t.String(),
  1343. Message: "simple value " + strconv.FormatInt(int64(val), 10) + " is not recognized",
  1344. }
  1345. }
  1346. switch ai {
  1347. case additionalInformationAsFalse,
  1348. additionalInformationAsTrue:
  1349. return fillBool(t, ai == additionalInformationAsTrue, v)
  1350. case additionalInformationAsNull,
  1351. additionalInformationAsUndefined:
  1352. return fillNil(t, v)
  1353. default:
  1354. return fillPositiveInt(t, val, v)
  1355. }
  1356. }
  1357. case cborTypeTag:
  1358. _, _, tagNum := d.getHead()
  1359. switch tagNum {
  1360. case tagNumUnsignedBignum:
  1361. // Bignum (tag 2) can be decoded to uint, int, float, slice, array, or big.Int.
  1362. b, copied := d.parseByteString()
  1363. bi := new(big.Int).SetBytes(b)
  1364. if tInfo.nonPtrType == typeBigInt {
  1365. v.Set(reflect.ValueOf(*bi))
  1366. return nil
  1367. }
  1368. if tInfo.nonPtrKind == reflect.Slice || tInfo.nonPtrKind == reflect.Array {
  1369. return fillByteString(t, b, !copied, v, ByteStringToStringForbidden, d.dm.binaryUnmarshaler, d.dm.textUnmarshaler)
  1370. }
  1371. if bi.IsUint64() {
  1372. return fillPositiveInt(t, bi.Uint64(), v)
  1373. }
  1374. return &UnmarshalTypeError{
  1375. CBORType: t.String(),
  1376. GoType: tInfo.nonPtrType.String(),
  1377. errorMsg: bi.String() + " overflows " + v.Type().String(),
  1378. }
  1379. case tagNumNegativeBignum:
  1380. // Bignum (tag 3) can be decoded to int, float, slice, array, or big.Int.
  1381. b, copied := d.parseByteString()
  1382. bi := new(big.Int).SetBytes(b)
  1383. bi.Add(bi, big.NewInt(1))
  1384. bi.Neg(bi)
  1385. if tInfo.nonPtrType == typeBigInt {
  1386. v.Set(reflect.ValueOf(*bi))
  1387. return nil
  1388. }
  1389. if tInfo.nonPtrKind == reflect.Slice || tInfo.nonPtrKind == reflect.Array {
  1390. return fillByteString(t, b, !copied, v, ByteStringToStringForbidden, d.dm.binaryUnmarshaler, d.dm.textUnmarshaler)
  1391. }
  1392. if bi.IsInt64() {
  1393. return fillNegativeInt(t, bi.Int64(), v)
  1394. }
  1395. return &UnmarshalTypeError{
  1396. CBORType: t.String(),
  1397. GoType: tInfo.nonPtrType.String(),
  1398. errorMsg: bi.String() + " overflows " + v.Type().String(),
  1399. }
  1400. case tagNumExpectedLaterEncodingBase64URL, tagNumExpectedLaterEncodingBase64, tagNumExpectedLaterEncodingBase16:
  1401. // If conversion for interoperability with text encodings is not configured,
  1402. // treat tags 21-23 as unregistered tags.
  1403. if d.dm.byteStringToString == ByteStringToStringAllowedWithExpectedLaterEncoding || d.dm.byteStringExpectedFormat != ByteStringExpectedFormatNone {
  1404. d.expectedLaterEncodingTags = append(d.expectedLaterEncodingTags, tagNum)
  1405. defer func() {
  1406. d.expectedLaterEncodingTags = d.expectedLaterEncodingTags[:len(d.expectedLaterEncodingTags)-1]
  1407. }()
  1408. }
  1409. }
  1410. return d.parseToValue(v, tInfo)
  1411. case cborTypeArray:
  1412. if tInfo.nonPtrKind == reflect.Slice {
  1413. return d.parseArrayToSlice(v, tInfo)
  1414. } else if tInfo.nonPtrKind == reflect.Array {
  1415. return d.parseArrayToArray(v, tInfo)
  1416. } else if tInfo.nonPtrKind == reflect.Struct {
  1417. return d.parseArrayToStruct(v, tInfo)
  1418. }
  1419. d.skip()
  1420. return &UnmarshalTypeError{CBORType: t.String(), GoType: tInfo.nonPtrType.String()}
  1421. case cborTypeMap:
  1422. if tInfo.nonPtrKind == reflect.Struct {
  1423. return d.parseMapToStruct(v, tInfo)
  1424. } else if tInfo.nonPtrKind == reflect.Map {
  1425. return d.parseMapToMap(v, tInfo)
  1426. }
  1427. d.skip()
  1428. return &UnmarshalTypeError{CBORType: t.String(), GoType: tInfo.nonPtrType.String()}
  1429. }
  1430. return nil
  1431. }
  1432. func (d *decoder) parseToTag(v reflect.Value) error {
  1433. if d.nextCBORNil() {
  1434. // Decoding CBOR null and undefined to cbor.Tag is no-op.
  1435. d.skip()
  1436. return nil
  1437. }
  1438. t := d.nextCBORType()
  1439. if t != cborTypeTag {
  1440. d.skip()
  1441. return &UnmarshalTypeError{CBORType: t.String(), GoType: typeTag.String()}
  1442. }
  1443. // Unmarshal tag number
  1444. _, _, num := d.getHead()
  1445. // Unmarshal tag content
  1446. content, err := d.parse(false)
  1447. if err != nil {
  1448. return err
  1449. }
  1450. v.Set(reflect.ValueOf(Tag{num, content}))
  1451. return nil
  1452. }
  1453. // parseToTime decodes the current data item as a time.Time. The bool return value is false if and
  1454. // only if the destination value should remain unmodified.
  1455. func (d *decoder) parseToTime() (time.Time, bool, error) {
  1456. // Verify that tag number or absence of tag number is acceptable to specified timeTag.
  1457. if t := d.nextCBORType(); t == cborTypeTag {
  1458. if d.dm.timeTag == DecTagIgnored {
  1459. // Skip all enclosing tags
  1460. for t == cborTypeTag {
  1461. d.getHead()
  1462. t = d.nextCBORType()
  1463. }
  1464. if d.nextCBORNil() {
  1465. d.skip()
  1466. return time.Time{}, false, nil
  1467. }
  1468. } else {
  1469. // Read tag number
  1470. _, _, tagNum := d.getHead()
  1471. if tagNum != 0 && tagNum != 1 {
  1472. d.skip() // skip tag content
  1473. return time.Time{}, false, errors.New("cbor: wrong tag number for time.Time, got " + strconv.Itoa(int(tagNum)) + ", expect 0 or 1")
  1474. }
  1475. }
  1476. } else {
  1477. if d.dm.timeTag == DecTagRequired {
  1478. d.skip()
  1479. return time.Time{}, false, &UnmarshalTypeError{CBORType: t.String(), GoType: typeTime.String(), errorMsg: "expect CBOR tag value"}
  1480. }
  1481. }
  1482. switch t := d.nextCBORType(); t {
  1483. case cborTypeByteString:
  1484. if d.dm.byteStringToTime == ByteStringToTimeAllowed {
  1485. b, _ := d.parseByteString()
  1486. t, err := time.Parse(time.RFC3339, string(b))
  1487. if err != nil {
  1488. return time.Time{}, false, fmt.Errorf("cbor: cannot set %q for time.Time: %w", string(b), err)
  1489. }
  1490. return t, true, nil
  1491. }
  1492. return time.Time{}, false, &UnmarshalTypeError{CBORType: t.String(), GoType: typeTime.String()}
  1493. case cborTypeTextString:
  1494. s, err := d.parseTextString()
  1495. if err != nil {
  1496. return time.Time{}, false, err
  1497. }
  1498. t, err := time.Parse(time.RFC3339, string(s))
  1499. if err != nil {
  1500. return time.Time{}, false, errors.New("cbor: cannot set " + string(s) + " for time.Time: " + err.Error())
  1501. }
  1502. return t, true, nil
  1503. case cborTypePositiveInt:
  1504. _, _, val := d.getHead()
  1505. if val > math.MaxInt64 {
  1506. return time.Time{}, false, &UnmarshalTypeError{
  1507. CBORType: t.String(),
  1508. GoType: typeTime.String(),
  1509. errorMsg: fmt.Sprintf("%d overflows Go's int64", val),
  1510. }
  1511. }
  1512. return time.Unix(int64(val), 0), true, nil
  1513. case cborTypeNegativeInt:
  1514. _, _, val := d.getHead()
  1515. if val > math.MaxInt64 {
  1516. if val == math.MaxUint64 {
  1517. // Maximum absolute value representable by negative integer is 2^64,
  1518. // not 2^64-1, so it overflows uint64.
  1519. return time.Time{}, false, &UnmarshalTypeError{
  1520. CBORType: t.String(),
  1521. GoType: typeTime.String(),
  1522. errorMsg: "-18446744073709551616 overflows Go's int64",
  1523. }
  1524. }
  1525. return time.Time{}, false, &UnmarshalTypeError{
  1526. CBORType: t.String(),
  1527. GoType: typeTime.String(),
  1528. errorMsg: fmt.Sprintf("-%d overflows Go's int64", val+1),
  1529. }
  1530. }
  1531. return time.Unix(int64(-1)^int64(val), 0), true, nil
  1532. case cborTypePrimitives:
  1533. _, ai, val := d.getHead()
  1534. var f float64
  1535. switch ai {
  1536. case additionalInformationAsFloat16:
  1537. f = float64(float16.Frombits(uint16(val)).Float32())
  1538. case additionalInformationAsFloat32:
  1539. f = float64(math.Float32frombits(uint32(val)))
  1540. case additionalInformationAsFloat64:
  1541. f = math.Float64frombits(val)
  1542. default:
  1543. return time.Time{}, false, &UnmarshalTypeError{CBORType: t.String(), GoType: typeTime.String()}
  1544. }
  1545. if math.IsNaN(f) || math.IsInf(f, 0) {
  1546. // https://www.rfc-editor.org/rfc/rfc8949.html#section-3.4.2-6
  1547. return time.Time{}, true, nil
  1548. }
  1549. seconds, fractional := math.Modf(f)
  1550. return time.Unix(int64(seconds), int64(fractional*1e9)), true, nil
  1551. default:
  1552. return time.Time{}, false, &UnmarshalTypeError{CBORType: t.String(), GoType: typeTime.String()}
  1553. }
  1554. }
  1555. // parseToUnmarshaler parses CBOR data to value implementing Unmarshaler interface.
  1556. // It assumes data is well-formed, and does not perform bounds checking.
  1557. func (d *decoder) parseToUnmarshaler(v reflect.Value) error {
  1558. if d.nextCBORNil() && v.Kind() == reflect.Pointer && v.IsNil() {
  1559. d.skip()
  1560. return nil
  1561. }
  1562. if v.Kind() != reflect.Pointer && v.CanAddr() {
  1563. v = v.Addr()
  1564. }
  1565. if u, ok := v.Interface().(Unmarshaler); ok {
  1566. start := d.off
  1567. d.skip()
  1568. return u.UnmarshalCBOR(d.data[start:d.off])
  1569. }
  1570. d.skip()
  1571. return errors.New("cbor: failed to assert " + v.Type().String() + " as cbor.Unmarshaler")
  1572. }
  1573. // parseToUnexportedUnmarshaler parses CBOR data to value implementing unmarshaler interface.
  1574. // It assumes data is well-formed, and does not perform bounds checking.
  1575. func (d *decoder) parseToUnexportedUnmarshaler(v reflect.Value) error {
  1576. if d.nextCBORNil() && v.Kind() == reflect.Pointer && v.IsNil() {
  1577. d.skip()
  1578. return nil
  1579. }
  1580. if v.Kind() != reflect.Pointer && v.CanAddr() {
  1581. v = v.Addr()
  1582. }
  1583. if u, ok := v.Interface().(unmarshaler); ok {
  1584. start := d.off
  1585. d.skip()
  1586. return u.unmarshalCBOR(d.data[start:d.off])
  1587. }
  1588. d.skip()
  1589. return errors.New("cbor: failed to assert " + v.Type().String() + " as cbor.unmarshaler")
  1590. }
  1591. // parseToJSONUnmarshaler parses CBOR data to be transcoded to JSON and passed to the value's
  1592. // implementation of the json.Unmarshaler interface. It assumes data is well-formed, and does not
  1593. // perform bounds checking.
  1594. func (d *decoder) parseToJSONUnmarshaler(v reflect.Value) error {
  1595. if d.nextCBORNil() && v.Kind() == reflect.Pointer && v.IsNil() {
  1596. d.skip()
  1597. return nil
  1598. }
  1599. if v.Kind() != reflect.Pointer && v.CanAddr() {
  1600. v = v.Addr()
  1601. }
  1602. if u, ok := v.Interface().(jsonUnmarshaler); ok {
  1603. start := d.off
  1604. d.skip()
  1605. e := getEncodeBuffer()
  1606. defer putEncodeBuffer(e)
  1607. if err := d.dm.jsonUnmarshalerTranscoder.Transcode(e, bytes.NewReader(d.data[start:d.off])); err != nil {
  1608. return &TranscodeError{err: err, rtype: v.Type(), sourceFormat: "cbor", targetFormat: "json"}
  1609. }
  1610. return u.UnmarshalJSON(e.Bytes())
  1611. }
  1612. d.skip()
  1613. return errors.New("cbor: failed to assert " + v.Type().String() + " as json.Unmarshaler")
  1614. }
  1615. // parse parses CBOR data and returns value in default Go type.
  1616. // It assumes data is well-formed, and does not perform bounds checking.
  1617. func (d *decoder) parse(skipSelfDescribedTag bool) (any, error) { //nolint:gocyclo
  1618. // Strip self-described CBOR tag number.
  1619. if skipSelfDescribedTag {
  1620. for d.nextCBORType() == cborTypeTag {
  1621. off := d.off
  1622. _, _, tagNum := d.getHead()
  1623. if tagNum != tagNumSelfDescribedCBOR {
  1624. d.off = off
  1625. break
  1626. }
  1627. }
  1628. }
  1629. // Check validity of supported built-in tags.
  1630. off := d.off
  1631. for d.nextCBORType() == cborTypeTag {
  1632. _, _, tagNum := d.getHead()
  1633. if err := validBuiltinTag(tagNum, d.data[d.off]); err != nil {
  1634. d.skip()
  1635. return nil, err
  1636. }
  1637. }
  1638. d.off = off
  1639. t := d.nextCBORType()
  1640. switch t {
  1641. case cborTypePositiveInt:
  1642. _, _, val := d.getHead()
  1643. switch d.dm.intDec {
  1644. case IntDecConvertNone:
  1645. return val, nil
  1646. case IntDecConvertSigned, IntDecConvertSignedOrFail:
  1647. if val > math.MaxInt64 {
  1648. return nil, &UnmarshalTypeError{
  1649. CBORType: t.String(),
  1650. GoType: reflect.TypeOf(int64(0)).String(),
  1651. errorMsg: strconv.FormatUint(val, 10) + " overflows Go's int64",
  1652. }
  1653. }
  1654. return int64(val), nil
  1655. case IntDecConvertSignedOrBigInt:
  1656. if val > math.MaxInt64 {
  1657. bi := new(big.Int).SetUint64(val)
  1658. if d.dm.bigIntDec == BigIntDecodePointer {
  1659. return bi, nil
  1660. }
  1661. return *bi, nil
  1662. }
  1663. return int64(val), nil
  1664. default:
  1665. // not reachable
  1666. }
  1667. case cborTypeNegativeInt:
  1668. _, _, val := d.getHead()
  1669. if val > math.MaxInt64 {
  1670. // CBOR negative integer value overflows Go int64, use big.Int instead.
  1671. bi := new(big.Int).SetUint64(val)
  1672. bi.Add(bi, big.NewInt(1))
  1673. bi.Neg(bi)
  1674. if d.dm.intDec == IntDecConvertSignedOrFail {
  1675. return nil, &UnmarshalTypeError{
  1676. CBORType: t.String(),
  1677. GoType: reflect.TypeOf(int64(0)).String(),
  1678. errorMsg: bi.String() + " overflows Go's int64",
  1679. }
  1680. }
  1681. if d.dm.bigIntDec == BigIntDecodePointer {
  1682. return bi, nil
  1683. }
  1684. return *bi, nil
  1685. }
  1686. nValue := int64(-1) ^ int64(val)
  1687. return nValue, nil
  1688. case cborTypeByteString:
  1689. b, copied := d.parseByteString()
  1690. var effectiveByteStringType = d.dm.defaultByteStringType
  1691. if effectiveByteStringType == nil {
  1692. effectiveByteStringType = typeByteSlice
  1693. }
  1694. b, converted, err := d.applyByteStringTextConversion(b, effectiveByteStringType)
  1695. if err != nil {
  1696. return nil, err
  1697. }
  1698. copied = copied || converted
  1699. switch effectiveByteStringType {
  1700. case typeByteSlice:
  1701. if copied {
  1702. return b, nil
  1703. }
  1704. clone := make([]byte, len(b))
  1705. copy(clone, b)
  1706. return clone, nil
  1707. case typeString:
  1708. return string(b), nil
  1709. default:
  1710. if copied || d.dm.defaultByteStringType.Kind() == reflect.String {
  1711. // Avoid an unnecessary copy since the conversion to string must
  1712. // copy the underlying bytes.
  1713. return reflect.ValueOf(b).Convert(d.dm.defaultByteStringType).Interface(), nil
  1714. }
  1715. clone := make([]byte, len(b))
  1716. copy(clone, b)
  1717. return reflect.ValueOf(clone).Convert(d.dm.defaultByteStringType).Interface(), nil
  1718. }
  1719. case cborTypeTextString:
  1720. b, err := d.parseTextString()
  1721. if err != nil {
  1722. return nil, err
  1723. }
  1724. return string(b), nil
  1725. case cborTypeTag:
  1726. tagOff := d.off
  1727. _, _, tagNum := d.getHead()
  1728. contentOff := d.off
  1729. switch tagNum {
  1730. case tagNumRFC3339Time, tagNumEpochTime:
  1731. d.off = tagOff
  1732. tm, _, err := d.parseToTime()
  1733. if err != nil {
  1734. return nil, err
  1735. }
  1736. switch d.dm.timeTagToAny {
  1737. case TimeTagToTime:
  1738. return tm, nil
  1739. case TimeTagToRFC3339:
  1740. if tagNum == 1 {
  1741. tm = tm.UTC()
  1742. }
  1743. // Call time.MarshalText() to format decoded time to RFC3339 format,
  1744. // and return error on time value that cannot be represented in
  1745. // RFC3339 format. E.g. year cannot exceed 9999, etc.
  1746. text, err := tm.Truncate(time.Second).MarshalText()
  1747. if err != nil {
  1748. return nil, fmt.Errorf("cbor: decoded time cannot be represented in RFC3339 format: %v", err)
  1749. }
  1750. return string(text), nil
  1751. case TimeTagToRFC3339Nano:
  1752. if tagNum == 1 {
  1753. tm = tm.UTC()
  1754. }
  1755. // Call time.MarshalText() to format decoded time to RFC3339 format,
  1756. // and return error on time value that cannot be represented in
  1757. // RFC3339 format with sub-second precision.
  1758. text, err := tm.MarshalText()
  1759. if err != nil {
  1760. return nil, fmt.Errorf("cbor: decoded time cannot be represented in RFC3339 format with sub-second precision: %v", err)
  1761. }
  1762. return string(text), nil
  1763. default:
  1764. // not reachable
  1765. }
  1766. case tagNumUnsignedBignum:
  1767. b, _ := d.parseByteString()
  1768. bi := new(big.Int).SetBytes(b)
  1769. if d.dm.bigIntDec == BigIntDecodePointer {
  1770. return bi, nil
  1771. }
  1772. return *bi, nil
  1773. case tagNumNegativeBignum:
  1774. b, _ := d.parseByteString()
  1775. bi := new(big.Int).SetBytes(b)
  1776. bi.Add(bi, big.NewInt(1))
  1777. bi.Neg(bi)
  1778. if d.dm.bigIntDec == BigIntDecodePointer {
  1779. return bi, nil
  1780. }
  1781. return *bi, nil
  1782. case tagNumExpectedLaterEncodingBase64URL, tagNumExpectedLaterEncodingBase64, tagNumExpectedLaterEncodingBase16:
  1783. // If conversion for interoperability with text encodings is not configured,
  1784. // treat tags 21-23 as unregistered tags.
  1785. if d.dm.byteStringToString == ByteStringToStringAllowedWithExpectedLaterEncoding ||
  1786. d.dm.byteStringExpectedFormat != ByteStringExpectedFormatNone {
  1787. d.expectedLaterEncodingTags = append(d.expectedLaterEncodingTags, tagNum)
  1788. defer func() {
  1789. d.expectedLaterEncodingTags = d.expectedLaterEncodingTags[:len(d.expectedLaterEncodingTags)-1]
  1790. }()
  1791. return d.parse(false)
  1792. }
  1793. }
  1794. if d.dm.tags != nil {
  1795. // Parse to specified type if tag number is registered.
  1796. tagNums := []uint64{tagNum}
  1797. for d.nextCBORType() == cborTypeTag {
  1798. _, _, num := d.getHead()
  1799. tagNums = append(tagNums, num)
  1800. }
  1801. registeredType := d.dm.tags.getTypeFromTagNum(tagNums)
  1802. if registeredType != nil {
  1803. d.off = tagOff
  1804. rv := reflect.New(registeredType)
  1805. if err := d.parseToValue(rv.Elem(), getTypeInfo(registeredType)); err != nil {
  1806. return nil, err
  1807. }
  1808. return rv.Elem().Interface(), nil
  1809. }
  1810. }
  1811. // Parse tag content
  1812. d.off = contentOff
  1813. content, err := d.parse(false)
  1814. if err != nil {
  1815. return nil, err
  1816. }
  1817. if d.dm.unrecognizedTagToAny == UnrecognizedTagContentToAny {
  1818. return content, nil
  1819. }
  1820. return Tag{tagNum, content}, nil
  1821. case cborTypePrimitives:
  1822. _, ai, val := d.getHead()
  1823. if ai <= 24 && d.dm.simpleValues.rejected[SimpleValue(val)] {
  1824. return nil, &UnacceptableDataItemError{
  1825. CBORType: t.String(),
  1826. Message: "simple value " + strconv.FormatInt(int64(val), 10) + " is not recognized",
  1827. }
  1828. }
  1829. if ai < 20 || ai == 24 {
  1830. return SimpleValue(val), nil
  1831. }
  1832. switch ai {
  1833. case additionalInformationAsFalse,
  1834. additionalInformationAsTrue:
  1835. return (ai == additionalInformationAsTrue), nil
  1836. case additionalInformationAsNull,
  1837. additionalInformationAsUndefined:
  1838. return nil, nil
  1839. case additionalInformationAsFloat16:
  1840. f := float64(float16.Frombits(uint16(val)).Float32())
  1841. return f, nil
  1842. case additionalInformationAsFloat32:
  1843. f := float64(math.Float32frombits(uint32(val)))
  1844. return f, nil
  1845. case additionalInformationAsFloat64:
  1846. f := math.Float64frombits(val)
  1847. return f, nil
  1848. }
  1849. case cborTypeArray:
  1850. return d.parseArray()
  1851. case cborTypeMap:
  1852. if d.dm.defaultMapType != nil {
  1853. m := reflect.New(d.dm.defaultMapType)
  1854. err := d.parseToValue(m, getTypeInfo(m.Elem().Type()))
  1855. if err != nil {
  1856. return nil, err
  1857. }
  1858. return m.Elem().Interface(), nil
  1859. }
  1860. return d.parseMap()
  1861. }
  1862. return nil, nil
  1863. }
  1864. // parseByteString parses a CBOR encoded byte string. The returned byte slice
  1865. // may be backed directly by the input. The second return value will be true if
  1866. // and only if the slice is backed by a copy of the input. Callers are
  1867. // responsible for making a copy if necessary.
  1868. func (d *decoder) parseByteString() ([]byte, bool) {
  1869. _, _, val, indefiniteLength := d.getHeadWithIndefiniteLengthFlag()
  1870. if !indefiniteLength {
  1871. b := d.data[d.off : d.off+int(val)]
  1872. d.off += int(val)
  1873. return b, false
  1874. }
  1875. // Process indefinite length string chunks.
  1876. b := []byte{}
  1877. for !d.foundBreak() {
  1878. _, _, val = d.getHead()
  1879. b = append(b, d.data[d.off:d.off+int(val)]...)
  1880. d.off += int(val)
  1881. }
  1882. return b, true
  1883. }
  1884. // applyByteStringTextConversion converts bytes read from a byte string to or from a configured text
  1885. // encoding. If no transformation was performed (because it was not required), the original byte
  1886. // slice is returned and the bool return value is false. Otherwise, a new slice containing the
  1887. // converted bytes is returned along with the bool value true.
  1888. func (d *decoder) applyByteStringTextConversion(
  1889. src []byte,
  1890. dstType reflect.Type,
  1891. ) (
  1892. dst []byte,
  1893. transformed bool,
  1894. err error,
  1895. ) {
  1896. switch dstType.Kind() {
  1897. case reflect.String:
  1898. if d.dm.byteStringToString != ByteStringToStringAllowedWithExpectedLaterEncoding || len(d.expectedLaterEncodingTags) == 0 {
  1899. return src, false, nil
  1900. }
  1901. switch d.expectedLaterEncodingTags[len(d.expectedLaterEncodingTags)-1] {
  1902. case tagNumExpectedLaterEncodingBase64URL:
  1903. encoded := make([]byte, base64.RawURLEncoding.EncodedLen(len(src)))
  1904. base64.RawURLEncoding.Encode(encoded, src)
  1905. return encoded, true, nil
  1906. case tagNumExpectedLaterEncodingBase64:
  1907. encoded := make([]byte, base64.StdEncoding.EncodedLen(len(src)))
  1908. base64.StdEncoding.Encode(encoded, src)
  1909. return encoded, true, nil
  1910. case tagNumExpectedLaterEncodingBase16:
  1911. encoded := make([]byte, hex.EncodedLen(len(src)))
  1912. hex.Encode(encoded, src)
  1913. return encoded, true, nil
  1914. default:
  1915. // If this happens, there is a bug: the decoder has pushed an invalid
  1916. // "expected later encoding" tag to the stack.
  1917. panic(fmt.Sprintf("unrecognized expected later encoding tag: %d", d.expectedLaterEncodingTags))
  1918. }
  1919. case reflect.Slice:
  1920. if dstType.Elem().Kind() != reflect.Uint8 || len(d.expectedLaterEncodingTags) > 0 {
  1921. // Either the destination is not a slice of bytes, or the encoder that
  1922. // produced the input indicated an expected text encoding tag and therefore
  1923. // the content of the byte string has NOT been text encoded.
  1924. return src, false, nil
  1925. }
  1926. switch d.dm.byteStringExpectedFormat {
  1927. case ByteStringExpectedBase64URL:
  1928. decoded := make([]byte, base64.RawURLEncoding.DecodedLen(len(src)))
  1929. n, err := base64.RawURLEncoding.Decode(decoded, src)
  1930. if err != nil {
  1931. return nil, false, newByteStringExpectedFormatError(ByteStringExpectedBase64URL, err)
  1932. }
  1933. return decoded[:n], true, nil
  1934. case ByteStringExpectedBase64:
  1935. decoded := make([]byte, base64.StdEncoding.DecodedLen(len(src)))
  1936. n, err := base64.StdEncoding.Decode(decoded, src)
  1937. if err != nil {
  1938. return nil, false, newByteStringExpectedFormatError(ByteStringExpectedBase64, err)
  1939. }
  1940. return decoded[:n], true, nil
  1941. case ByteStringExpectedBase16:
  1942. decoded := make([]byte, hex.DecodedLen(len(src)))
  1943. n, err := hex.Decode(decoded, src)
  1944. if err != nil {
  1945. return nil, false, newByteStringExpectedFormatError(ByteStringExpectedBase16, err)
  1946. }
  1947. return decoded[:n], true, nil
  1948. }
  1949. }
  1950. return src, false, nil
  1951. }
  1952. // parseTextString parses CBOR encoded text string. It returns a byte slice
  1953. // to prevent creating an extra copy of string. Caller should wrap returned
  1954. // byte slice as string when needed.
  1955. func (d *decoder) parseTextString() ([]byte, error) {
  1956. _, _, val, indefiniteLength := d.getHeadWithIndefiniteLengthFlag()
  1957. if !indefiniteLength {
  1958. b := d.data[d.off : d.off+int(val)]
  1959. d.off += int(val)
  1960. if d.dm.utf8 == UTF8RejectInvalid && !utf8.Valid(b) {
  1961. return nil, &SemanticError{"cbor: invalid UTF-8 string"}
  1962. }
  1963. return b, nil
  1964. }
  1965. // Process indefinite length string chunks.
  1966. b := []byte{}
  1967. for !d.foundBreak() {
  1968. _, _, val = d.getHead()
  1969. x := d.data[d.off : d.off+int(val)]
  1970. d.off += int(val)
  1971. if d.dm.utf8 == UTF8RejectInvalid && !utf8.Valid(x) {
  1972. for !d.foundBreak() {
  1973. d.skip() // Skip remaining chunk on error
  1974. }
  1975. return nil, &SemanticError{"cbor: invalid UTF-8 string"}
  1976. }
  1977. b = append(b, x...)
  1978. }
  1979. return b, nil
  1980. }
  1981. func (d *decoder) parseArray() ([]any, error) {
  1982. _, _, val, indefiniteLength := d.getHeadWithIndefiniteLengthFlag()
  1983. hasSize := !indefiniteLength
  1984. count := int(val)
  1985. if !hasSize {
  1986. count = d.numOfItemsUntilBreak() // peek ahead to get array size to preallocate slice for better performance
  1987. }
  1988. v := make([]any, count)
  1989. var e any
  1990. var err, lastErr error
  1991. for i := 0; (hasSize && i < count) || (!hasSize && !d.foundBreak()); i++ {
  1992. if e, lastErr = d.parse(true); lastErr != nil {
  1993. if err == nil {
  1994. err = lastErr
  1995. }
  1996. continue
  1997. }
  1998. v[i] = e
  1999. }
  2000. return v, err
  2001. }
  2002. func (d *decoder) parseArrayToSlice(v reflect.Value, tInfo *typeInfo) error {
  2003. _, _, val, indefiniteLength := d.getHeadWithIndefiniteLengthFlag()
  2004. hasSize := !indefiniteLength
  2005. count := int(val)
  2006. if !hasSize {
  2007. count = d.numOfItemsUntilBreak() // peek ahead to get array size to preallocate slice for better performance
  2008. }
  2009. if v.IsNil() || v.Cap() < count || count == 0 {
  2010. v.Set(reflect.MakeSlice(tInfo.nonPtrType, count, count))
  2011. }
  2012. v.SetLen(count)
  2013. var err error
  2014. for i := 0; (hasSize && i < count) || (!hasSize && !d.foundBreak()); i++ {
  2015. if lastErr := d.parseToValue(v.Index(i), tInfo.elemTypeInfo); lastErr != nil {
  2016. if err == nil {
  2017. err = lastErr
  2018. }
  2019. }
  2020. }
  2021. return err
  2022. }
  2023. func (d *decoder) parseArrayToArray(v reflect.Value, tInfo *typeInfo) error {
  2024. _, _, val, indefiniteLength := d.getHeadWithIndefiniteLengthFlag()
  2025. hasSize := !indefiniteLength
  2026. count := int(val)
  2027. gi := 0
  2028. vLen := v.Len()
  2029. var err error
  2030. for ci := 0; (hasSize && ci < count) || (!hasSize && !d.foundBreak()); ci++ {
  2031. if gi < vLen {
  2032. // Read CBOR array element and set array element
  2033. if lastErr := d.parseToValue(v.Index(gi), tInfo.elemTypeInfo); lastErr != nil {
  2034. if err == nil {
  2035. err = lastErr
  2036. }
  2037. }
  2038. gi++
  2039. } else {
  2040. d.skip() // Skip remaining CBOR array element
  2041. }
  2042. }
  2043. // Set remaining Go array elements to zero values.
  2044. if gi < vLen {
  2045. for ; gi < vLen; gi++ {
  2046. v.Index(gi).SetZero()
  2047. }
  2048. }
  2049. return err
  2050. }
  2051. func (d *decoder) parseMap() (any, error) {
  2052. _, _, val, indefiniteLength := d.getHeadWithIndefiniteLengthFlag()
  2053. hasSize := !indefiniteLength
  2054. count := int(val)
  2055. m := make(map[any]any)
  2056. var k, e any
  2057. var err, lastErr error
  2058. keyCount := 0
  2059. for i := 0; (hasSize && i < count) || (!hasSize && !d.foundBreak()); i++ {
  2060. // Parse CBOR map key.
  2061. if k, lastErr = d.parse(true); lastErr != nil {
  2062. if err == nil {
  2063. err = lastErr
  2064. }
  2065. d.skip()
  2066. continue
  2067. }
  2068. // Detect if CBOR map key can be used as Go map key.
  2069. rv := reflect.ValueOf(k)
  2070. if !isHashableValue(rv) {
  2071. var converted bool
  2072. if d.dm.mapKeyByteString == MapKeyByteStringAllowed {
  2073. k, converted = convertByteSliceToByteString(k)
  2074. }
  2075. if !converted {
  2076. if err == nil {
  2077. err = &InvalidMapKeyTypeError{rv.Type().String()}
  2078. }
  2079. d.skip()
  2080. continue
  2081. }
  2082. }
  2083. // Parse CBOR map value.
  2084. if e, lastErr = d.parse(true); lastErr != nil {
  2085. if err == nil {
  2086. err = lastErr
  2087. }
  2088. continue
  2089. }
  2090. // Add key-value pair to Go map.
  2091. m[k] = e
  2092. // Detect duplicate map key.
  2093. if d.dm.dupMapKey == DupMapKeyEnforcedAPF {
  2094. newKeyCount := len(m)
  2095. if newKeyCount == keyCount {
  2096. m[k] = nil
  2097. err = &DupMapKeyError{k, i}
  2098. i++
  2099. // skip the rest of the map
  2100. for ; (hasSize && i < count) || (!hasSize && !d.foundBreak()); i++ {
  2101. d.skip() // Skip map key
  2102. d.skip() // Skip map value
  2103. }
  2104. return m, err
  2105. }
  2106. keyCount = newKeyCount
  2107. }
  2108. }
  2109. return m, err
  2110. }
  2111. func (d *decoder) parseMapToMap(v reflect.Value, tInfo *typeInfo) error { //nolint:gocyclo
  2112. _, _, val, indefiniteLength := d.getHeadWithIndefiniteLengthFlag()
  2113. hasSize := !indefiniteLength
  2114. count := int(val)
  2115. if v.IsNil() {
  2116. mapsize := count
  2117. if !hasSize {
  2118. mapsize = 0
  2119. }
  2120. v.Set(reflect.MakeMapWithSize(tInfo.nonPtrType, mapsize))
  2121. }
  2122. keyType, eleType := tInfo.keyTypeInfo.typ, tInfo.elemTypeInfo.typ
  2123. reuseKey, reuseEle := isImmutableKind(tInfo.keyTypeInfo.kind), isImmutableKind(tInfo.elemTypeInfo.kind)
  2124. var keyValue, eleValue reflect.Value
  2125. keyIsInterfaceType := keyType == typeIntf // If key type is interface{}, need to check if key value is hashable.
  2126. var err, lastErr error
  2127. keyCount := v.Len()
  2128. var existingKeys map[any]bool // Store existing map keys, used for detecting duplicate map key.
  2129. if d.dm.dupMapKey == DupMapKeyEnforcedAPF {
  2130. existingKeys = make(map[any]bool, keyCount)
  2131. if keyCount > 0 {
  2132. vKeys := v.MapKeys()
  2133. for i := 0; i < len(vKeys); i++ {
  2134. existingKeys[vKeys[i].Interface()] = true
  2135. }
  2136. }
  2137. }
  2138. for i := 0; (hasSize && i < count) || (!hasSize && !d.foundBreak()); i++ {
  2139. // Parse CBOR map key.
  2140. if !keyValue.IsValid() {
  2141. keyValue = reflect.New(keyType).Elem()
  2142. } else if !reuseKey {
  2143. keyValue.SetZero()
  2144. }
  2145. if lastErr = d.parseToValue(keyValue, tInfo.keyTypeInfo); lastErr != nil {
  2146. if err == nil {
  2147. err = lastErr
  2148. }
  2149. d.skip()
  2150. continue
  2151. }
  2152. // Detect if CBOR map key can be used as Go map key.
  2153. if keyIsInterfaceType && keyValue.Elem().IsValid() {
  2154. if !isHashableValue(keyValue.Elem()) {
  2155. var converted bool
  2156. if d.dm.mapKeyByteString == MapKeyByteStringAllowed {
  2157. var k any
  2158. k, converted = convertByteSliceToByteString(keyValue.Elem().Interface())
  2159. if converted {
  2160. keyValue.Set(reflect.ValueOf(k))
  2161. }
  2162. }
  2163. if !converted {
  2164. if err == nil {
  2165. err = &InvalidMapKeyTypeError{keyValue.Elem().Type().String()}
  2166. }
  2167. d.skip()
  2168. continue
  2169. }
  2170. }
  2171. }
  2172. // Parse CBOR map value.
  2173. if !eleValue.IsValid() {
  2174. eleValue = reflect.New(eleType).Elem()
  2175. } else if !reuseEle {
  2176. eleValue.SetZero()
  2177. }
  2178. if lastErr := d.parseToValue(eleValue, tInfo.elemTypeInfo); lastErr != nil {
  2179. if err == nil {
  2180. err = lastErr
  2181. }
  2182. continue
  2183. }
  2184. // Add key-value pair to Go map.
  2185. v.SetMapIndex(keyValue, eleValue)
  2186. // Detect duplicate map key.
  2187. if d.dm.dupMapKey == DupMapKeyEnforcedAPF {
  2188. newKeyCount := v.Len()
  2189. if newKeyCount == keyCount {
  2190. kvi := keyValue.Interface()
  2191. if !existingKeys[kvi] {
  2192. v.SetMapIndex(keyValue, reflect.New(eleType).Elem())
  2193. err = &DupMapKeyError{kvi, i}
  2194. i++
  2195. // skip the rest of the map
  2196. for ; (hasSize && i < count) || (!hasSize && !d.foundBreak()); i++ {
  2197. d.skip() // skip map key
  2198. d.skip() // skip map value
  2199. }
  2200. return err
  2201. }
  2202. delete(existingKeys, kvi)
  2203. }
  2204. keyCount = newKeyCount
  2205. }
  2206. }
  2207. return err
  2208. }
  2209. func (d *decoder) parseArrayToStruct(v reflect.Value, tInfo *typeInfo) error {
  2210. structType := getDecodingStructType(tInfo.nonPtrType)
  2211. if structType.err != nil {
  2212. return structType.err
  2213. }
  2214. if !structType.toArray {
  2215. t := d.nextCBORType()
  2216. d.skip()
  2217. return &UnmarshalTypeError{
  2218. CBORType: t.String(),
  2219. GoType: tInfo.nonPtrType.String(),
  2220. errorMsg: "cannot decode CBOR array to struct without toarray option",
  2221. }
  2222. }
  2223. start := d.off
  2224. _, _, val, indefiniteLength := d.getHeadWithIndefiniteLengthFlag()
  2225. hasSize := !indefiniteLength
  2226. count := int(val)
  2227. if !hasSize {
  2228. count = d.numOfItemsUntilBreak() // peek ahead to get array size
  2229. }
  2230. if count != len(structType.fields) {
  2231. d.off = start
  2232. d.skip()
  2233. return &UnmarshalTypeError{
  2234. CBORType: cborTypeArray.String(),
  2235. GoType: tInfo.typ.String(),
  2236. errorMsg: "cannot decode CBOR array to struct with different number of elements",
  2237. }
  2238. }
  2239. var err, lastErr error
  2240. for i := 0; (hasSize && i < count) || (!hasSize && !d.foundBreak()); i++ {
  2241. f := structType.fields[i]
  2242. // Get field value by index
  2243. var fv reflect.Value
  2244. if len(f.idx) == 1 {
  2245. fv = v.Field(f.idx[0])
  2246. } else {
  2247. fv, lastErr = getFieldValue(v, f.idx, func(v reflect.Value) (reflect.Value, error) {
  2248. // Return a new value for embedded field null pointer to point to, or return error.
  2249. if !v.CanSet() {
  2250. return reflect.Value{}, errors.New("cbor: cannot set embedded pointer to unexported struct: " + v.Type().String())
  2251. }
  2252. v.Set(reflect.New(v.Type().Elem()))
  2253. return v, nil
  2254. })
  2255. if lastErr != nil && err == nil {
  2256. err = lastErr
  2257. }
  2258. if !fv.IsValid() {
  2259. d.skip()
  2260. continue
  2261. }
  2262. }
  2263. if lastErr = d.parseToValue(fv, f.typInfo); lastErr != nil {
  2264. if err == nil {
  2265. if typeError, ok := lastErr.(*UnmarshalTypeError); ok {
  2266. typeError.StructFieldName = tInfo.typ.String() + "." + f.name
  2267. err = typeError
  2268. } else {
  2269. err = lastErr
  2270. }
  2271. }
  2272. }
  2273. }
  2274. return err
  2275. }
  2276. // parseMapToStruct needs to be fast so gocyclo can be ignored for now.
  2277. func (d *decoder) parseMapToStruct(v reflect.Value, tInfo *typeInfo) error { //nolint:gocyclo
  2278. structType := getDecodingStructType(tInfo.nonPtrType)
  2279. if structType.err != nil {
  2280. return structType.err
  2281. }
  2282. if structType.toArray {
  2283. t := d.nextCBORType()
  2284. d.skip()
  2285. return &UnmarshalTypeError{
  2286. CBORType: t.String(),
  2287. GoType: tInfo.nonPtrType.String(),
  2288. errorMsg: "cannot decode CBOR map to struct with toarray option",
  2289. }
  2290. }
  2291. var err, lastErr error
  2292. // Get CBOR map size
  2293. _, _, val, indefiniteLength := d.getHeadWithIndefiniteLengthFlag()
  2294. hasSize := !indefiniteLength
  2295. count := int(val)
  2296. // Keeps track of matched struct fields
  2297. var foundFldIdx []bool
  2298. {
  2299. const maxStackFields = 128
  2300. if nfields := len(structType.fields); nfields <= maxStackFields {
  2301. // For structs with typical field counts, expect that this can be
  2302. // stack-allocated.
  2303. var a [maxStackFields]bool
  2304. foundFldIdx = a[:nfields]
  2305. } else {
  2306. foundFldIdx = make([]bool, len(structType.fields))
  2307. }
  2308. }
  2309. // Keeps track of CBOR map keys to detect duplicate map key
  2310. keyCount := 0
  2311. var mapKeys map[any]struct{}
  2312. errOnUnknownField := (d.dm.extraReturnErrors & ExtraDecErrorUnknownField) > 0
  2313. MapEntryLoop:
  2314. for j := 0; (hasSize && j < count) || (!hasSize && !d.foundBreak()); j++ {
  2315. var f *field
  2316. // If duplicate field detection is enabled and the key at index j did not match any
  2317. // field, k will hold the map key.
  2318. var k any
  2319. t := d.nextCBORType()
  2320. if t == cborTypeTextString || (t == cborTypeByteString && d.dm.fieldNameByteString == FieldNameByteStringAllowed) {
  2321. var keyBytes []byte
  2322. if t == cborTypeTextString {
  2323. keyBytes, lastErr = d.parseTextString()
  2324. if lastErr != nil {
  2325. if err == nil {
  2326. err = lastErr
  2327. }
  2328. d.skip() // skip value
  2329. continue
  2330. }
  2331. } else { // cborTypeByteString
  2332. keyBytes, _ = d.parseByteString()
  2333. }
  2334. // Check for exact match on field name.
  2335. if i, ok := structType.fieldIndicesByName[string(keyBytes)]; ok {
  2336. fld := structType.fields[i]
  2337. if !foundFldIdx[i] {
  2338. f = fld
  2339. foundFldIdx[i] = true
  2340. } else if d.dm.dupMapKey == DupMapKeyEnforcedAPF {
  2341. err = &DupMapKeyError{fld.name, j}
  2342. d.skip() // skip value
  2343. j++
  2344. // skip the rest of the map
  2345. for ; (hasSize && j < count) || (!hasSize && !d.foundBreak()); j++ {
  2346. d.skip()
  2347. d.skip()
  2348. }
  2349. return err
  2350. } else {
  2351. // discard repeated match
  2352. d.skip()
  2353. continue MapEntryLoop
  2354. }
  2355. }
  2356. // Find field with case-insensitive match
  2357. if f == nil && d.dm.fieldNameMatching == FieldNameMatchingPreferCaseSensitive {
  2358. keyLen := len(keyBytes)
  2359. keyString := string(keyBytes)
  2360. for i := 0; i < len(structType.fields); i++ {
  2361. fld := structType.fields[i]
  2362. if len(fld.name) == keyLen && strings.EqualFold(fld.name, keyString) {
  2363. if !foundFldIdx[i] {
  2364. f = fld
  2365. foundFldIdx[i] = true
  2366. } else if d.dm.dupMapKey == DupMapKeyEnforcedAPF {
  2367. err = &DupMapKeyError{keyString, j}
  2368. d.skip() // skip value
  2369. j++
  2370. // skip the rest of the map
  2371. for ; (hasSize && j < count) || (!hasSize && !d.foundBreak()); j++ {
  2372. d.skip()
  2373. d.skip()
  2374. }
  2375. return err
  2376. } else {
  2377. // discard repeated match
  2378. d.skip()
  2379. continue MapEntryLoop
  2380. }
  2381. break
  2382. }
  2383. }
  2384. }
  2385. if d.dm.dupMapKey == DupMapKeyEnforcedAPF && f == nil {
  2386. k = string(keyBytes)
  2387. }
  2388. } else if t <= cborTypeNegativeInt { // uint/int
  2389. var nameAsInt int64
  2390. if t == cborTypePositiveInt {
  2391. _, _, val := d.getHead()
  2392. nameAsInt = int64(val)
  2393. } else {
  2394. _, _, val := d.getHead()
  2395. if val > math.MaxInt64 {
  2396. if err == nil {
  2397. err = &UnmarshalTypeError{
  2398. CBORType: t.String(),
  2399. GoType: reflect.TypeOf(int64(0)).String(),
  2400. errorMsg: "-1-" + strconv.FormatUint(val, 10) + " overflows Go's int64",
  2401. }
  2402. }
  2403. d.skip() // skip value
  2404. continue
  2405. }
  2406. nameAsInt = int64(-1) ^ int64(val)
  2407. }
  2408. // Find field
  2409. for i := 0; i < len(structType.fields); i++ {
  2410. fld := structType.fields[i]
  2411. if fld.keyAsInt && fld.nameAsInt == nameAsInt {
  2412. if !foundFldIdx[i] {
  2413. f = fld
  2414. foundFldIdx[i] = true
  2415. } else if d.dm.dupMapKey == DupMapKeyEnforcedAPF {
  2416. err = &DupMapKeyError{nameAsInt, j}
  2417. d.skip() // skip value
  2418. j++
  2419. // skip the rest of the map
  2420. for ; (hasSize && j < count) || (!hasSize && !d.foundBreak()); j++ {
  2421. d.skip()
  2422. d.skip()
  2423. }
  2424. return err
  2425. } else {
  2426. // discard repeated match
  2427. d.skip()
  2428. continue MapEntryLoop
  2429. }
  2430. break
  2431. }
  2432. }
  2433. if d.dm.dupMapKey == DupMapKeyEnforcedAPF && f == nil {
  2434. k = nameAsInt
  2435. }
  2436. } else {
  2437. if err == nil {
  2438. err = &UnmarshalTypeError{
  2439. CBORType: t.String(),
  2440. GoType: reflect.TypeOf("").String(),
  2441. errorMsg: "map key is of type " + t.String() + " and cannot be used to match struct field name",
  2442. }
  2443. }
  2444. if d.dm.dupMapKey == DupMapKeyEnforcedAPF {
  2445. // parse key
  2446. k, lastErr = d.parse(true)
  2447. if lastErr != nil {
  2448. d.skip() // skip value
  2449. continue
  2450. }
  2451. // Detect if CBOR map key can be used as Go map key.
  2452. if !isHashableValue(reflect.ValueOf(k)) {
  2453. d.skip() // skip value
  2454. continue
  2455. }
  2456. } else {
  2457. d.skip() // skip key
  2458. }
  2459. }
  2460. if f == nil {
  2461. if errOnUnknownField {
  2462. err = &UnknownFieldError{j}
  2463. d.skip() // Skip value
  2464. j++
  2465. // skip the rest of the map
  2466. for ; (hasSize && j < count) || (!hasSize && !d.foundBreak()); j++ {
  2467. d.skip()
  2468. d.skip()
  2469. }
  2470. return err
  2471. }
  2472. // Two map keys that match the same struct field are immediately considered
  2473. // duplicates. This check detects duplicates between two map keys that do
  2474. // not match a struct field. If unknown field errors are enabled, then this
  2475. // check is never reached.
  2476. if d.dm.dupMapKey == DupMapKeyEnforcedAPF {
  2477. if mapKeys == nil {
  2478. mapKeys = make(map[any]struct{}, 1)
  2479. }
  2480. mapKeys[k] = struct{}{}
  2481. newKeyCount := len(mapKeys)
  2482. if newKeyCount == keyCount {
  2483. err = &DupMapKeyError{k, j}
  2484. d.skip() // skip value
  2485. j++
  2486. // skip the rest of the map
  2487. for ; (hasSize && j < count) || (!hasSize && !d.foundBreak()); j++ {
  2488. d.skip()
  2489. d.skip()
  2490. }
  2491. return err
  2492. }
  2493. keyCount = newKeyCount
  2494. }
  2495. d.skip() // Skip value
  2496. continue
  2497. }
  2498. // Get field value by index
  2499. var fv reflect.Value
  2500. if len(f.idx) == 1 {
  2501. fv = v.Field(f.idx[0])
  2502. } else {
  2503. fv, lastErr = getFieldValue(v, f.idx, func(v reflect.Value) (reflect.Value, error) {
  2504. // Return a new value for embedded field null pointer to point to, or return error.
  2505. if !v.CanSet() {
  2506. return reflect.Value{}, errors.New("cbor: cannot set embedded pointer to unexported struct: " + v.Type().String())
  2507. }
  2508. v.Set(reflect.New(v.Type().Elem()))
  2509. return v, nil
  2510. })
  2511. if lastErr != nil && err == nil {
  2512. err = lastErr
  2513. }
  2514. if !fv.IsValid() {
  2515. d.skip()
  2516. continue
  2517. }
  2518. }
  2519. if lastErr = d.parseToValue(fv, f.typInfo); lastErr != nil {
  2520. if err == nil {
  2521. if typeError, ok := lastErr.(*UnmarshalTypeError); ok {
  2522. typeError.StructFieldName = tInfo.nonPtrType.String() + "." + f.name
  2523. err = typeError
  2524. } else {
  2525. err = lastErr
  2526. }
  2527. }
  2528. }
  2529. }
  2530. return err
  2531. }
  2532. // validRegisteredTagNums verifies that tag numbers match registered tag numbers of type t.
  2533. // validRegisteredTagNums assumes next CBOR data type is tag. It scans all tag numbers, and stops at tag content.
  2534. func (d *decoder) validRegisteredTagNums(registeredTag *tagItem) error {
  2535. // Scan until next cbor data is tag content.
  2536. tagNums := make([]uint64, 0, 1)
  2537. for d.nextCBORType() == cborTypeTag {
  2538. _, _, val := d.getHead()
  2539. tagNums = append(tagNums, val)
  2540. }
  2541. if !registeredTag.equalTagNum(tagNums) {
  2542. return &WrongTagError{registeredTag.contentType, registeredTag.num, tagNums}
  2543. }
  2544. return nil
  2545. }
  2546. func (d *decoder) getRegisteredTagItem(vt reflect.Type) *tagItem {
  2547. if d.dm.tags != nil {
  2548. return d.dm.tags.getTagItemFromType(vt)
  2549. }
  2550. return nil
  2551. }
  2552. // skip moves data offset to the next item. skip assumes data is well-formed,
  2553. // and does not perform bounds checking.
  2554. func (d *decoder) skip() {
  2555. t, _, val, indefiniteLength := d.getHeadWithIndefiniteLengthFlag()
  2556. if indefiniteLength {
  2557. switch t {
  2558. case cborTypeByteString, cborTypeTextString, cborTypeArray, cborTypeMap:
  2559. for {
  2560. if isBreakFlag(d.data[d.off]) {
  2561. d.off++
  2562. return
  2563. }
  2564. d.skip()
  2565. }
  2566. }
  2567. }
  2568. switch t {
  2569. case cborTypeByteString, cborTypeTextString:
  2570. d.off += int(val)
  2571. case cborTypeArray:
  2572. for i := 0; i < int(val); i++ {
  2573. d.skip()
  2574. }
  2575. case cborTypeMap:
  2576. for i := 0; i < int(val)*2; i++ {
  2577. d.skip()
  2578. }
  2579. case cborTypeTag:
  2580. d.skip()
  2581. }
  2582. }
  2583. func (d *decoder) getHeadWithIndefiniteLengthFlag() (
  2584. t cborType,
  2585. ai byte,
  2586. val uint64,
  2587. indefiniteLength bool,
  2588. ) {
  2589. t, ai, val = d.getHead()
  2590. indefiniteLength = additionalInformation(ai).isIndefiniteLength()
  2591. return
  2592. }
  2593. // getHead assumes data is well-formed, and does not perform bounds checking.
  2594. func (d *decoder) getHead() (t cborType, ai byte, val uint64) {
  2595. t, ai = parseInitialByte(d.data[d.off])
  2596. val = uint64(ai)
  2597. d.off++
  2598. if ai <= maxAdditionalInformationWithoutArgument {
  2599. return
  2600. }
  2601. if ai == additionalInformationWith1ByteArgument {
  2602. val = uint64(d.data[d.off])
  2603. d.off++
  2604. return
  2605. }
  2606. if ai == additionalInformationWith2ByteArgument {
  2607. const argumentSize = 2
  2608. val = uint64(binary.BigEndian.Uint16(d.data[d.off : d.off+argumentSize]))
  2609. d.off += argumentSize
  2610. return
  2611. }
  2612. if ai == additionalInformationWith4ByteArgument {
  2613. const argumentSize = 4
  2614. val = uint64(binary.BigEndian.Uint32(d.data[d.off : d.off+argumentSize]))
  2615. d.off += argumentSize
  2616. return
  2617. }
  2618. if ai == additionalInformationWith8ByteArgument {
  2619. const argumentSize = 8
  2620. val = binary.BigEndian.Uint64(d.data[d.off : d.off+argumentSize])
  2621. d.off += argumentSize
  2622. return
  2623. }
  2624. return
  2625. }
  2626. func (d *decoder) numOfItemsUntilBreak() int {
  2627. savedOff := d.off
  2628. i := 0
  2629. for !d.foundBreak() {
  2630. d.skip()
  2631. i++
  2632. }
  2633. d.off = savedOff
  2634. return i
  2635. }
  2636. // foundBreak returns true if next byte is CBOR break code and moves cursor by 1,
  2637. // otherwise it returns false.
  2638. // foundBreak assumes data is well-formed, and does not perform bounds checking.
  2639. func (d *decoder) foundBreak() bool {
  2640. if isBreakFlag(d.data[d.off]) {
  2641. d.off++
  2642. return true
  2643. }
  2644. return false
  2645. }
  2646. func (d *decoder) reset(data []byte) {
  2647. d.data = data
  2648. d.off = 0
  2649. d.expectedLaterEncodingTags = d.expectedLaterEncodingTags[:0]
  2650. }
  2651. func (d *decoder) nextCBORType() cborType {
  2652. return getType(d.data[d.off])
  2653. }
  2654. func (d *decoder) nextCBORNil() bool {
  2655. return d.data[d.off] == 0xf6 || d.data[d.off] == 0xf7
  2656. }
  2657. type jsonUnmarshaler interface{ UnmarshalJSON([]byte) error }
  2658. var (
  2659. typeIntf = reflect.TypeOf([]any(nil)).Elem()
  2660. typeTime = reflect.TypeOf(time.Time{})
  2661. typeBigInt = reflect.TypeOf(big.Int{})
  2662. typeUnmarshaler = reflect.TypeOf((*Unmarshaler)(nil)).Elem()
  2663. typeUnexportedUnmarshaler = reflect.TypeOf((*unmarshaler)(nil)).Elem()
  2664. typeBinaryUnmarshaler = reflect.TypeOf((*encoding.BinaryUnmarshaler)(nil)).Elem()
  2665. typeTextUnmarshaler = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem()
  2666. typeJSONUnmarshaler = reflect.TypeOf((*jsonUnmarshaler)(nil)).Elem()
  2667. typeString = reflect.TypeOf("")
  2668. typeByteSlice = reflect.TypeOf([]byte(nil))
  2669. )
  2670. func fillNil(_ cborType, v reflect.Value) error {
  2671. switch v.Kind() {
  2672. case reflect.Slice, reflect.Map, reflect.Interface, reflect.Pointer:
  2673. v.SetZero()
  2674. return nil
  2675. }
  2676. return nil
  2677. }
  2678. func fillPositiveInt(t cborType, val uint64, v reflect.Value) error {
  2679. switch v.Kind() {
  2680. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  2681. if val > math.MaxInt64 {
  2682. return &UnmarshalTypeError{
  2683. CBORType: t.String(),
  2684. GoType: v.Type().String(),
  2685. errorMsg: strconv.FormatUint(val, 10) + " overflows " + v.Type().String(),
  2686. }
  2687. }
  2688. if v.OverflowInt(int64(val)) {
  2689. return &UnmarshalTypeError{
  2690. CBORType: t.String(),
  2691. GoType: v.Type().String(),
  2692. errorMsg: strconv.FormatUint(val, 10) + " overflows " + v.Type().String(),
  2693. }
  2694. }
  2695. v.SetInt(int64(val))
  2696. return nil
  2697. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  2698. if v.OverflowUint(val) {
  2699. return &UnmarshalTypeError{
  2700. CBORType: t.String(),
  2701. GoType: v.Type().String(),
  2702. errorMsg: strconv.FormatUint(val, 10) + " overflows " + v.Type().String(),
  2703. }
  2704. }
  2705. v.SetUint(val)
  2706. return nil
  2707. case reflect.Float32, reflect.Float64:
  2708. f := float64(val)
  2709. v.SetFloat(f)
  2710. return nil
  2711. }
  2712. if v.Type() == typeBigInt {
  2713. i := new(big.Int).SetUint64(val)
  2714. v.Set(reflect.ValueOf(*i))
  2715. return nil
  2716. }
  2717. return &UnmarshalTypeError{CBORType: t.String(), GoType: v.Type().String()}
  2718. }
  2719. func fillNegativeInt(t cborType, val int64, v reflect.Value) error {
  2720. switch v.Kind() {
  2721. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  2722. if v.OverflowInt(val) {
  2723. return &UnmarshalTypeError{
  2724. CBORType: t.String(),
  2725. GoType: v.Type().String(),
  2726. errorMsg: strconv.FormatInt(val, 10) + " overflows " + v.Type().String(),
  2727. }
  2728. }
  2729. v.SetInt(val)
  2730. return nil
  2731. case reflect.Float32, reflect.Float64:
  2732. f := float64(val)
  2733. v.SetFloat(f)
  2734. return nil
  2735. }
  2736. if v.Type() == typeBigInt {
  2737. i := new(big.Int).SetInt64(val)
  2738. v.Set(reflect.ValueOf(*i))
  2739. return nil
  2740. }
  2741. return &UnmarshalTypeError{CBORType: t.String(), GoType: v.Type().String()}
  2742. }
  2743. func fillBool(t cborType, val bool, v reflect.Value) error {
  2744. if v.Kind() == reflect.Bool {
  2745. v.SetBool(val)
  2746. return nil
  2747. }
  2748. return &UnmarshalTypeError{CBORType: t.String(), GoType: v.Type().String()}
  2749. }
  2750. func fillFloat(t cborType, val float64, v reflect.Value) error {
  2751. switch v.Kind() {
  2752. case reflect.Float32, reflect.Float64:
  2753. if v.OverflowFloat(val) {
  2754. return &UnmarshalTypeError{
  2755. CBORType: t.String(),
  2756. GoType: v.Type().String(),
  2757. errorMsg: strconv.FormatFloat(val, 'E', -1, 64) + " overflows " + v.Type().String(),
  2758. }
  2759. }
  2760. v.SetFloat(val)
  2761. return nil
  2762. }
  2763. return &UnmarshalTypeError{CBORType: t.String(), GoType: v.Type().String()}
  2764. }
  2765. func fillByteString(t cborType, val []byte, shared bool, v reflect.Value, bsts ByteStringToStringMode, bum BinaryUnmarshalerMode, tum TextUnmarshalerMode) error {
  2766. if bum == BinaryUnmarshalerByteString && reflect.PointerTo(v.Type()).Implements(typeBinaryUnmarshaler) {
  2767. if v.CanAddr() {
  2768. v = v.Addr()
  2769. if u, ok := v.Interface().(encoding.BinaryUnmarshaler); ok {
  2770. // The contract of BinaryUnmarshaler forbids
  2771. // retaining the input bytes, so no copying is
  2772. // required even if val is shared.
  2773. return u.UnmarshalBinary(val)
  2774. }
  2775. }
  2776. return errors.New("cbor: cannot set new value for " + v.Type().String())
  2777. }
  2778. if bsts != ByteStringToStringForbidden {
  2779. if tum == TextUnmarshalerTextString && reflect.PointerTo(v.Type()).Implements(typeTextUnmarshaler) {
  2780. if v.CanAddr() {
  2781. v = v.Addr()
  2782. if u, ok := v.Interface().(encoding.TextUnmarshaler); ok {
  2783. // The contract of TextUnmarshaler forbids retaining the input
  2784. // bytes, so no copying is required even if val is shared.
  2785. if err := u.UnmarshalText(val); err != nil {
  2786. return fmt.Errorf("cbor: cannot unmarshal text for %s: %w", v.Type(), err)
  2787. }
  2788. return nil
  2789. }
  2790. }
  2791. return errors.New("cbor: cannot set new value for " + v.Type().String())
  2792. }
  2793. if v.Kind() == reflect.String {
  2794. v.SetString(string(val))
  2795. return nil
  2796. }
  2797. }
  2798. if v.Kind() == reflect.Slice && v.Type().Elem().Kind() == reflect.Uint8 {
  2799. src := val
  2800. if shared {
  2801. // SetBytes shares the underlying bytes of the source slice.
  2802. src = make([]byte, len(val))
  2803. copy(src, val)
  2804. }
  2805. v.SetBytes(src)
  2806. return nil
  2807. }
  2808. if v.Kind() == reflect.Array && v.Type().Elem().Kind() == reflect.Uint8 {
  2809. vLen := v.Len()
  2810. i := 0
  2811. for ; i < vLen && i < len(val); i++ {
  2812. v.Index(i).SetUint(uint64(val[i]))
  2813. }
  2814. // Set remaining Go array elements to zero values.
  2815. if i < vLen {
  2816. for ; i < vLen; i++ {
  2817. v.Index(i).SetZero()
  2818. }
  2819. }
  2820. return nil
  2821. }
  2822. return &UnmarshalTypeError{CBORType: t.String(), GoType: v.Type().String()}
  2823. }
  2824. func fillTextString(t cborType, val []byte, v reflect.Value, tum TextUnmarshalerMode) error {
  2825. // Check if the value implements TextUnmarshaler and the mode allows it
  2826. if tum == TextUnmarshalerTextString && reflect.PointerTo(v.Type()).Implements(typeTextUnmarshaler) {
  2827. if v.CanAddr() {
  2828. v = v.Addr()
  2829. if u, ok := v.Interface().(encoding.TextUnmarshaler); ok {
  2830. // The contract of TextUnmarshaler forbids retaining the input
  2831. // bytes, so no copying is required even if val is shared.
  2832. if err := u.UnmarshalText(val); err != nil {
  2833. return fmt.Errorf("cbor: cannot unmarshal text for %s: %w", v.Type(), err)
  2834. }
  2835. return nil
  2836. }
  2837. }
  2838. return errors.New("cbor: cannot set new value for " + v.Type().String())
  2839. }
  2840. if v.Kind() == reflect.String {
  2841. v.SetString(string(val))
  2842. return nil
  2843. }
  2844. return &UnmarshalTypeError{CBORType: t.String(), GoType: v.Type().String()}
  2845. }
  2846. func isImmutableKind(k reflect.Kind) bool {
  2847. switch k {
  2848. case reflect.Bool,
  2849. reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
  2850. reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
  2851. reflect.Float32, reflect.Float64,
  2852. reflect.String:
  2853. return true
  2854. default:
  2855. return false
  2856. }
  2857. }
  2858. func isHashableValue(rv reflect.Value) bool {
  2859. switch rv.Kind() {
  2860. case reflect.Slice, reflect.Map, reflect.Func:
  2861. return false
  2862. case reflect.Struct:
  2863. switch rv.Type() {
  2864. case typeTag:
  2865. tag := rv.Interface().(Tag)
  2866. return isHashableValue(reflect.ValueOf(tag.Content))
  2867. case typeBigInt:
  2868. return false
  2869. }
  2870. }
  2871. return true
  2872. }
  2873. // convertByteSliceToByteString converts []byte to ByteString if
  2874. // - v is []byte type, or
  2875. // - v is Tag type and tag content type is []byte
  2876. // This function also handles nested tags.
  2877. // CBOR data is already verified to be well-formed before this function is used,
  2878. // so the recursion won't exceed max nested levels.
  2879. func convertByteSliceToByteString(v any) (any, bool) {
  2880. switch v := v.(type) {
  2881. case []byte:
  2882. return ByteString(v), true
  2883. case Tag:
  2884. content, converted := convertByteSliceToByteString(v.Content)
  2885. if converted {
  2886. return Tag{Number: v.Number, Content: content}, true
  2887. }
  2888. }
  2889. return v, false
  2890. }