ua_types_encoding_json.c 110 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  4. *
  5. * Copyright 2014-2018 (c) Fraunhofer IOSB (Author: Julius Pfrommer)
  6. * Copyright 2018 (c) Fraunhofer IOSB (Author: Lukas Meling)
  7. */
  8. #include "ua_types_encoding_json.h"
  9. #include <open62541/types_generated.h>
  10. #include <open62541/types_generated_handling.h>
  11. #include "ua_types_encoding_binary.h"
  12. #include <float.h>
  13. #include <math.h>
  14. #ifdef UA_ENABLE_CUSTOM_LIBC
  15. #include "../deps/musl/floatscan.h"
  16. #include "../deps/musl/vfprintf.h"
  17. #endif
  18. #include "../deps/itoa.h"
  19. #include "../deps/atoi.h"
  20. #include "../deps/string_escape.h"
  21. #include "../deps/base64.h"
  22. #include "../deps/libc_time.h"
  23. #if defined(_MSC_VER)
  24. # define strtoll _strtoi64
  25. # define strtoull _strtoui64
  26. #endif
  27. /* vs2008 does not have INFINITY and NAN defined */
  28. #ifndef INFINITY
  29. # define INFINITY ((UA_Double)(DBL_MAX+DBL_MAX))
  30. #endif
  31. #ifndef NAN
  32. # define NAN ((UA_Double)(INFINITY-INFINITY))
  33. #endif
  34. #if defined(_MSC_VER)
  35. # pragma warning(disable: 4756)
  36. # pragma warning(disable: 4056)
  37. #endif
  38. #define UA_NODEIDTYPE_NUMERIC_TWOBYTE 0
  39. #define UA_NODEIDTYPE_NUMERIC_FOURBYTE 1
  40. #define UA_NODEIDTYPE_NUMERIC_COMPLETE 2
  41. #define UA_EXPANDEDNODEID_SERVERINDEX_FLAG 0x40
  42. #define UA_EXPANDEDNODEID_NAMESPACEURI_FLAG 0x80
  43. #define UA_JSON_DATETIME_LENGTH 30
  44. /* Max length of numbers for the allocation of temp buffers. Don't forget that
  45. * printf adds an additional \0 at the end!
  46. *
  47. * Sources:
  48. * https://www.exploringbinary.com/maximum-number-of-decimal-digits-in-binary-floating-point-numbers/
  49. *
  50. * UInt16: 3 + 1
  51. * SByte: 3 + 1
  52. * UInt32:
  53. * Int32:
  54. * UInt64:
  55. * Int64:
  56. * Float: 149 + 1
  57. * Double: 767 + 1
  58. */
  59. /************/
  60. /* Encoding */
  61. /************/
  62. #define ENCODE_JSON(TYPE) static status \
  63. TYPE##_encodeJson(const UA_##TYPE *src, const UA_DataType *type, CtxJson *ctx)
  64. #define ENCODE_DIRECT_JSON(SRC, TYPE) \
  65. TYPE##_encodeJson((const UA_##TYPE*)SRC, NULL, ctx)
  66. extern const encodeJsonSignature encodeJsonJumpTable[UA_DATATYPEKINDS];
  67. extern const decodeJsonSignature decodeJsonJumpTable[UA_DATATYPEKINDS];
  68. /* Forward declarations */
  69. UA_String UA_DateTime_toJSON(UA_DateTime t);
  70. ENCODE_JSON(ByteString);
  71. static status UA_FUNC_ATTR_WARN_UNUSED_RESULT
  72. writeChar(CtxJson *ctx, char c) {
  73. if(ctx->pos >= ctx->end)
  74. return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED;
  75. if(!ctx->calcOnly)
  76. *ctx->pos = (UA_Byte)c;
  77. ctx->pos++;
  78. return UA_STATUSCODE_GOOD;
  79. }
  80. #define WRITE_JSON_ELEMENT(ELEM) \
  81. UA_FUNC_ATTR_WARN_UNUSED_RESULT status \
  82. writeJson##ELEM(CtxJson *ctx)
  83. static WRITE_JSON_ELEMENT(Quote) {
  84. return writeChar(ctx, '\"');
  85. }
  86. WRITE_JSON_ELEMENT(ObjStart) {
  87. /* increase depth, save: before first key-value no comma needed. */
  88. ctx->depth++;
  89. ctx->commaNeeded[ctx->depth] = false;
  90. return writeChar(ctx, '{');
  91. }
  92. WRITE_JSON_ELEMENT(ObjEnd) {
  93. ctx->depth--; //decrease depth
  94. ctx->commaNeeded[ctx->depth] = true;
  95. return writeChar(ctx, '}');
  96. }
  97. WRITE_JSON_ELEMENT(ArrStart) {
  98. /* increase depth, save: before first array entry no comma needed. */
  99. ctx->commaNeeded[++ctx->depth] = false;
  100. return writeChar(ctx, '[');
  101. }
  102. WRITE_JSON_ELEMENT(ArrEnd) {
  103. ctx->depth--; //decrease depth
  104. ctx->commaNeeded[ctx->depth] = true;
  105. return writeChar(ctx, ']');
  106. }
  107. WRITE_JSON_ELEMENT(CommaIfNeeded) {
  108. if(ctx->commaNeeded[ctx->depth])
  109. return writeChar(ctx, ',');
  110. return UA_STATUSCODE_GOOD;
  111. }
  112. status
  113. writeJsonArrElm(CtxJson *ctx, const void *value,
  114. const UA_DataType *type) {
  115. status ret = writeJsonCommaIfNeeded(ctx);
  116. ctx->commaNeeded[ctx->depth] = true;
  117. ret |= encodeJsonInternal(value, type, ctx);
  118. return ret;
  119. }
  120. status writeJsonObjElm(CtxJson *ctx, const char *key,
  121. const void *value, const UA_DataType *type){
  122. return writeJsonKey(ctx, key) | encodeJsonInternal(value, type, ctx);
  123. }
  124. status writeJsonNull(CtxJson *ctx) {
  125. if(ctx->pos + 4 > ctx->end)
  126. return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED;
  127. if(ctx->calcOnly) {
  128. ctx->pos += 4;
  129. } else {
  130. *(ctx->pos++) = 'n';
  131. *(ctx->pos++) = 'u';
  132. *(ctx->pos++) = 'l';
  133. *(ctx->pos++) = 'l';
  134. }
  135. return UA_STATUSCODE_GOOD;
  136. }
  137. /* Keys for JSON */
  138. /* LocalizedText */
  139. static const char* UA_JSONKEY_LOCALE = "Locale";
  140. static const char* UA_JSONKEY_TEXT = "Text";
  141. /* QualifiedName */
  142. static const char* UA_JSONKEY_NAME = "Name";
  143. static const char* UA_JSONKEY_URI = "Uri";
  144. /* NodeId */
  145. static const char* UA_JSONKEY_ID = "Id";
  146. static const char* UA_JSONKEY_IDTYPE = "IdType";
  147. static const char* UA_JSONKEY_NAMESPACE = "Namespace";
  148. /* ExpandedNodeId */
  149. static const char* UA_JSONKEY_SERVERURI = "ServerUri";
  150. /* Variant */
  151. static const char* UA_JSONKEY_TYPE = "Type";
  152. static const char* UA_JSONKEY_BODY = "Body";
  153. static const char* UA_JSONKEY_DIMENSION = "Dimension";
  154. /* DataValue */
  155. static const char* UA_JSONKEY_VALUE = "Value";
  156. static const char* UA_JSONKEY_STATUS = "Status";
  157. static const char* UA_JSONKEY_SOURCETIMESTAMP = "SourceTimestamp";
  158. static const char* UA_JSONKEY_SOURCEPICOSECONDS = "SourcePicoseconds";
  159. static const char* UA_JSONKEY_SERVERTIMESTAMP = "ServerTimestamp";
  160. static const char* UA_JSONKEY_SERVERPICOSECONDS = "ServerPicoseconds";
  161. /* ExtensionObject */
  162. static const char* UA_JSONKEY_ENCODING = "Encoding";
  163. static const char* UA_JSONKEY_TYPEID = "TypeId";
  164. /* StatusCode */
  165. static const char* UA_JSONKEY_CODE = "Code";
  166. static const char* UA_JSONKEY_SYMBOL = "Symbol";
  167. /* DiagnosticInfo */
  168. static const char* UA_JSONKEY_SYMBOLICID = "SymbolicId";
  169. static const char* UA_JSONKEY_NAMESPACEURI = "NamespaceUri";
  170. static const char* UA_JSONKEY_LOCALIZEDTEXT = "LocalizedText";
  171. static const char* UA_JSONKEY_ADDITIONALINFO = "AdditionalInfo";
  172. static const char* UA_JSONKEY_INNERSTATUSCODE = "InnerStatusCode";
  173. static const char* UA_JSONKEY_INNERDIAGNOSTICINFO = "InnerDiagnosticInfo";
  174. /* Writes null terminated string to output buffer (current ctx->pos). Writes
  175. * comma in front of key if needed. Encapsulates key in quotes. */
  176. status UA_FUNC_ATTR_WARN_UNUSED_RESULT
  177. writeJsonKey(CtxJson *ctx, const char* key) {
  178. size_t size = strlen(key);
  179. if(ctx->pos + size + 4 > ctx->end) /* +4 because of " " : and , */
  180. return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED;
  181. status ret = writeJsonCommaIfNeeded(ctx);
  182. ctx->commaNeeded[ctx->depth] = true;
  183. if(ctx->calcOnly) {
  184. ctx->commaNeeded[ctx->depth] = true;
  185. ctx->pos += 3;
  186. ctx->pos += size;
  187. return ret;
  188. }
  189. ret |= writeChar(ctx, '\"');
  190. for(size_t i = 0; i < size; i++) {
  191. *(ctx->pos++) = (u8)key[i];
  192. }
  193. ret |= writeChar(ctx, '\"');
  194. ret |= writeChar(ctx, ':');
  195. return ret;
  196. }
  197. /* Boolean */
  198. ENCODE_JSON(Boolean) {
  199. size_t sizeOfJSONBool;
  200. if(*src == true) {
  201. sizeOfJSONBool = 4; /*"true"*/
  202. } else {
  203. sizeOfJSONBool = 5; /*"false"*/
  204. }
  205. if(ctx->calcOnly) {
  206. ctx->pos += sizeOfJSONBool;
  207. return UA_STATUSCODE_GOOD;
  208. }
  209. if(ctx->pos + sizeOfJSONBool > ctx->end)
  210. return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED;
  211. if(*src) {
  212. *(ctx->pos++) = 't';
  213. *(ctx->pos++) = 'r';
  214. *(ctx->pos++) = 'u';
  215. *(ctx->pos++) = 'e';
  216. } else {
  217. *(ctx->pos++) = 'f';
  218. *(ctx->pos++) = 'a';
  219. *(ctx->pos++) = 'l';
  220. *(ctx->pos++) = 's';
  221. *(ctx->pos++) = 'e';
  222. }
  223. return UA_STATUSCODE_GOOD;
  224. }
  225. /*****************/
  226. /* Integer Types */
  227. /*****************/
  228. /* Byte */
  229. ENCODE_JSON(Byte) {
  230. char buf[4];
  231. UA_UInt16 digits = itoaUnsigned(*src, buf, 10);
  232. /* Ensure destination can hold the data- */
  233. if(ctx->pos + digits > ctx->end)
  234. return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED;
  235. /* Copy digits to the output string/buffer. */
  236. if(!ctx->calcOnly)
  237. memcpy(ctx->pos, buf, digits);
  238. ctx->pos += digits;
  239. return UA_STATUSCODE_GOOD;
  240. }
  241. /* signed Byte */
  242. ENCODE_JSON(SByte) {
  243. char buf[5];
  244. UA_UInt16 digits = itoaSigned(*src, buf);
  245. if(ctx->pos + digits > ctx->end)
  246. return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED;
  247. if(!ctx->calcOnly)
  248. memcpy(ctx->pos, buf, digits);
  249. ctx->pos += digits;
  250. return UA_STATUSCODE_GOOD;
  251. }
  252. /* UInt16 */
  253. ENCODE_JSON(UInt16) {
  254. char buf[6];
  255. UA_UInt16 digits = itoaUnsigned(*src, buf, 10);
  256. if(ctx->pos + digits > ctx->end)
  257. return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED;
  258. if(!ctx->calcOnly)
  259. memcpy(ctx->pos, buf, digits);
  260. ctx->pos += digits;
  261. return UA_STATUSCODE_GOOD;
  262. }
  263. /* Int16 */
  264. ENCODE_JSON(Int16) {
  265. char buf[7];
  266. UA_UInt16 digits = itoaSigned(*src, buf);
  267. if(ctx->pos + digits > ctx->end)
  268. return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED;
  269. if(!ctx->calcOnly)
  270. memcpy(ctx->pos, buf, digits);
  271. ctx->pos += digits;
  272. return UA_STATUSCODE_GOOD;
  273. }
  274. /* UInt32 */
  275. ENCODE_JSON(UInt32) {
  276. char buf[11];
  277. UA_UInt16 digits = itoaUnsigned(*src, buf, 10);
  278. if(ctx->pos + digits > ctx->end)
  279. return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED;
  280. if(!ctx->calcOnly)
  281. memcpy(ctx->pos, buf, digits);
  282. ctx->pos += digits;
  283. return UA_STATUSCODE_GOOD;
  284. }
  285. /* Int32 */
  286. ENCODE_JSON(Int32) {
  287. char buf[12];
  288. UA_UInt16 digits = itoaSigned(*src, buf);
  289. if(ctx->pos + digits > ctx->end)
  290. return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED;
  291. if(!ctx->calcOnly)
  292. memcpy(ctx->pos, buf, digits);
  293. ctx->pos += digits;
  294. return UA_STATUSCODE_GOOD;
  295. }
  296. /* UInt64 */
  297. ENCODE_JSON(UInt64) {
  298. char buf[23];
  299. buf[0] = '\"';
  300. UA_UInt16 digits = itoaUnsigned(*src, buf + 1, 10);
  301. buf[digits + 1] = '\"';
  302. UA_UInt16 length = (UA_UInt16)(digits + 2);
  303. if(ctx->pos + length > ctx->end)
  304. return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED;
  305. if(!ctx->calcOnly)
  306. memcpy(ctx->pos, buf, length);
  307. ctx->pos += length;
  308. return UA_STATUSCODE_GOOD;
  309. }
  310. /* Int64 */
  311. ENCODE_JSON(Int64) {
  312. char buf[23];
  313. buf[0] = '\"';
  314. UA_UInt16 digits = itoaSigned(*src, buf + 1);
  315. buf[digits + 1] = '\"';
  316. UA_UInt16 length = (UA_UInt16)(digits + 2);
  317. if(ctx->pos + length > ctx->end)
  318. return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED;
  319. if(!ctx->calcOnly)
  320. memcpy(ctx->pos, buf, length);
  321. ctx->pos += length;
  322. return UA_STATUSCODE_GOOD;
  323. }
  324. /************************/
  325. /* Floating Point Types */
  326. /************************/
  327. /* Convert special numbers to string
  328. * - fmt_fp gives NAN, nan,-NAN, -nan, inf, INF, -inf, -INF
  329. * - Special floating-point numbers such as positive infinity (INF), negative
  330. * infinity (-INF) and not-a-number (NaN) shall be represented by the values
  331. * “Infinity”, “-Infinity” and “NaN” encoded as a JSON string. */
  332. static status
  333. checkAndEncodeSpecialFloatingPoint(char *buffer, size_t *len) {
  334. /*nan and NaN*/
  335. if(*len == 3 &&
  336. (buffer[0] == 'n' || buffer[0] == 'N') &&
  337. (buffer[1] == 'a' || buffer[1] == 'A') &&
  338. (buffer[2] == 'n' || buffer[2] == 'N')) {
  339. *len = 5;
  340. memcpy(buffer, "\"NaN\"", *len);
  341. return UA_STATUSCODE_GOOD;
  342. }
  343. /*-nan and -NaN*/
  344. if(*len == 4 && buffer[0] == '-' &&
  345. (buffer[1] == 'n' || buffer[1] == 'N') &&
  346. (buffer[2] == 'a' || buffer[2] == 'A') &&
  347. (buffer[3] == 'n' || buffer[3] == 'N')) {
  348. *len = 6;
  349. memcpy(buffer, "\"-NaN\"", *len);
  350. return UA_STATUSCODE_GOOD;
  351. }
  352. /*inf*/
  353. if(*len == 3 &&
  354. (buffer[0] == 'i' || buffer[0] == 'I') &&
  355. (buffer[1] == 'n' || buffer[1] == 'N') &&
  356. (buffer[2] == 'f' || buffer[2] == 'F')) {
  357. *len = 10;
  358. memcpy(buffer, "\"Infinity\"", *len);
  359. return UA_STATUSCODE_GOOD;
  360. }
  361. /*-inf*/
  362. if(*len == 4 && buffer[0] == '-' &&
  363. (buffer[1] == 'i' || buffer[1] == 'I') &&
  364. (buffer[2] == 'n' || buffer[2] == 'N') &&
  365. (buffer[3] == 'f' || buffer[3] == 'F')) {
  366. *len = 11;
  367. memcpy(buffer, "\"-Infinity\"", *len);
  368. return UA_STATUSCODE_GOOD;
  369. }
  370. return UA_STATUSCODE_GOOD;
  371. }
  372. ENCODE_JSON(Float) {
  373. char buffer[200];
  374. if(*src == *src) {
  375. #ifdef UA_ENABLE_CUSTOM_LIBC
  376. fmt_fp(buffer, *src, 0, -1, 0, 'g');
  377. #else
  378. UA_snprintf(buffer, 200, "%.149g", (UA_Double)*src);
  379. #endif
  380. } else {
  381. strcpy(buffer, "NaN");
  382. }
  383. size_t len = strlen(buffer);
  384. if(len == 0)
  385. return UA_STATUSCODE_BADENCODINGERROR;
  386. checkAndEncodeSpecialFloatingPoint(buffer, &len);
  387. if(ctx->pos + len > ctx->end)
  388. return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED;
  389. if(!ctx->calcOnly)
  390. memcpy(ctx->pos, buffer, len);
  391. ctx->pos += len;
  392. return UA_STATUSCODE_GOOD;
  393. }
  394. ENCODE_JSON(Double) {
  395. char buffer[2000];
  396. if(*src == *src) {
  397. #ifdef UA_ENABLE_CUSTOM_LIBC
  398. fmt_fp(buffer, *src, 0, 17, 0, 'g');
  399. #else
  400. UA_snprintf(buffer, 2000, "%.1074g", *src);
  401. #endif
  402. } else {
  403. strcpy(buffer, "NaN");
  404. }
  405. size_t len = strlen(buffer);
  406. checkAndEncodeSpecialFloatingPoint(buffer, &len);
  407. if(ctx->pos + len > ctx->end)
  408. return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED;
  409. if(!ctx->calcOnly)
  410. memcpy(ctx->pos, buffer, len);
  411. ctx->pos += len;
  412. return UA_STATUSCODE_GOOD;
  413. }
  414. static status
  415. encodeJsonArray(CtxJson *ctx, const void *ptr, size_t length,
  416. const UA_DataType *type) {
  417. encodeJsonSignature encodeType = encodeJsonJumpTable[type->typeKind];
  418. status ret = writeJsonArrStart(ctx);
  419. uintptr_t uptr = (uintptr_t)ptr;
  420. for(size_t i = 0; i < length && ret == UA_STATUSCODE_GOOD; ++i) {
  421. ret |= writeJsonCommaIfNeeded(ctx);
  422. ret |= encodeType((const void*)uptr, type, ctx);
  423. ctx->commaNeeded[ctx->depth] = true;
  424. uptr += type->memSize;
  425. }
  426. ret |= writeJsonArrEnd(ctx);
  427. return ret;
  428. }
  429. /*****************/
  430. /* Builtin Types */
  431. /*****************/
  432. static const u8 hexmapLower[16] =
  433. {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
  434. static const u8 hexmapUpper[16] =
  435. {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
  436. ENCODE_JSON(String) {
  437. if(!src->data)
  438. return writeJsonNull(ctx);
  439. if(src->length == 0) {
  440. status retval = writeJsonQuote(ctx);
  441. retval |= writeJsonQuote(ctx);
  442. return retval;
  443. }
  444. UA_StatusCode ret = writeJsonQuote(ctx);
  445. /* Escaping adapted from https://github.com/akheron/jansson dump.c */
  446. const char *str = (char*)src->data;
  447. const char *pos = str;
  448. const char *end = str;
  449. const char *lim = str + src->length;
  450. UA_UInt32 codepoint = 0;
  451. while(1) {
  452. const char *text;
  453. u8 seq[13];
  454. size_t length;
  455. while(end < lim) {
  456. end = utf8_iterate(pos, (size_t)(lim - pos), (int32_t *)&codepoint);
  457. if(!end)
  458. return UA_STATUSCODE_BADENCODINGERROR;
  459. /* mandatory escape or control char */
  460. if(codepoint == '\\' || codepoint == '"' || codepoint < 0x20)
  461. break;
  462. /* TODO: Why is this commented? */
  463. /* slash
  464. if((flags & JSON_ESCAPE_SLASH) && codepoint == '/')
  465. break;*/
  466. /* non-ASCII
  467. if((flags & JSON_ENSURE_ASCII) && codepoint > 0x7F)
  468. break;*/
  469. pos = end;
  470. }
  471. if(pos != str) {
  472. if(ctx->pos + (pos - str) > ctx->end)
  473. return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED;
  474. if(!ctx->calcOnly)
  475. memcpy(ctx->pos, str, (size_t)(pos - str));
  476. ctx->pos += pos - str;
  477. }
  478. if(end == pos)
  479. break;
  480. /* handle \, /, ", and control codes */
  481. length = 2;
  482. switch(codepoint) {
  483. case '\\': text = "\\\\"; break;
  484. case '\"': text = "\\\""; break;
  485. case '\b': text = "\\b"; break;
  486. case '\f': text = "\\f"; break;
  487. case '\n': text = "\\n"; break;
  488. case '\r': text = "\\r"; break;
  489. case '\t': text = "\\t"; break;
  490. case '/': text = "\\/"; break;
  491. default:
  492. if(codepoint < 0x10000) {
  493. /* codepoint is in BMP */
  494. seq[0] = '\\';
  495. seq[1] = 'u';
  496. UA_Byte b1 = (UA_Byte)(codepoint >> 8u);
  497. UA_Byte b2 = (UA_Byte)(codepoint >> 0u);
  498. seq[2] = hexmapLower[(b1 & 0xF0u) >> 4u];
  499. seq[3] = hexmapLower[b1 & 0x0Fu];
  500. seq[4] = hexmapLower[(b2 & 0xF0u) >> 4u];
  501. seq[5] = hexmapLower[b2 & 0x0Fu];
  502. length = 6;
  503. } else {
  504. /* not in BMP -> construct a UTF-16 surrogate pair */
  505. codepoint -= 0x10000;
  506. UA_UInt32 first = 0xD800u | ((codepoint & 0xffc00u) >> 10u);
  507. UA_UInt32 last = 0xDC00u | (codepoint & 0x003ffu);
  508. UA_Byte fb1 = (UA_Byte)(first >> 8u);
  509. UA_Byte fb2 = (UA_Byte)(first >> 0u);
  510. UA_Byte lb1 = (UA_Byte)(last >> 8u);
  511. UA_Byte lb2 = (UA_Byte)(last >> 0u);
  512. seq[0] = '\\';
  513. seq[1] = 'u';
  514. seq[2] = hexmapLower[(fb1 & 0xF0u) >> 4u];
  515. seq[3] = hexmapLower[fb1 & 0x0Fu];
  516. seq[4] = hexmapLower[(fb2 & 0xF0u) >> 4u];
  517. seq[5] = hexmapLower[fb2 & 0x0Fu];
  518. seq[6] = '\\';
  519. seq[7] = 'u';
  520. seq[8] = hexmapLower[(lb1 & 0xF0u) >> 4u];
  521. seq[9] = hexmapLower[lb1 & 0x0Fu];
  522. seq[10] = hexmapLower[(lb2 & 0xF0u) >> 4u];
  523. seq[11] = hexmapLower[lb2 & 0x0Fu];
  524. length = 12;
  525. }
  526. text = (char*)seq;
  527. break;
  528. }
  529. if(ctx->pos + length > ctx->end)
  530. return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED;
  531. if(!ctx->calcOnly)
  532. memcpy(ctx->pos, text, length);
  533. ctx->pos += length;
  534. str = pos = end;
  535. }
  536. ret |= writeJsonQuote(ctx);
  537. return ret;
  538. }
  539. ENCODE_JSON(ByteString) {
  540. if(!src->data)
  541. return writeJsonNull(ctx);
  542. if(src->length == 0) {
  543. status retval = writeJsonQuote(ctx);
  544. retval |= writeJsonQuote(ctx);
  545. return retval;
  546. }
  547. status ret = writeJsonQuote(ctx);
  548. int flen;
  549. char *ba64 = UA_base64(src->data, (int)src->length, &flen);
  550. /* Not converted, no mem */
  551. if(!ba64)
  552. return UA_STATUSCODE_BADENCODINGERROR;
  553. /* Check if negative... (TODO: Why is base64 3rd argument type int?) */
  554. if(flen < 0) {
  555. UA_free(ba64);
  556. return UA_STATUSCODE_BADENCODINGERROR;
  557. }
  558. if(ctx->pos + flen > ctx->end) {
  559. UA_free(ba64);
  560. return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED;
  561. }
  562. /* Copy flen bytes to output stream. */
  563. if(!ctx->calcOnly)
  564. memcpy(ctx->pos, ba64, (size_t)flen);
  565. ctx->pos += flen;
  566. /* Base64 result no longer needed */
  567. UA_free(ba64);
  568. ret |= writeJsonQuote(ctx);
  569. return ret;
  570. }
  571. /* Converts Guid to a hexadecimal represenation */
  572. static void UA_Guid_to_hex(const UA_Guid *guid, u8* out) {
  573. /*
  574. 16 byte
  575. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  576. | data1 |data2|data3| data4 |
  577. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  578. |aa aa aa aa-bb bb-cc cc-dd dd-ee ee ee ee ee ee|
  579. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  580. 36 character
  581. */
  582. #ifdef hexCharlowerCase
  583. const u8 *hexmap = hexmapLower;
  584. #else
  585. const u8 *hexmap = hexmapUpper;
  586. #endif
  587. size_t i = 0, j = 28;
  588. for(; i<8;i++,j-=4) /* pos 0-7, 4byte, (a) */
  589. out[i] = hexmap[(guid->data1 >> j) & 0x0Fu];
  590. out[i++] = '-'; /* pos 8 */
  591. for(j=12; i<13;i++,j-=4) /* pos 9-12, 2byte, (b) */
  592. out[i] = hexmap[(uint16_t)(guid->data2 >> j) & 0x0Fu];
  593. out[i++] = '-'; /* pos 13 */
  594. for(j=12; i<18;i++,j-=4) /* pos 14-17, 2byte (c) */
  595. out[i] = hexmap[(uint16_t)(guid->data3 >> j) & 0x0Fu];
  596. out[i++] = '-'; /* pos 18 */
  597. for(j=0;i<23;i+=2,j++) { /* pos 19-22, 2byte (d) */
  598. out[i] = hexmap[(guid->data4[j] & 0xF0u) >> 4u];
  599. out[i+1] = hexmap[guid->data4[j] & 0x0Fu];
  600. }
  601. out[i++] = '-'; /* pos 23 */
  602. for(j=2; i<36;i+=2,j++) { /* pos 24-35, 6byte (e) */
  603. out[i] = hexmap[(guid->data4[j] & 0xF0u) >> 4u];
  604. out[i+1] = hexmap[guid->data4[j] & 0x0Fu];
  605. }
  606. }
  607. /* Guid */
  608. ENCODE_JSON(Guid) {
  609. if(ctx->pos + 38 > ctx->end) /* 36 + 2 (") */
  610. return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED;
  611. status ret = writeJsonQuote(ctx);
  612. u8 *buf = ctx->pos;
  613. if(!ctx->calcOnly)
  614. UA_Guid_to_hex(src, buf);
  615. ctx->pos += 36;
  616. ret |= writeJsonQuote(ctx);
  617. return ret;
  618. }
  619. static void
  620. printNumber(u16 n, u8 *pos, size_t digits) {
  621. for(size_t i = digits; i > 0; --i) {
  622. pos[i - 1] = (u8) ((n % 10) + '0');
  623. n = n / 10;
  624. }
  625. }
  626. ENCODE_JSON(DateTime) {
  627. UA_DateTimeStruct tSt = UA_DateTime_toStruct(*src);
  628. /* Format: yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSS'Z' is used. max 30 bytes.*/
  629. UA_Byte buffer[UA_JSON_DATETIME_LENGTH];
  630. printNumber(tSt.year, &buffer[0], 4);
  631. buffer[4] = '-';
  632. printNumber(tSt.month, &buffer[5], 2);
  633. buffer[7] = '-';
  634. printNumber(tSt.day, &buffer[8], 2);
  635. buffer[10] = 'T';
  636. printNumber(tSt.hour, &buffer[11], 2);
  637. buffer[13] = ':';
  638. printNumber(tSt.min, &buffer[14], 2);
  639. buffer[16] = ':';
  640. printNumber(tSt.sec, &buffer[17], 2);
  641. buffer[19] = '.';
  642. printNumber(tSt.milliSec, &buffer[20], 3);
  643. printNumber(tSt.microSec, &buffer[23], 3);
  644. printNumber(tSt.nanoSec, &buffer[26], 3);
  645. size_t length = 28;
  646. while (buffer[length] == '0')
  647. length--;
  648. if (length != 19)
  649. length++;
  650. buffer[length] = 'Z';
  651. UA_String str = {length + 1, buffer};
  652. return ENCODE_DIRECT_JSON(&str, String);
  653. }
  654. /* NodeId */
  655. static status
  656. NodeId_encodeJsonInternal(UA_NodeId const *src, CtxJson *ctx) {
  657. status ret = UA_STATUSCODE_GOOD;
  658. switch (src->identifierType) {
  659. case UA_NODEIDTYPE_NUMERIC:
  660. ret |= writeJsonKey(ctx, UA_JSONKEY_ID);
  661. ret |= ENCODE_DIRECT_JSON(&src->identifier.numeric, UInt32);
  662. break;
  663. case UA_NODEIDTYPE_STRING:
  664. ret |= writeJsonKey(ctx, UA_JSONKEY_IDTYPE);
  665. ret |= writeChar(ctx, '1');
  666. ret |= writeJsonKey(ctx, UA_JSONKEY_ID);
  667. ret |= ENCODE_DIRECT_JSON(&src->identifier.string, String);
  668. break;
  669. case UA_NODEIDTYPE_GUID:
  670. ret |= writeJsonKey(ctx, UA_JSONKEY_IDTYPE);
  671. ret |= writeChar(ctx, '2');
  672. ret |= writeJsonKey(ctx, UA_JSONKEY_ID); /* Id */
  673. ret |= ENCODE_DIRECT_JSON(&src->identifier.guid, Guid);
  674. break;
  675. case UA_NODEIDTYPE_BYTESTRING:
  676. ret |= writeJsonKey(ctx, UA_JSONKEY_IDTYPE);
  677. ret |= writeChar(ctx, '3');
  678. ret |= writeJsonKey(ctx, UA_JSONKEY_ID); /* Id */
  679. ret |= ENCODE_DIRECT_JSON(&src->identifier.byteString, ByteString);
  680. break;
  681. default:
  682. return UA_STATUSCODE_BADINTERNALERROR;
  683. }
  684. return ret;
  685. }
  686. ENCODE_JSON(NodeId) {
  687. UA_StatusCode ret = writeJsonObjStart(ctx);
  688. ret |= NodeId_encodeJsonInternal(src, ctx);
  689. if(ctx->useReversible) {
  690. if(src->namespaceIndex > 0) {
  691. ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE);
  692. ret |= ENCODE_DIRECT_JSON(&src->namespaceIndex, UInt16);
  693. }
  694. } else {
  695. /* For the non-reversible encoding, the field is the NamespaceUri
  696. * associated with the NamespaceIndex, encoded as a JSON string.
  697. * A NamespaceIndex of 1 is always encoded as a JSON number. */
  698. if(src->namespaceIndex == 1) {
  699. ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE);
  700. ret |= ENCODE_DIRECT_JSON(&src->namespaceIndex, UInt16);
  701. } else {
  702. ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE);
  703. /* Check if Namespace given and in range */
  704. if(src->namespaceIndex < ctx->namespacesSize && ctx->namespaces != NULL) {
  705. UA_String namespaceEntry = ctx->namespaces[src->namespaceIndex];
  706. ret |= ENCODE_DIRECT_JSON(&namespaceEntry, String);
  707. } else {
  708. return UA_STATUSCODE_BADNOTFOUND;
  709. }
  710. }
  711. }
  712. ret |= writeJsonObjEnd(ctx);
  713. return ret;
  714. }
  715. /* ExpandedNodeId */
  716. ENCODE_JSON(ExpandedNodeId) {
  717. status ret = writeJsonObjStart(ctx);
  718. /* Encode the NodeId */
  719. ret |= NodeId_encodeJsonInternal(&src->nodeId, ctx);
  720. if(ctx->useReversible) {
  721. if(src->namespaceUri.data != NULL && src->namespaceUri.length != 0 &&
  722. (void*) src->namespaceUri.data > UA_EMPTY_ARRAY_SENTINEL) {
  723. /* If the NamespaceUri is specified it is encoded as a JSON string in this field. */
  724. ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE);
  725. ret |= ENCODE_DIRECT_JSON(&src->namespaceUri, String);
  726. } else {
  727. /* If the NamespaceUri is not specified, the NamespaceIndex is encoded with these rules:
  728. * The field is encoded as a JSON number for the reversible encoding.
  729. * The field is omitted if the NamespaceIndex equals 0. */
  730. if(src->nodeId.namespaceIndex > 0) {
  731. ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE);
  732. ret |= ENCODE_DIRECT_JSON(&src->nodeId.namespaceIndex, UInt16);
  733. }
  734. }
  735. /* Encode the serverIndex/Url
  736. * This field is encoded as a JSON number for the reversible encoding.
  737. * This field is omitted if the ServerIndex equals 0. */
  738. if(src->serverIndex > 0) {
  739. ret |= writeJsonKey(ctx, UA_JSONKEY_SERVERURI);
  740. ret |= ENCODE_DIRECT_JSON(&src->serverIndex, UInt32);
  741. }
  742. ret |= writeJsonObjEnd(ctx);
  743. return ret;
  744. }
  745. /* NON-Reversible Case */
  746. /* If the NamespaceUri is not specified, the NamespaceIndex is encoded with these rules:
  747. * For the non-reversible encoding the field is the NamespaceUri associated with the
  748. * NamespaceIndex encoded as a JSON string.
  749. * A NamespaceIndex of 1 is always encoded as a JSON number. */
  750. if(src->namespaceUri.data != NULL && src->namespaceUri.length != 0) {
  751. ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE);
  752. ret |= ENCODE_DIRECT_JSON(&src->namespaceUri, String);
  753. if(ret != UA_STATUSCODE_GOOD)
  754. return ret;
  755. } else {
  756. if(src->nodeId.namespaceIndex == 1) {
  757. ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE);
  758. ret |= ENCODE_DIRECT_JSON(&src->nodeId.namespaceIndex, UInt16);
  759. if(ret != UA_STATUSCODE_GOOD)
  760. return ret;
  761. } else {
  762. ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE);
  763. /* Check if Namespace given and in range */
  764. if(src->nodeId.namespaceIndex < ctx->namespacesSize
  765. && ctx->namespaces != NULL) {
  766. UA_String namespaceEntry = ctx->namespaces[src->nodeId.namespaceIndex];
  767. ret |= ENCODE_DIRECT_JSON(&namespaceEntry, String);
  768. if(ret != UA_STATUSCODE_GOOD)
  769. return ret;
  770. } else {
  771. return UA_STATUSCODE_BADNOTFOUND;
  772. }
  773. }
  774. }
  775. /* For the non-reversible encoding, this field is the ServerUri associated
  776. * with the ServerIndex portion of the ExpandedNodeId, encoded as a JSON
  777. * string. */
  778. /* Check if Namespace given and in range */
  779. if(src->serverIndex < ctx->serverUrisSize && ctx->serverUris != NULL) {
  780. UA_String serverUriEntry = ctx->serverUris[src->serverIndex];
  781. ret |= writeJsonKey(ctx, UA_JSONKEY_SERVERURI);
  782. ret |= ENCODE_DIRECT_JSON(&serverUriEntry, String);
  783. } else {
  784. return UA_STATUSCODE_BADNOTFOUND;
  785. }
  786. ret |= writeJsonObjEnd(ctx);
  787. return ret;
  788. }
  789. /* LocalizedText */
  790. ENCODE_JSON(LocalizedText) {
  791. if(ctx->useReversible) {
  792. status ret = writeJsonObjStart(ctx);
  793. ret |= writeJsonKey(ctx, UA_JSONKEY_LOCALE);
  794. ret |= ENCODE_DIRECT_JSON(&src->locale, String);
  795. ret |= writeJsonKey(ctx, UA_JSONKEY_TEXT);
  796. ret |= ENCODE_DIRECT_JSON(&src->text, String);
  797. ret |= writeJsonObjEnd(ctx);
  798. return ret;
  799. }
  800. /* For the non-reversible form, LocalizedText value shall be encoded as a
  801. * JSON string containing the Text component.*/
  802. return ENCODE_DIRECT_JSON(&src->text, String);
  803. }
  804. ENCODE_JSON(QualifiedName) {
  805. status ret = writeJsonObjStart(ctx);
  806. ret |= writeJsonKey(ctx, UA_JSONKEY_NAME);
  807. ret |= ENCODE_DIRECT_JSON(&src->name, String);
  808. if(ctx->useReversible) {
  809. if(src->namespaceIndex != 0) {
  810. ret |= writeJsonKey(ctx, UA_JSONKEY_URI);
  811. ret |= ENCODE_DIRECT_JSON(&src->namespaceIndex, UInt16);
  812. }
  813. } else {
  814. /* For the non-reversible form, the NamespaceUri associated with the
  815. * NamespaceIndex portion of the QualifiedName is encoded as JSON string
  816. * unless the NamespaceIndex is 1 or if NamespaceUri is unknown. In
  817. * these cases, the NamespaceIndex is encoded as a JSON number. */
  818. if(src->namespaceIndex == 1) {
  819. ret |= writeJsonKey(ctx, UA_JSONKEY_URI);
  820. ret |= ENCODE_DIRECT_JSON(&src->namespaceIndex, UInt16);
  821. } else {
  822. ret |= writeJsonKey(ctx, UA_JSONKEY_URI);
  823. /* Check if Namespace given and in range */
  824. if(src->namespaceIndex < ctx->namespacesSize && ctx->namespaces != NULL) {
  825. UA_String namespaceEntry = ctx->namespaces[src->namespaceIndex];
  826. ret |= ENCODE_DIRECT_JSON(&namespaceEntry, String);
  827. } else {
  828. /* If not encode as number */
  829. ret |= ENCODE_DIRECT_JSON(&src->namespaceIndex, UInt16);
  830. }
  831. }
  832. }
  833. return ret | writeJsonObjEnd(ctx);
  834. }
  835. ENCODE_JSON(StatusCode) {
  836. if(!src)
  837. return writeJsonNull(ctx);
  838. if(ctx->useReversible)
  839. return ENCODE_DIRECT_JSON(src, UInt32);
  840. if(*src == UA_STATUSCODE_GOOD)
  841. return writeJsonNull(ctx);
  842. status ret = UA_STATUSCODE_GOOD;
  843. ret |= writeJsonObjStart(ctx);
  844. ret |= writeJsonKey(ctx, UA_JSONKEY_CODE);
  845. ret |= ENCODE_DIRECT_JSON(src, UInt32);
  846. ret |= writeJsonKey(ctx, UA_JSONKEY_SYMBOL);
  847. const char *codename = UA_StatusCode_name(*src);
  848. UA_String statusDescription = UA_STRING((char*)(uintptr_t)codename);
  849. ret |= ENCODE_DIRECT_JSON(&statusDescription, String);
  850. ret |= writeJsonObjEnd(ctx);
  851. return ret;
  852. }
  853. /* ExtensionObject */
  854. ENCODE_JSON(ExtensionObject) {
  855. u8 encoding = (u8) src->encoding;
  856. if(encoding == UA_EXTENSIONOBJECT_ENCODED_NOBODY)
  857. return writeJsonNull(ctx);
  858. status ret = UA_STATUSCODE_GOOD;
  859. /* already encoded content.*/
  860. if(encoding <= UA_EXTENSIONOBJECT_ENCODED_XML) {
  861. ret |= writeJsonObjStart(ctx);
  862. if(ctx->useReversible) {
  863. ret |= writeJsonKey(ctx, UA_JSONKEY_TYPEID);
  864. ret |= ENCODE_DIRECT_JSON(&src->content.encoded.typeId, NodeId);
  865. if(ret != UA_STATUSCODE_GOOD)
  866. return ret;
  867. }
  868. switch (src->encoding) {
  869. case UA_EXTENSIONOBJECT_ENCODED_BYTESTRING:
  870. {
  871. if(ctx->useReversible) {
  872. ret |= writeJsonKey(ctx, UA_JSONKEY_ENCODING);
  873. ret |= writeChar(ctx, '1');
  874. }
  875. ret |= writeJsonKey(ctx, UA_JSONKEY_BODY);
  876. ret |= ENCODE_DIRECT_JSON(&src->content.encoded.body, String);
  877. break;
  878. }
  879. case UA_EXTENSIONOBJECT_ENCODED_XML:
  880. {
  881. if(ctx->useReversible) {
  882. ret |= writeJsonKey(ctx, UA_JSONKEY_ENCODING);
  883. ret |= writeChar(ctx, '2');
  884. }
  885. ret |= writeJsonKey(ctx, UA_JSONKEY_BODY);
  886. ret |= ENCODE_DIRECT_JSON(&src->content.encoded.body, String);
  887. break;
  888. }
  889. default:
  890. ret = UA_STATUSCODE_BADINTERNALERROR;
  891. }
  892. ret |= writeJsonObjEnd(ctx);
  893. return ret;
  894. } /* encoding <= UA_EXTENSIONOBJECT_ENCODED_XML */
  895. /* Cannot encode with no type description */
  896. if(!src->content.decoded.type)
  897. return UA_STATUSCODE_BADENCODINGERROR;
  898. if(!src->content.decoded.data)
  899. return writeJsonNull(ctx);
  900. UA_NodeId typeId = src->content.decoded.type->typeId;
  901. if(typeId.identifierType != UA_NODEIDTYPE_NUMERIC)
  902. return UA_STATUSCODE_BADENCODINGERROR;
  903. ret |= writeJsonObjStart(ctx);
  904. const UA_DataType *contentType = src->content.decoded.type;
  905. if(ctx->useReversible) {
  906. /* REVERSIBLE */
  907. ret |= writeJsonKey(ctx, UA_JSONKEY_TYPEID);
  908. ret |= ENCODE_DIRECT_JSON(&typeId, NodeId);
  909. /* Encode the content */
  910. ret |= writeJsonKey(ctx, UA_JSONKEY_BODY);
  911. ret |= encodeJsonInternal(src->content.decoded.data, contentType, ctx);
  912. } else {
  913. /* NON-REVERSIBLE
  914. * For the non-reversible form, ExtensionObject values
  915. * shall be encoded as a JSON object containing only the
  916. * value of the Body field. The TypeId and Encoding fields are dropped.
  917. *
  918. * TODO: UA_JSONKEY_BODY key in the ExtensionObject?
  919. */
  920. ret |= writeJsonKey(ctx, UA_JSONKEY_BODY);
  921. ret |= encodeJsonInternal(src->content.decoded.data, contentType, ctx);
  922. }
  923. ret |= writeJsonObjEnd(ctx);
  924. return ret;
  925. }
  926. static status
  927. Variant_encodeJsonWrapExtensionObject(const UA_Variant *src, const bool isArray, CtxJson *ctx) {
  928. size_t length = 1;
  929. status ret = UA_STATUSCODE_GOOD;
  930. if(isArray) {
  931. if(src->arrayLength > UA_INT32_MAX)
  932. return UA_STATUSCODE_BADENCODINGERROR;
  933. length = src->arrayLength;
  934. }
  935. /* Set up the ExtensionObject */
  936. UA_ExtensionObject eo;
  937. UA_ExtensionObject_init(&eo);
  938. eo.encoding = UA_EXTENSIONOBJECT_DECODED;
  939. eo.content.decoded.type = src->type;
  940. const u16 memSize = src->type->memSize;
  941. uintptr_t ptr = (uintptr_t) src->data;
  942. if(isArray) {
  943. ret |= writeJsonArrStart(ctx);
  944. ctx->commaNeeded[ctx->depth] = false;
  945. /* Iterate over the array */
  946. for(size_t i = 0; i < length && ret == UA_STATUSCODE_GOOD; ++i) {
  947. eo.content.decoded.data = (void*) ptr;
  948. ret |= writeJsonArrElm(ctx, &eo, &UA_TYPES[UA_TYPES_EXTENSIONOBJECT]);
  949. ptr += memSize;
  950. }
  951. ret |= writeJsonArrEnd(ctx);
  952. return ret;
  953. }
  954. eo.content.decoded.data = (void*) ptr;
  955. return encodeJsonInternal(&eo, &UA_TYPES[UA_TYPES_EXTENSIONOBJECT], ctx);
  956. }
  957. static status
  958. addMultiArrayContentJSON(CtxJson *ctx, void* array, const UA_DataType *type,
  959. size_t *index, UA_UInt32 *arrayDimensions, size_t dimensionIndex,
  960. size_t dimensionSize) {
  961. /* Check the recursion limit */
  962. if(ctx->depth > UA_JSON_ENCODING_MAX_RECURSION)
  963. return UA_STATUSCODE_BADENCODINGERROR;
  964. /* Stop recursion: The inner Arrays are written */
  965. status ret;
  966. if(dimensionIndex == (dimensionSize - 1)) {
  967. ret = encodeJsonArray(ctx, ((u8*)array) + (type->memSize * *index),
  968. arrayDimensions[dimensionIndex], type);
  969. (*index) += arrayDimensions[dimensionIndex];
  970. return ret;
  971. }
  972. /* Recurse to the next dimension */
  973. ret = writeJsonArrStart(ctx);
  974. for(size_t i = 0; i < arrayDimensions[dimensionIndex]; i++) {
  975. ret |= writeJsonCommaIfNeeded(ctx);
  976. ret |= addMultiArrayContentJSON(ctx, array, type, index, arrayDimensions,
  977. dimensionIndex + 1, dimensionSize);
  978. ctx->commaNeeded[ctx->depth] = true;
  979. if(ret != UA_STATUSCODE_GOOD)
  980. return ret;
  981. }
  982. ret |= writeJsonArrEnd(ctx);
  983. return ret;
  984. }
  985. ENCODE_JSON(Variant) {
  986. /* If type is 0 (NULL) the Variant contains a NULL value and the containing
  987. * JSON object shall be omitted or replaced by the JSON literal ‘null’ (when
  988. * an element of a JSON array). */
  989. if(!src->type) {
  990. return writeJsonNull(ctx);
  991. }
  992. /* Set the content type in the encoding mask */
  993. const UA_Boolean isBuiltin = (src->type->typeKind <= UA_DATATYPEKIND_DIAGNOSTICINFO);
  994. const UA_Boolean isEnum = (src->type->typeKind == UA_DATATYPEKIND_ENUM);
  995. /* Set the array type in the encoding mask */
  996. const bool isArray = src->arrayLength > 0 || src->data <= UA_EMPTY_ARRAY_SENTINEL;
  997. const bool hasDimensions = isArray && src->arrayDimensionsSize > 0;
  998. status ret = UA_STATUSCODE_GOOD;
  999. if(ctx->useReversible) {
  1000. ret |= writeJsonObjStart(ctx);
  1001. if(ret != UA_STATUSCODE_GOOD)
  1002. return ret;
  1003. /* Encode the content */
  1004. if(!isBuiltin && !isEnum) {
  1005. /* REVERSIBLE: NOT BUILTIN, can it be encoded? Wrap in extension object.*/
  1006. ret |= writeJsonKey(ctx, UA_JSONKEY_TYPE);
  1007. ret |= ENCODE_DIRECT_JSON(&UA_TYPES[UA_TYPES_EXTENSIONOBJECT].typeId.identifier.numeric, UInt32);
  1008. ret |= writeJsonKey(ctx, UA_JSONKEY_BODY);
  1009. ret |= Variant_encodeJsonWrapExtensionObject(src, isArray, ctx);
  1010. } else if(!isArray) {
  1011. /*REVERSIBLE: BUILTIN, single value.*/
  1012. ret |= writeJsonKey(ctx, UA_JSONKEY_TYPE);
  1013. ret |= ENCODE_DIRECT_JSON(&src->type->typeId.identifier.numeric, UInt32);
  1014. ret |= writeJsonKey(ctx, UA_JSONKEY_BODY);
  1015. ret |= encodeJsonInternal(src->data, src->type, ctx);
  1016. } else {
  1017. /*REVERSIBLE: BUILTIN, array.*/
  1018. ret |= writeJsonKey(ctx, UA_JSONKEY_TYPE);
  1019. ret |= ENCODE_DIRECT_JSON(&src->type->typeId.identifier.numeric, UInt32);
  1020. ret |= writeJsonKey(ctx, UA_JSONKEY_BODY);
  1021. ret |= encodeJsonArray(ctx, src->data, src->arrayLength, src->type);
  1022. }
  1023. if(ret != UA_STATUSCODE_GOOD)
  1024. return ret;
  1025. /* REVERSIBLE: Encode the array dimensions */
  1026. if(hasDimensions && ret == UA_STATUSCODE_GOOD) {
  1027. ret |= writeJsonKey(ctx, UA_JSONKEY_DIMENSION);
  1028. ret |= encodeJsonArray(ctx, src->arrayDimensions, src->arrayDimensionsSize,
  1029. &UA_TYPES[UA_TYPES_INT32]);
  1030. if(ret != UA_STATUSCODE_GOOD)
  1031. return ret;
  1032. }
  1033. ret |= writeJsonObjEnd(ctx);
  1034. return ret;
  1035. } /* reversible */
  1036. /* NON-REVERSIBLE
  1037. * For the non-reversible form, Variant values shall be encoded as a JSON object containing only
  1038. * the value of the Body field. The Type and Dimensions fields are dropped. Multi-dimensional
  1039. * arrays are encoded as a multi dimensional JSON array as described in 5.4.5.
  1040. */
  1041. ret |= writeJsonObjStart(ctx);
  1042. if(!isBuiltin && !isEnum) {
  1043. /*NON REVERSIBLE: NOT BUILTIN, can it be encoded? Wrap in extension object.*/
  1044. if(src->arrayDimensionsSize > 1) {
  1045. return UA_STATUSCODE_BADNOTIMPLEMENTED;
  1046. }
  1047. ret |= writeJsonKey(ctx, UA_JSONKEY_BODY);
  1048. ret |= Variant_encodeJsonWrapExtensionObject(src, isArray, ctx);
  1049. } else if(!isArray) {
  1050. /*NON REVERSIBLE: BUILTIN, single value.*/
  1051. ret |= writeJsonKey(ctx, UA_JSONKEY_BODY);
  1052. ret |= encodeJsonInternal(src->data, src->type, ctx);
  1053. } else {
  1054. /*NON REVERSIBLE: BUILTIN, array.*/
  1055. ret |= writeJsonKey(ctx, UA_JSONKEY_BODY);
  1056. size_t dimensionSize = src->arrayDimensionsSize;
  1057. if(dimensionSize > 1) {
  1058. /*nonreversible multidimensional array*/
  1059. size_t index = 0; size_t dimensionIndex = 0;
  1060. void *ptr = src->data;
  1061. const UA_DataType *arraytype = src->type;
  1062. ret |= addMultiArrayContentJSON(ctx, ptr, arraytype, &index,
  1063. src->arrayDimensions, dimensionIndex, dimensionSize);
  1064. } else {
  1065. /*nonreversible simple array*/
  1066. ret |= encodeJsonArray(ctx, src->data, src->arrayLength, src->type);
  1067. }
  1068. }
  1069. ret |= writeJsonObjEnd(ctx);
  1070. return ret;
  1071. }
  1072. /* DataValue */
  1073. ENCODE_JSON(DataValue) {
  1074. UA_Boolean hasValue = src->hasValue && src->value.type != NULL;
  1075. UA_Boolean hasStatus = src->hasStatus && src->status;
  1076. UA_Boolean hasSourceTimestamp = src->hasSourceTimestamp && src->sourceTimestamp;
  1077. UA_Boolean hasSourcePicoseconds = src->hasSourcePicoseconds && src->sourcePicoseconds;
  1078. UA_Boolean hasServerTimestamp = src->hasServerTimestamp && src->serverTimestamp;
  1079. UA_Boolean hasServerPicoseconds = src->hasServerPicoseconds && src->serverPicoseconds;
  1080. if(!hasValue && !hasStatus && !hasSourceTimestamp && !hasSourcePicoseconds &&
  1081. !hasServerTimestamp && !hasServerPicoseconds) {
  1082. return writeJsonNull(ctx); /*no element, encode as null*/
  1083. }
  1084. status ret = UA_STATUSCODE_GOOD;
  1085. ret |= writeJsonObjStart(ctx);
  1086. if(hasValue) {
  1087. ret |= writeJsonKey(ctx, UA_JSONKEY_VALUE);
  1088. ret |= ENCODE_DIRECT_JSON(&src->value, Variant);
  1089. if(ret != UA_STATUSCODE_GOOD)
  1090. return ret;
  1091. }
  1092. if(hasStatus) {
  1093. ret |= writeJsonKey(ctx, UA_JSONKEY_STATUS);
  1094. ret |= ENCODE_DIRECT_JSON(&src->status, StatusCode);
  1095. if(ret != UA_STATUSCODE_GOOD)
  1096. return ret;
  1097. }
  1098. if(hasSourceTimestamp) {
  1099. ret |= writeJsonKey(ctx, UA_JSONKEY_SOURCETIMESTAMP);
  1100. ret |= ENCODE_DIRECT_JSON(&src->sourceTimestamp, DateTime);
  1101. if(ret != UA_STATUSCODE_GOOD)
  1102. return ret;
  1103. }
  1104. if(hasSourcePicoseconds) {
  1105. ret |= writeJsonKey(ctx, UA_JSONKEY_SOURCEPICOSECONDS);
  1106. ret |= ENCODE_DIRECT_JSON(&src->sourcePicoseconds, UInt16);
  1107. if(ret != UA_STATUSCODE_GOOD)
  1108. return ret;
  1109. }
  1110. if(hasServerTimestamp) {
  1111. ret |= writeJsonKey(ctx, UA_JSONKEY_SERVERTIMESTAMP);
  1112. ret |= ENCODE_DIRECT_JSON(&src->serverTimestamp, DateTime);
  1113. if(ret != UA_STATUSCODE_GOOD)
  1114. return ret;
  1115. }
  1116. if(hasServerPicoseconds) {
  1117. ret |= writeJsonKey(ctx, UA_JSONKEY_SERVERPICOSECONDS);
  1118. ret |= ENCODE_DIRECT_JSON(&src->serverPicoseconds, UInt16);
  1119. if(ret != UA_STATUSCODE_GOOD)
  1120. return ret;
  1121. }
  1122. ret |= writeJsonObjEnd(ctx);
  1123. return ret;
  1124. }
  1125. /* DiagnosticInfo */
  1126. ENCODE_JSON(DiagnosticInfo) {
  1127. status ret = UA_STATUSCODE_GOOD;
  1128. if(!src->hasSymbolicId && !src->hasNamespaceUri && !src->hasLocalizedText &&
  1129. !src->hasLocale && !src->hasAdditionalInfo && !src->hasInnerDiagnosticInfo &&
  1130. !src->hasInnerStatusCode) {
  1131. return writeJsonNull(ctx); /*no element present, encode as null.*/
  1132. }
  1133. ret |= writeJsonObjStart(ctx);
  1134. if(src->hasSymbolicId) {
  1135. ret |= writeJsonKey(ctx, UA_JSONKEY_SYMBOLICID);
  1136. ret |= ENCODE_DIRECT_JSON(&src->symbolicId, UInt32);
  1137. if(ret != UA_STATUSCODE_GOOD)
  1138. return ret;
  1139. }
  1140. if(src->hasNamespaceUri) {
  1141. ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACEURI);
  1142. ret |= ENCODE_DIRECT_JSON(&src->namespaceUri, UInt32);
  1143. if(ret != UA_STATUSCODE_GOOD)
  1144. return ret;
  1145. }
  1146. if(src->hasLocalizedText) {
  1147. ret |= writeJsonKey(ctx, UA_JSONKEY_LOCALIZEDTEXT);
  1148. ret |= ENCODE_DIRECT_JSON(&src->localizedText, UInt32);
  1149. if(ret != UA_STATUSCODE_GOOD)
  1150. return ret;
  1151. }
  1152. if(src->hasLocale) {
  1153. ret |= writeJsonKey(ctx, UA_JSONKEY_LOCALE);
  1154. ret |= ENCODE_DIRECT_JSON(&src->locale, UInt32);
  1155. if(ret != UA_STATUSCODE_GOOD)
  1156. return ret;
  1157. }
  1158. if(src->hasAdditionalInfo) {
  1159. ret |= writeJsonKey(ctx, UA_JSONKEY_ADDITIONALINFO);
  1160. ret |= ENCODE_DIRECT_JSON(&src->additionalInfo, String);
  1161. if(ret != UA_STATUSCODE_GOOD)
  1162. return ret;
  1163. }
  1164. if(src->hasInnerStatusCode) {
  1165. ret |= writeJsonKey(ctx, UA_JSONKEY_INNERSTATUSCODE);
  1166. ret |= ENCODE_DIRECT_JSON(&src->innerStatusCode, StatusCode);
  1167. if(ret != UA_STATUSCODE_GOOD)
  1168. return ret;
  1169. }
  1170. if(src->hasInnerDiagnosticInfo && src->innerDiagnosticInfo) {
  1171. ret |= writeJsonKey(ctx, UA_JSONKEY_INNERDIAGNOSTICINFO);
  1172. /* Check recursion depth in encodeJsonInternal */
  1173. ret |= encodeJsonInternal(src->innerDiagnosticInfo, &UA_TYPES[UA_TYPES_DIAGNOSTICINFO], ctx);
  1174. if(ret != UA_STATUSCODE_GOOD)
  1175. return ret;
  1176. }
  1177. ret |= writeJsonObjEnd(ctx);
  1178. return ret;
  1179. }
  1180. static status
  1181. encodeJsonStructure(const void *src, const UA_DataType *type, CtxJson *ctx) {
  1182. /* Check the recursion limit */
  1183. if(ctx->depth > UA_JSON_ENCODING_MAX_RECURSION)
  1184. return UA_STATUSCODE_BADENCODINGERROR;
  1185. ctx->depth++;
  1186. status ret = writeJsonObjStart(ctx);
  1187. uintptr_t ptr = (uintptr_t) src;
  1188. u8 membersSize = type->membersSize;
  1189. const UA_DataType * typelists[2] = {UA_TYPES, &type[-type->typeIndex]};
  1190. for(size_t i = 0; i < membersSize && ret == UA_STATUSCODE_GOOD; ++i) {
  1191. const UA_DataTypeMember *m = &type->members[i];
  1192. const UA_DataType *mt = &typelists[!m->namespaceZero][m->memberTypeIndex];
  1193. if(m->memberName != NULL && *m->memberName != 0)
  1194. ret |= writeJsonKey(ctx, m->memberName);
  1195. if(!m->isArray) {
  1196. ptr += m->padding;
  1197. size_t memSize = mt->memSize;
  1198. ret |= encodeJsonJumpTable[mt->typeKind]((const void*) ptr, mt, ctx);
  1199. ptr += memSize;
  1200. } else {
  1201. ptr += m->padding;
  1202. const size_t length = *((const size_t*) ptr);
  1203. ptr += sizeof (size_t);
  1204. ret |= encodeJsonArray(ctx, *(void * const *)ptr, length, mt);
  1205. ptr += sizeof (void*);
  1206. }
  1207. }
  1208. ret |= writeJsonObjEnd(ctx);
  1209. ctx->depth--;
  1210. return ret;
  1211. }
  1212. static status
  1213. encodeJsonNotImplemented(const void *src, const UA_DataType *type, CtxJson *ctx) {
  1214. (void) src, (void) type, (void)ctx;
  1215. return UA_STATUSCODE_BADNOTIMPLEMENTED;
  1216. }
  1217. const encodeJsonSignature encodeJsonJumpTable[UA_DATATYPEKINDS] = {
  1218. (encodeJsonSignature)Boolean_encodeJson,
  1219. (encodeJsonSignature)SByte_encodeJson, /* SByte */
  1220. (encodeJsonSignature)Byte_encodeJson,
  1221. (encodeJsonSignature)Int16_encodeJson, /* Int16 */
  1222. (encodeJsonSignature)UInt16_encodeJson,
  1223. (encodeJsonSignature)Int32_encodeJson, /* Int32 */
  1224. (encodeJsonSignature)UInt32_encodeJson,
  1225. (encodeJsonSignature)Int64_encodeJson, /* Int64 */
  1226. (encodeJsonSignature)UInt64_encodeJson,
  1227. (encodeJsonSignature)Float_encodeJson,
  1228. (encodeJsonSignature)Double_encodeJson,
  1229. (encodeJsonSignature)String_encodeJson,
  1230. (encodeJsonSignature)DateTime_encodeJson, /* DateTime */
  1231. (encodeJsonSignature)Guid_encodeJson,
  1232. (encodeJsonSignature)ByteString_encodeJson, /* ByteString */
  1233. (encodeJsonSignature)String_encodeJson, /* XmlElement */
  1234. (encodeJsonSignature)NodeId_encodeJson,
  1235. (encodeJsonSignature)ExpandedNodeId_encodeJson,
  1236. (encodeJsonSignature)StatusCode_encodeJson, /* StatusCode */
  1237. (encodeJsonSignature)QualifiedName_encodeJson, /* QualifiedName */
  1238. (encodeJsonSignature)LocalizedText_encodeJson,
  1239. (encodeJsonSignature)ExtensionObject_encodeJson,
  1240. (encodeJsonSignature)DataValue_encodeJson,
  1241. (encodeJsonSignature)Variant_encodeJson,
  1242. (encodeJsonSignature)DiagnosticInfo_encodeJson,
  1243. (encodeJsonSignature)encodeJsonNotImplemented, /* Decimal */
  1244. (encodeJsonSignature)Int32_encodeJson, /* Enum */
  1245. (encodeJsonSignature)encodeJsonStructure,
  1246. (encodeJsonSignature)encodeJsonNotImplemented, /* Structure with optional fields */
  1247. (encodeJsonSignature)encodeJsonNotImplemented, /* Union */
  1248. (encodeJsonSignature)encodeJsonNotImplemented /* BitfieldCluster */
  1249. };
  1250. status
  1251. encodeJsonInternal(const void *src, const UA_DataType *type, CtxJson *ctx) {
  1252. return encodeJsonJumpTable[type->typeKind](src, type, ctx);
  1253. }
  1254. status UA_FUNC_ATTR_WARN_UNUSED_RESULT
  1255. UA_encodeJson(const void *src, const UA_DataType *type,
  1256. u8 **bufPos, const u8 **bufEnd, UA_String *namespaces,
  1257. size_t namespaceSize, UA_String *serverUris,
  1258. size_t serverUriSize, UA_Boolean useReversible) {
  1259. if(!src || !type)
  1260. return UA_STATUSCODE_BADINTERNALERROR;
  1261. /* Set up the context */
  1262. CtxJson ctx;
  1263. memset(&ctx, 0, sizeof(ctx));
  1264. ctx.pos = *bufPos;
  1265. ctx.end = *bufEnd;
  1266. ctx.depth = 0;
  1267. ctx.namespaces = namespaces;
  1268. ctx.namespacesSize = namespaceSize;
  1269. ctx.serverUris = serverUris;
  1270. ctx.serverUrisSize = serverUriSize;
  1271. ctx.useReversible = useReversible;
  1272. ctx.calcOnly = false;
  1273. /* Encode */
  1274. status ret = encodeJsonJumpTable[type->typeKind](src, type, &ctx);
  1275. *bufPos = ctx.pos;
  1276. *bufEnd = ctx.end;
  1277. return ret;
  1278. }
  1279. /************/
  1280. /* CalcSize */
  1281. /************/
  1282. size_t
  1283. UA_calcSizeJson(const void *src, const UA_DataType *type,
  1284. UA_String *namespaces, size_t namespaceSize,
  1285. UA_String *serverUris, size_t serverUriSize,
  1286. UA_Boolean useReversible) {
  1287. if(!src || !type)
  1288. return UA_STATUSCODE_BADINTERNALERROR;
  1289. /* Set up the context */
  1290. CtxJson ctx;
  1291. memset(&ctx, 0, sizeof(ctx));
  1292. ctx.pos = 0;
  1293. ctx.end = (const UA_Byte*)(uintptr_t)SIZE_MAX;
  1294. ctx.depth = 0;
  1295. ctx.namespaces = namespaces;
  1296. ctx.namespacesSize = namespaceSize;
  1297. ctx.serverUris = serverUris;
  1298. ctx.serverUrisSize = serverUriSize;
  1299. ctx.useReversible = useReversible;
  1300. ctx.calcOnly = true;
  1301. /* Encode */
  1302. status ret = encodeJsonJumpTable[type->typeKind](src, type, &ctx);
  1303. if(ret != UA_STATUSCODE_GOOD)
  1304. return 0;
  1305. return (size_t)ctx.pos;
  1306. }
  1307. /**********/
  1308. /* Decode */
  1309. /**********/
  1310. /* Macro which gets current size and char pointer of current Token. Needs
  1311. * ParseCtx (parseCtx) and CtxJson (ctx). Does NOT increment index of Token. */
  1312. #define GET_TOKEN(data, size) do { \
  1313. (size) = (size_t)(parseCtx->tokenArray[parseCtx->index].end - parseCtx->tokenArray[parseCtx->index].start); \
  1314. (data) = (char*)(ctx->pos + parseCtx->tokenArray[parseCtx->index].start); } while(0)
  1315. #define ALLOW_NULL do { \
  1316. if(isJsonNull(ctx, parseCtx)) { \
  1317. parseCtx->index++; \
  1318. return UA_STATUSCODE_GOOD; \
  1319. }} while(0)
  1320. #define CHECK_TOKEN_BOUNDS do { \
  1321. if(parseCtx->index >= parseCtx->tokenCount) \
  1322. return UA_STATUSCODE_BADDECODINGERROR; \
  1323. } while(0)
  1324. #define CHECK_PRIMITIVE do { \
  1325. if(getJsmnType(parseCtx) != JSMN_PRIMITIVE) { \
  1326. return UA_STATUSCODE_BADDECODINGERROR; \
  1327. }} while(0)
  1328. #define CHECK_STRING do { \
  1329. if(getJsmnType(parseCtx) != JSMN_STRING) { \
  1330. return UA_STATUSCODE_BADDECODINGERROR; \
  1331. }} while(0)
  1332. #define CHECK_OBJECT do { \
  1333. if(getJsmnType(parseCtx) != JSMN_OBJECT) { \
  1334. return UA_STATUSCODE_BADDECODINGERROR; \
  1335. }} while(0)
  1336. /* Forward declarations*/
  1337. #define DECODE_JSON(TYPE) static status \
  1338. TYPE##_decodeJson(UA_##TYPE *dst, const UA_DataType *type, \
  1339. CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken)
  1340. /* decode without moving the token index */
  1341. #define DECODE_DIRECT_JSON(DST, TYPE) TYPE##_decodeJson((UA_##TYPE*)DST, NULL, ctx, parseCtx, false)
  1342. static status
  1343. Array_decodeJson(void *dst, const UA_DataType *type, CtxJson *ctx,
  1344. ParseCtx *parseCtx, UA_Boolean moveToken);
  1345. static status
  1346. Array_decodeJson_internal(void **dst, const UA_DataType *type,
  1347. CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken);
  1348. static status
  1349. Variant_decodeJsonUnwrapExtensionObject(UA_Variant *dst, const UA_DataType *type,
  1350. CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken);
  1351. /* Json decode Helper */
  1352. jsmntype_t
  1353. getJsmnType(const ParseCtx *parseCtx) {
  1354. if(parseCtx->index >= parseCtx->tokenCount)
  1355. return JSMN_UNDEFINED;
  1356. return parseCtx->tokenArray[parseCtx->index].type;
  1357. }
  1358. static UA_Boolean
  1359. isJsonTokenNull(const CtxJson *ctx, jsmntok_t *token) {
  1360. if(token->type != JSMN_PRIMITIVE)
  1361. return false;
  1362. char* elem = (char*)(ctx->pos + token->start);
  1363. return (elem[0] == 'n' && elem[1] == 'u' && elem[2] == 'l' && elem[3] == 'l');
  1364. }
  1365. UA_Boolean
  1366. isJsonNull(const CtxJson *ctx, const ParseCtx *parseCtx) {
  1367. if(parseCtx->index >= parseCtx->tokenCount)
  1368. return false;
  1369. if(parseCtx->tokenArray[parseCtx->index].type != JSMN_PRIMITIVE) {
  1370. return false;
  1371. }
  1372. char* elem = (char*)(ctx->pos + parseCtx->tokenArray[parseCtx->index].start);
  1373. return (elem[0] == 'n' && elem[1] == 'u' && elem[2] == 'l' && elem[3] == 'l');
  1374. }
  1375. static UA_SByte jsoneq(const char *json, jsmntok_t *tok, const char *searchKey) {
  1376. /* TODO: necessary?
  1377. if(json == NULL
  1378. || tok == NULL
  1379. || searchKey == NULL) {
  1380. return -1;
  1381. } */
  1382. if(tok->type == JSMN_STRING) {
  1383. if(strlen(searchKey) == (size_t)(tok->end - tok->start) ) {
  1384. if(strncmp(json + tok->start,
  1385. (const char*)searchKey, (size_t)(tok->end - tok->start)) == 0) {
  1386. return 0;
  1387. }
  1388. }
  1389. }
  1390. return -1;
  1391. }
  1392. DECODE_JSON(Boolean) {
  1393. CHECK_PRIMITIVE;
  1394. CHECK_TOKEN_BOUNDS;
  1395. size_t tokenSize;
  1396. char* tokenData;
  1397. GET_TOKEN(tokenData, tokenSize);
  1398. if(tokenSize == 4 &&
  1399. tokenData[0] == 't' && tokenData[1] == 'r' &&
  1400. tokenData[2] == 'u' && tokenData[3] == 'e') {
  1401. *dst = true;
  1402. } else if(tokenSize == 5 &&
  1403. tokenData[0] == 'f' && tokenData[1] == 'a' &&
  1404. tokenData[2] == 'l' && tokenData[3] == 's' &&
  1405. tokenData[4] == 'e') {
  1406. *dst = false;
  1407. } else {
  1408. return UA_STATUSCODE_BADDECODINGERROR;
  1409. }
  1410. if(moveToken)
  1411. parseCtx->index++;
  1412. return UA_STATUSCODE_GOOD;
  1413. }
  1414. #ifdef UA_ENABLE_CUSTOM_LIBC
  1415. static UA_StatusCode
  1416. parseUnsignedInteger(char* inputBuffer, size_t sizeOfBuffer,
  1417. UA_UInt64 *destinationOfNumber) {
  1418. UA_UInt64 d = 0;
  1419. atoiUnsigned(inputBuffer, sizeOfBuffer, &d);
  1420. if(!destinationOfNumber)
  1421. return UA_STATUSCODE_BADDECODINGERROR;
  1422. *destinationOfNumber = d;
  1423. return UA_STATUSCODE_GOOD;
  1424. }
  1425. static UA_StatusCode
  1426. parseSignedInteger(char* inputBuffer, size_t sizeOfBuffer,
  1427. UA_Int64 *destinationOfNumber) {
  1428. UA_Int64 d = 0;
  1429. atoiSigned(inputBuffer, sizeOfBuffer, &d);
  1430. if(!destinationOfNumber)
  1431. return UA_STATUSCODE_BADDECODINGERROR;
  1432. *destinationOfNumber = d;
  1433. return UA_STATUSCODE_GOOD;
  1434. }
  1435. #else
  1436. /* Safe strtol variant of unsigned string conversion.
  1437. * Returns UA_STATUSCODE_BADDECODINGERROR in case of overflows.
  1438. * Buffer limit is 20 digits. */
  1439. static UA_StatusCode
  1440. parseUnsignedInteger(char* inputBuffer, size_t sizeOfBuffer,
  1441. UA_UInt64 *destinationOfNumber) {
  1442. /* Check size to avoid huge malicious stack allocation.
  1443. * No UInt64 can have more digits than 20. */
  1444. if(sizeOfBuffer > 20) {
  1445. return UA_STATUSCODE_BADDECODINGERROR;
  1446. }
  1447. /* convert to null terminated string */
  1448. UA_STACKARRAY(char, string, sizeOfBuffer+1);
  1449. memcpy(string, inputBuffer, sizeOfBuffer);
  1450. string[sizeOfBuffer] = 0;
  1451. /* Conversion */
  1452. char *endptr, *str;
  1453. str = string;
  1454. errno = 0; /* To distinguish success/failure after call */
  1455. UA_UInt64 val = strtoull(str, &endptr, 10);
  1456. /* Check for various possible errors */
  1457. if((errno == ERANGE && (val == LLONG_MAX || val == 0))
  1458. || (errno != 0 )) {
  1459. return UA_STATUSCODE_BADDECODINGERROR;
  1460. }
  1461. /* Check if no digits were found */
  1462. if(endptr == str)
  1463. return UA_STATUSCODE_BADDECODINGERROR;
  1464. /* copy to destination */
  1465. *destinationOfNumber = val;
  1466. return UA_STATUSCODE_GOOD;
  1467. }
  1468. /* Safe strtol variant of unsigned string conversion.
  1469. * Returns UA_STATUSCODE_BADDECODINGERROR in case of overflows.
  1470. * Buffer limit is 20 digits. */
  1471. static UA_StatusCode
  1472. parseSignedInteger(char* inputBuffer, size_t sizeOfBuffer,
  1473. UA_Int64 *destinationOfNumber) {
  1474. /* Check size to avoid huge malicious stack allocation.
  1475. * No UInt64 can have more digits than 20. */
  1476. if(sizeOfBuffer > 20)
  1477. return UA_STATUSCODE_BADDECODINGERROR;
  1478. /* convert to null terminated string */
  1479. UA_STACKARRAY(char, string, sizeOfBuffer + 1);
  1480. memcpy(string, inputBuffer, sizeOfBuffer);
  1481. string[sizeOfBuffer] = 0;
  1482. /* Conversion */
  1483. char *endptr, *str;
  1484. str = string;
  1485. errno = 0; /* To distinguish success/failure after call */
  1486. UA_Int64 val = strtoll(str, &endptr, 10);
  1487. /* Check for various possible errors */
  1488. if((errno == ERANGE && (val == LONG_MAX || val == LONG_MIN))
  1489. || (errno != 0 )) {
  1490. return UA_STATUSCODE_BADDECODINGERROR;
  1491. }
  1492. /* Check if no digits were found */
  1493. if(endptr == str)
  1494. return UA_STATUSCODE_BADDECODINGERROR;
  1495. /* copy to destination */
  1496. *destinationOfNumber = val;
  1497. return UA_STATUSCODE_GOOD;
  1498. }
  1499. #endif
  1500. DECODE_JSON(Byte) {
  1501. CHECK_TOKEN_BOUNDS;
  1502. CHECK_PRIMITIVE;
  1503. size_t tokenSize;
  1504. char* tokenData;
  1505. GET_TOKEN(tokenData, tokenSize);
  1506. UA_UInt64 out = 0;
  1507. UA_StatusCode s = parseUnsignedInteger(tokenData, tokenSize, &out);
  1508. *dst = (UA_Byte)out;
  1509. if(moveToken)
  1510. parseCtx->index++;
  1511. return s;
  1512. }
  1513. DECODE_JSON(UInt16) {
  1514. CHECK_TOKEN_BOUNDS;
  1515. CHECK_PRIMITIVE;
  1516. size_t tokenSize;
  1517. char* tokenData;
  1518. GET_TOKEN(tokenData, tokenSize);
  1519. UA_UInt64 out = 0;
  1520. UA_StatusCode s = parseUnsignedInteger(tokenData, tokenSize, &out);
  1521. *dst = (UA_UInt16)out;
  1522. if(moveToken)
  1523. parseCtx->index++;
  1524. return s;
  1525. }
  1526. DECODE_JSON(UInt32) {
  1527. CHECK_TOKEN_BOUNDS;
  1528. CHECK_PRIMITIVE;
  1529. size_t tokenSize;
  1530. char* tokenData;
  1531. GET_TOKEN(tokenData, tokenSize);
  1532. UA_UInt64 out = 0;
  1533. UA_StatusCode s = parseUnsignedInteger(tokenData, tokenSize, &out);
  1534. *dst = (UA_UInt32)out;
  1535. if(moveToken)
  1536. parseCtx->index++;
  1537. return s;
  1538. }
  1539. DECODE_JSON(UInt64) {
  1540. CHECK_TOKEN_BOUNDS;
  1541. CHECK_STRING;
  1542. size_t tokenSize;
  1543. char* tokenData;
  1544. GET_TOKEN(tokenData, tokenSize);
  1545. UA_UInt64 out = 0;
  1546. UA_StatusCode s = parseUnsignedInteger(tokenData, tokenSize, &out);
  1547. *dst = (UA_UInt64)out;
  1548. if(moveToken)
  1549. parseCtx->index++;
  1550. return s;
  1551. }
  1552. DECODE_JSON(SByte) {
  1553. CHECK_TOKEN_BOUNDS;
  1554. CHECK_PRIMITIVE;
  1555. size_t tokenSize;
  1556. char* tokenData;
  1557. GET_TOKEN(tokenData, tokenSize);
  1558. UA_Int64 out = 0;
  1559. UA_StatusCode s = parseSignedInteger(tokenData, tokenSize, &out);
  1560. *dst = (UA_SByte)out;
  1561. if(moveToken)
  1562. parseCtx->index++;
  1563. return s;
  1564. }
  1565. DECODE_JSON(Int16) {
  1566. CHECK_TOKEN_BOUNDS;
  1567. CHECK_PRIMITIVE;
  1568. size_t tokenSize;
  1569. char* tokenData;
  1570. GET_TOKEN(tokenData, tokenSize);
  1571. UA_Int64 out = 0;
  1572. UA_StatusCode s = parseSignedInteger(tokenData, tokenSize, &out);
  1573. *dst = (UA_Int16)out;
  1574. if(moveToken)
  1575. parseCtx->index++;
  1576. return s;
  1577. }
  1578. DECODE_JSON(Int32) {
  1579. CHECK_TOKEN_BOUNDS;
  1580. CHECK_PRIMITIVE;
  1581. size_t tokenSize;
  1582. char* tokenData;
  1583. GET_TOKEN(tokenData, tokenSize);
  1584. UA_Int64 out = 0;
  1585. UA_StatusCode s = parseSignedInteger(tokenData, tokenSize, &out);
  1586. *dst = (UA_Int32)out;
  1587. if(moveToken)
  1588. parseCtx->index++;
  1589. return s;
  1590. }
  1591. DECODE_JSON(Int64) {
  1592. CHECK_TOKEN_BOUNDS;
  1593. CHECK_STRING;
  1594. size_t tokenSize;
  1595. char* tokenData;
  1596. GET_TOKEN(tokenData, tokenSize);
  1597. UA_Int64 out = 0;
  1598. UA_StatusCode s = parseSignedInteger(tokenData, tokenSize, &out);
  1599. *dst = (UA_Int64)out;
  1600. if(moveToken)
  1601. parseCtx->index++;
  1602. return s;
  1603. }
  1604. static UA_UInt32 hex2int(char ch) {
  1605. if(ch >= '0' && ch <= '9')
  1606. return (UA_UInt32)(ch - '0');
  1607. if(ch >= 'A' && ch <= 'F')
  1608. return (UA_UInt32)(ch - 'A' + 10);
  1609. if(ch >= 'a' && ch <= 'f')
  1610. return (UA_UInt32)(ch - 'a' + 10);
  1611. return 0;
  1612. }
  1613. /* Float
  1614. * Either a JSMN_STRING or JSMN_PRIMITIVE
  1615. */
  1616. DECODE_JSON(Float) {
  1617. CHECK_TOKEN_BOUNDS;
  1618. size_t tokenSize;
  1619. char* tokenData;
  1620. GET_TOKEN(tokenData, tokenSize);
  1621. /* https://www.exploringbinary.com/maximum-number-of-decimal-digits-in-binary-floating-point-numbers/
  1622. * Maximum digit counts for select IEEE floating-point formats: 149
  1623. * Sanity check. */
  1624. if(tokenSize > 150)
  1625. return UA_STATUSCODE_BADDECODINGERROR;
  1626. jsmntype_t tokenType = getJsmnType(parseCtx);
  1627. if(tokenType == JSMN_STRING) {
  1628. /*It could be a String with Nan, Infinity*/
  1629. if(tokenSize == 8 && memcmp(tokenData, "Infinity", 8) == 0) {
  1630. *dst = (UA_Float)INFINITY;
  1631. return UA_STATUSCODE_GOOD;
  1632. }
  1633. if(tokenSize == 9 && memcmp(tokenData, "-Infinity", 9) == 0) {
  1634. /* workaround an MSVC 2013 issue */
  1635. *dst = (UA_Float)-INFINITY;
  1636. return UA_STATUSCODE_GOOD;
  1637. }
  1638. if(tokenSize == 3 && memcmp(tokenData, "NaN", 3) == 0) {
  1639. *dst = (UA_Float)NAN;
  1640. return UA_STATUSCODE_GOOD;
  1641. }
  1642. if(tokenSize == 4 && memcmp(tokenData, "-NaN", 4) == 0) {
  1643. *dst = (UA_Float)NAN;
  1644. return UA_STATUSCODE_GOOD;
  1645. }
  1646. return UA_STATUSCODE_BADDECODINGERROR;
  1647. }
  1648. if(tokenType != JSMN_PRIMITIVE)
  1649. return UA_STATUSCODE_BADDECODINGERROR;
  1650. /* Null-Terminate for sscanf. */
  1651. UA_STACKARRAY(char, string, tokenSize+1);
  1652. memcpy(string, tokenData, tokenSize);
  1653. string[tokenSize] = 0;
  1654. UA_Float d = 0;
  1655. #ifdef UA_ENABLE_CUSTOM_LIBC
  1656. d = (UA_Float)__floatscan(string, 1, 0);
  1657. #else
  1658. char c = 0;
  1659. /* On success, the function returns the number of variables filled.
  1660. * In the case of an input failure before any data could be successfully read, EOF is returned. */
  1661. int ret = sscanf(string, "%f%c", &d, &c);
  1662. /* Exactly one var must be filled. %c acts as a guard for wrong input which is accepted by sscanf.
  1663. E.g. 1.23.45 is not accepted. */
  1664. if(ret == EOF || (ret != 1))
  1665. return UA_STATUSCODE_BADDECODINGERROR;
  1666. #endif
  1667. *dst = d;
  1668. parseCtx->index++;
  1669. return UA_STATUSCODE_GOOD;
  1670. }
  1671. /* Either a JSMN_STRING or JSMN_PRIMITIVE */
  1672. DECODE_JSON(Double) {
  1673. CHECK_TOKEN_BOUNDS;
  1674. size_t tokenSize;
  1675. char* tokenData;
  1676. GET_TOKEN(tokenData, tokenSize);
  1677. /* https://www.exploringbinary.com/maximum-number-of-decimal-digits-in-binary-floating-point-numbers/
  1678. * Maximum digit counts for select IEEE floating-point formats: 1074
  1679. * Sanity check.
  1680. */
  1681. if(tokenSize > 1075)
  1682. return UA_STATUSCODE_BADDECODINGERROR;
  1683. jsmntype_t tokenType = getJsmnType(parseCtx);
  1684. if(tokenType == JSMN_STRING) {
  1685. /*It could be a String with Nan, Infinity*/
  1686. if(tokenSize == 8 && memcmp(tokenData, "Infinity", 8) == 0) {
  1687. *dst = INFINITY;
  1688. return UA_STATUSCODE_GOOD;
  1689. }
  1690. if(tokenSize == 9 && memcmp(tokenData, "-Infinity", 9) == 0) {
  1691. /* workaround an MSVC 2013 issue */
  1692. *dst = -INFINITY;
  1693. return UA_STATUSCODE_GOOD;
  1694. }
  1695. if(tokenSize == 3 && memcmp(tokenData, "NaN", 3) == 0) {
  1696. *dst = NAN;
  1697. return UA_STATUSCODE_GOOD;
  1698. }
  1699. if(tokenSize == 4 && memcmp(tokenData, "-NaN", 4) == 0) {
  1700. *dst = NAN;
  1701. return UA_STATUSCODE_GOOD;
  1702. }
  1703. return UA_STATUSCODE_BADDECODINGERROR;
  1704. }
  1705. if(tokenType != JSMN_PRIMITIVE)
  1706. return UA_STATUSCODE_BADDECODINGERROR;
  1707. /* Null-Terminate for sscanf. Should this better be handled on heap? Max
  1708. * 1075 input chars allowed. Not using heap. */
  1709. UA_STACKARRAY(char, string, tokenSize+1);
  1710. memcpy(string, tokenData, tokenSize);
  1711. string[tokenSize] = 0;
  1712. UA_Double d = 0;
  1713. #ifdef UA_ENABLE_CUSTOM_LIBC
  1714. d = (UA_Double)__floatscan(string, 2, 0);
  1715. #else
  1716. char c = 0;
  1717. /* On success, the function returns the number of variables filled.
  1718. * In the case of an input failure before any data could be successfully read, EOF is returned. */
  1719. int ret = sscanf(string, "%lf%c", &d, &c);
  1720. /* Exactly one var must be filled. %c acts as a guard for wrong input which is accepted by sscanf.
  1721. E.g. 1.23.45 is not accepted. */
  1722. if(ret == EOF || (ret != 1))
  1723. return UA_STATUSCODE_BADDECODINGERROR;
  1724. #endif
  1725. *dst = d;
  1726. parseCtx->index++;
  1727. return UA_STATUSCODE_GOOD;
  1728. }
  1729. /*
  1730. Expects 36 chars in format 00000003-0009-000A-0807-060504030201
  1731. | data1| |d2| |d3| |d4| | data4 |
  1732. */
  1733. static UA_Guid UA_Guid_fromChars(const char* chars) {
  1734. UA_Guid dst;
  1735. UA_Guid_init(&dst);
  1736. for(size_t i = 0; i < 8; i++)
  1737. dst.data1 |= (UA_UInt32)(hex2int(chars[i]) << (28 - (i*4)));
  1738. for(size_t i = 0; i < 4; i++) {
  1739. dst.data2 |= (UA_UInt16)(hex2int(chars[9+i]) << (12 - (i*4)));
  1740. dst.data3 |= (UA_UInt16)(hex2int(chars[14+i]) << (12 - (i*4)));
  1741. }
  1742. dst.data4[0] |= (UA_Byte)(hex2int(chars[19]) << 4u);
  1743. dst.data4[0] |= (UA_Byte)(hex2int(chars[20]) << 0u);
  1744. dst.data4[1] |= (UA_Byte)(hex2int(chars[21]) << 4u);
  1745. dst.data4[1] |= (UA_Byte)(hex2int(chars[22]) << 0u);
  1746. for(size_t i = 0; i < 6; i++) {
  1747. dst.data4[2+i] |= (UA_Byte)(hex2int(chars[24 + i*2]) << 4u);
  1748. dst.data4[2+i] |= (UA_Byte)(hex2int(chars[25 + i*2]) << 0u);
  1749. }
  1750. return dst;
  1751. }
  1752. DECODE_JSON(Guid) {
  1753. CHECK_STRING;
  1754. CHECK_TOKEN_BOUNDS;
  1755. size_t tokenSize;
  1756. char* tokenData;
  1757. GET_TOKEN(tokenData, tokenSize);
  1758. if(tokenSize != 36)
  1759. return UA_STATUSCODE_BADDECODINGERROR;
  1760. /* check if incorrect chars are present */
  1761. for(size_t i = 0; i < tokenSize; i++) {
  1762. if(!(tokenData[i] == '-'
  1763. || (tokenData[i] >= '0' && tokenData[i] <= '9')
  1764. || (tokenData[i] >= 'A' && tokenData[i] <= 'F')
  1765. || (tokenData[i] >= 'a' && tokenData[i] <= 'f'))) {
  1766. return UA_STATUSCODE_BADDECODINGERROR;
  1767. }
  1768. }
  1769. *dst = UA_Guid_fromChars(tokenData);
  1770. if(moveToken)
  1771. parseCtx->index++;
  1772. return UA_STATUSCODE_GOOD;
  1773. }
  1774. DECODE_JSON(String) {
  1775. ALLOW_NULL;
  1776. CHECK_STRING;
  1777. CHECK_TOKEN_BOUNDS;
  1778. size_t tokenSize;
  1779. char* tokenData;
  1780. GET_TOKEN(tokenData, tokenSize);
  1781. /* Empty string? */
  1782. if(tokenSize == 0) {
  1783. dst->data = (UA_Byte*)UA_EMPTY_ARRAY_SENTINEL;
  1784. dst->length = 0;
  1785. if(moveToken)
  1786. parseCtx->index++;
  1787. return UA_STATUSCODE_GOOD;
  1788. }
  1789. /* The actual value is at most of the same length as the source string:
  1790. * - Shortcut escapes (e.g. "\t") (length 2) are converted to 1 byte
  1791. * - A single \uXXXX escape (length 6) is converted to at most 3 bytes
  1792. * - Two \uXXXX escapes (length 12) forming an UTF-16 surrogate pair are
  1793. * converted to 4 bytes */
  1794. char *outputBuffer = (char*)UA_malloc(tokenSize);
  1795. if(!outputBuffer)
  1796. return UA_STATUSCODE_BADOUTOFMEMORY;
  1797. const char *p = (char*)tokenData;
  1798. const char *end = (char*)&tokenData[tokenSize];
  1799. char *pos = outputBuffer;
  1800. while(p < end) {
  1801. /* No escaping */
  1802. if(*p != '\\') {
  1803. *(pos++) = *(p++);
  1804. continue;
  1805. }
  1806. /* Escape character */
  1807. p++;
  1808. if(p == end)
  1809. goto cleanup;
  1810. if(*p != 'u') {
  1811. switch(*p) {
  1812. case '"': case '\\': case '/': *pos = *p; break;
  1813. case 'b': *pos = '\b'; break;
  1814. case 'f': *pos = '\f'; break;
  1815. case 'n': *pos = '\n'; break;
  1816. case 'r': *pos = '\r'; break;
  1817. case 't': *pos = '\t'; break;
  1818. default: goto cleanup;
  1819. }
  1820. pos++;
  1821. p++;
  1822. continue;
  1823. }
  1824. /* Unicode */
  1825. if(p + 4 >= end)
  1826. goto cleanup;
  1827. int32_t value_signed = decode_unicode_escape(p);
  1828. if(value_signed < 0)
  1829. goto cleanup;
  1830. uint32_t value = (uint32_t)value_signed;
  1831. p += 5;
  1832. if(0xD800 <= value && value <= 0xDBFF) {
  1833. /* Surrogate pair */
  1834. if(p + 5 >= end)
  1835. goto cleanup;
  1836. if(*p != '\\' || *(p + 1) != 'u')
  1837. goto cleanup;
  1838. int32_t value2 = decode_unicode_escape(p + 1);
  1839. if(value2 < 0xDC00 || value2 > 0xDFFF)
  1840. goto cleanup;
  1841. value = ((value - 0xD800u) << 10u) + (uint32_t)((value2 - 0xDC00) + 0x10000);
  1842. p += 6;
  1843. } else if(0xDC00 <= value && value <= 0xDFFF) {
  1844. /* Invalid Unicode '\\u%04X' */
  1845. goto cleanup;
  1846. }
  1847. size_t length;
  1848. if(utf8_encode((int32_t)value, pos, &length))
  1849. goto cleanup;
  1850. pos += length;
  1851. }
  1852. dst->length = (size_t)(pos - outputBuffer);
  1853. if(dst->length > 0) {
  1854. dst->data = (UA_Byte*)outputBuffer;
  1855. } else {
  1856. dst->data = (UA_Byte*)UA_EMPTY_ARRAY_SENTINEL;
  1857. UA_free(outputBuffer);
  1858. }
  1859. if(moveToken)
  1860. parseCtx->index++;
  1861. return UA_STATUSCODE_GOOD;
  1862. cleanup:
  1863. UA_free(outputBuffer);
  1864. return UA_STATUSCODE_BADDECODINGERROR;
  1865. }
  1866. DECODE_JSON(ByteString) {
  1867. ALLOW_NULL;
  1868. CHECK_STRING;
  1869. CHECK_TOKEN_BOUNDS;
  1870. size_t tokenSize;
  1871. char* tokenData;
  1872. GET_TOKEN(tokenData, tokenSize);
  1873. /* Empty bytestring? */
  1874. if(tokenSize == 0) {
  1875. dst->data = (UA_Byte*)UA_EMPTY_ARRAY_SENTINEL;
  1876. dst->length = 0;
  1877. return UA_STATUSCODE_GOOD;
  1878. }
  1879. int flen;
  1880. unsigned char* unB64 = UA_unbase64(tokenData, (int)tokenSize, &flen);
  1881. if(unB64 == 0)
  1882. return UA_STATUSCODE_BADDECODINGERROR;
  1883. dst->data = (u8*)unB64;
  1884. dst->length = (size_t)flen;
  1885. if(moveToken)
  1886. parseCtx->index++;
  1887. return UA_STATUSCODE_GOOD;
  1888. }
  1889. DECODE_JSON(LocalizedText) {
  1890. ALLOW_NULL;
  1891. CHECK_OBJECT;
  1892. DecodeEntry entries[2] = {
  1893. {UA_JSONKEY_LOCALE, &dst->locale, (decodeJsonSignature) String_decodeJson, false, NULL},
  1894. {UA_JSONKEY_TEXT, &dst->text, (decodeJsonSignature) String_decodeJson, false, NULL}
  1895. };
  1896. return decodeFields(ctx, parseCtx, entries, 2, type);
  1897. }
  1898. DECODE_JSON(QualifiedName) {
  1899. ALLOW_NULL;
  1900. CHECK_OBJECT;
  1901. DecodeEntry entries[2] = {
  1902. {UA_JSONKEY_NAME, &dst->name, (decodeJsonSignature) String_decodeJson, false, NULL},
  1903. {UA_JSONKEY_URI, &dst->namespaceIndex, (decodeJsonSignature) UInt16_decodeJson, false, NULL}
  1904. };
  1905. return decodeFields(ctx, parseCtx, entries, 2, type);
  1906. }
  1907. /* Function for searching ahead of the current token. Used for retrieving the
  1908. * OPC UA type of a token */
  1909. static status
  1910. searchObjectForKeyRec(const char *searchKey, CtxJson *ctx,
  1911. ParseCtx *parseCtx, size_t *resultIndex, UA_UInt16 depth) {
  1912. UA_StatusCode ret = UA_STATUSCODE_BADNOTFOUND;
  1913. CHECK_TOKEN_BOUNDS;
  1914. if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) {
  1915. size_t objectCount = (size_t)(parseCtx->tokenArray[parseCtx->index].size);
  1916. parseCtx->index++; /*Object to first Key*/
  1917. CHECK_TOKEN_BOUNDS;
  1918. size_t i;
  1919. for(i = 0; i < objectCount; i++) {
  1920. CHECK_TOKEN_BOUNDS;
  1921. if(depth == 0) { /* we search only on first layer */
  1922. if(jsoneq((char*)ctx->pos, &parseCtx->tokenArray[parseCtx->index], searchKey) == 0) {
  1923. /*found*/
  1924. parseCtx->index++; /*We give back a pointer to the value of the searched key!*/
  1925. *resultIndex = parseCtx->index;
  1926. ret = UA_STATUSCODE_GOOD;
  1927. break;
  1928. }
  1929. }
  1930. parseCtx->index++; /* value */
  1931. CHECK_TOKEN_BOUNDS;
  1932. if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) {
  1933. ret = searchObjectForKeyRec(searchKey, ctx, parseCtx, resultIndex,
  1934. (UA_UInt16)(depth + 1));
  1935. } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) {
  1936. ret = searchObjectForKeyRec(searchKey, ctx, parseCtx, resultIndex,
  1937. (UA_UInt16)(depth + 1));
  1938. } else {
  1939. /* Only Primitive or string */
  1940. parseCtx->index++;
  1941. }
  1942. }
  1943. } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) {
  1944. size_t arraySize = (size_t)(parseCtx->tokenArray[parseCtx->index].size);
  1945. parseCtx->index++; /*Object to first element*/
  1946. CHECK_TOKEN_BOUNDS;
  1947. size_t i;
  1948. for(i = 0; i < arraySize; i++) {
  1949. if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) {
  1950. ret = searchObjectForKeyRec(searchKey, ctx, parseCtx, resultIndex,
  1951. (UA_UInt16)(depth + 1));
  1952. } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) {
  1953. ret = searchObjectForKeyRec(searchKey, ctx, parseCtx, resultIndex,
  1954. (UA_UInt16)(depth + 1));
  1955. } else {
  1956. /* Only Primitive or string */
  1957. parseCtx->index++;
  1958. }
  1959. }
  1960. }
  1961. return ret;
  1962. }
  1963. UA_FUNC_ATTR_WARN_UNUSED_RESULT status
  1964. lookAheadForKey(const char* search, CtxJson *ctx,
  1965. ParseCtx *parseCtx, size_t *resultIndex) {
  1966. UA_UInt16 oldIndex = parseCtx->index; /* Save index for later restore */
  1967. UA_UInt16 depth = 0;
  1968. UA_StatusCode ret = searchObjectForKeyRec(search, ctx, parseCtx, resultIndex, depth);
  1969. parseCtx->index = oldIndex; /* Restore index */
  1970. return ret;
  1971. }
  1972. /* Function used to jump over an object which cannot be parsed */
  1973. static status
  1974. jumpOverRec(CtxJson *ctx, ParseCtx *parseCtx,
  1975. size_t *resultIndex, UA_UInt16 depth) {
  1976. UA_StatusCode ret = UA_STATUSCODE_BADDECODINGERROR;
  1977. CHECK_TOKEN_BOUNDS;
  1978. if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) {
  1979. size_t objectCount = (size_t)(parseCtx->tokenArray[parseCtx->index].size);
  1980. parseCtx->index++; /*Object to first Key*/
  1981. CHECK_TOKEN_BOUNDS;
  1982. size_t i;
  1983. for(i = 0; i < objectCount; i++) {
  1984. CHECK_TOKEN_BOUNDS;
  1985. parseCtx->index++; /*value*/
  1986. CHECK_TOKEN_BOUNDS;
  1987. if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) {
  1988. jumpOverRec(ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1));
  1989. } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) {
  1990. jumpOverRec(ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1));
  1991. } else {
  1992. /*Only Primitive or string*/
  1993. parseCtx->index++;
  1994. }
  1995. }
  1996. } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) {
  1997. size_t arraySize = (size_t)(parseCtx->tokenArray[parseCtx->index].size);
  1998. parseCtx->index++; /*Object to first element*/
  1999. CHECK_TOKEN_BOUNDS;
  2000. size_t i;
  2001. for(i = 0; i < arraySize; i++) {
  2002. if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) {
  2003. jumpOverRec(ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1));
  2004. } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) {
  2005. jumpOverRec(ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1));
  2006. } else {
  2007. /*Only Primitive or string*/
  2008. parseCtx->index++;
  2009. }
  2010. }
  2011. }
  2012. return ret;
  2013. }
  2014. static status
  2015. jumpOverObject(CtxJson *ctx, ParseCtx *parseCtx, size_t *resultIndex) {
  2016. UA_UInt16 oldIndex = parseCtx->index; /* Save index for later restore */
  2017. UA_UInt16 depth = 0;
  2018. jumpOverRec(ctx, parseCtx, resultIndex, depth);
  2019. *resultIndex = parseCtx->index;
  2020. parseCtx->index = oldIndex; /* Restore index */
  2021. return UA_STATUSCODE_GOOD;
  2022. }
  2023. static status
  2024. prepareDecodeNodeIdJson(UA_NodeId *dst, CtxJson *ctx, ParseCtx *parseCtx,
  2025. u8 *fieldCount, DecodeEntry *entries) {
  2026. /* possible keys: Id, IdType*/
  2027. /* Id must always be present */
  2028. entries[*fieldCount].fieldName = UA_JSONKEY_ID;
  2029. entries[*fieldCount].found = false;
  2030. entries[*fieldCount].type = NULL;
  2031. /* IdType */
  2032. UA_Boolean hasIdType = false;
  2033. size_t searchResult = 0;
  2034. status ret = lookAheadForKey(UA_JSONKEY_IDTYPE, ctx, parseCtx, &searchResult);
  2035. if(ret == UA_STATUSCODE_GOOD) { /*found*/
  2036. hasIdType = true;
  2037. }
  2038. if(hasIdType) {
  2039. size_t size = (size_t)(parseCtx->tokenArray[searchResult].end -
  2040. parseCtx->tokenArray[searchResult].start);
  2041. if(size < 1) {
  2042. return UA_STATUSCODE_BADDECODINGERROR;
  2043. }
  2044. char *idType = (char*)(ctx->pos + parseCtx->tokenArray[searchResult].start);
  2045. if(idType[0] == '2') {
  2046. dst->identifierType = UA_NODEIDTYPE_GUID;
  2047. entries[*fieldCount].fieldPointer = &dst->identifier.guid;
  2048. entries[*fieldCount].function = (decodeJsonSignature) Guid_decodeJson;
  2049. } else if(idType[0] == '1') {
  2050. dst->identifierType = UA_NODEIDTYPE_STRING;
  2051. entries[*fieldCount].fieldPointer = &dst->identifier.string;
  2052. entries[*fieldCount].function = (decodeJsonSignature) String_decodeJson;
  2053. } else if(idType[0] == '3') {
  2054. dst->identifierType = UA_NODEIDTYPE_BYTESTRING;
  2055. entries[*fieldCount].fieldPointer = &dst->identifier.byteString;
  2056. entries[*fieldCount].function = (decodeJsonSignature) ByteString_decodeJson;
  2057. } else {
  2058. return UA_STATUSCODE_BADDECODINGERROR;
  2059. }
  2060. /* Id always present */
  2061. (*fieldCount)++;
  2062. entries[*fieldCount].fieldName = UA_JSONKEY_IDTYPE;
  2063. entries[*fieldCount].fieldPointer = NULL;
  2064. entries[*fieldCount].function = NULL;
  2065. entries[*fieldCount].found = false;
  2066. entries[*fieldCount].type = NULL;
  2067. /* IdType */
  2068. (*fieldCount)++;
  2069. } else {
  2070. dst->identifierType = UA_NODEIDTYPE_NUMERIC;
  2071. entries[*fieldCount].fieldPointer = &dst->identifier.numeric;
  2072. entries[*fieldCount].function = (decodeJsonSignature) UInt32_decodeJson;
  2073. entries[*fieldCount].type = NULL;
  2074. (*fieldCount)++;
  2075. }
  2076. return UA_STATUSCODE_GOOD;
  2077. }
  2078. DECODE_JSON(NodeId) {
  2079. ALLOW_NULL;
  2080. CHECK_OBJECT;
  2081. /* NameSpace */
  2082. UA_Boolean hasNamespace = false;
  2083. size_t searchResultNamespace = 0;
  2084. status ret = lookAheadForKey(UA_JSONKEY_NAMESPACE, ctx, parseCtx, &searchResultNamespace);
  2085. if(ret != UA_STATUSCODE_GOOD) {
  2086. dst->namespaceIndex = 0;
  2087. } else {
  2088. hasNamespace = true;
  2089. }
  2090. /* Keep track over number of keys present, incremented if key found */
  2091. u8 fieldCount = 0;
  2092. DecodeEntry entries[3];
  2093. ret = prepareDecodeNodeIdJson(dst, ctx, parseCtx, &fieldCount, entries);
  2094. if(ret != UA_STATUSCODE_GOOD)
  2095. return ret;
  2096. if(hasNamespace) {
  2097. entries[fieldCount].fieldName = UA_JSONKEY_NAMESPACE;
  2098. entries[fieldCount].fieldPointer = &dst->namespaceIndex;
  2099. entries[fieldCount].function = (decodeJsonSignature) UInt16_decodeJson;
  2100. entries[fieldCount].found = false;
  2101. entries[fieldCount].type = NULL;
  2102. fieldCount++;
  2103. } else {
  2104. dst->namespaceIndex = 0;
  2105. }
  2106. ret = decodeFields(ctx, parseCtx, entries, fieldCount, type);
  2107. return ret;
  2108. }
  2109. DECODE_JSON(ExpandedNodeId) {
  2110. ALLOW_NULL;
  2111. CHECK_OBJECT;
  2112. /* Keep track over number of keys present, incremented if key found */
  2113. u8 fieldCount = 0;
  2114. /* ServerUri */
  2115. UA_Boolean hasServerUri = false;
  2116. size_t searchResultServerUri = 0;
  2117. status ret = lookAheadForKey(UA_JSONKEY_SERVERURI, ctx, parseCtx, &searchResultServerUri);
  2118. if(ret != UA_STATUSCODE_GOOD) {
  2119. dst->serverIndex = 0;
  2120. } else {
  2121. hasServerUri = true;
  2122. }
  2123. /* NameSpace */
  2124. UA_Boolean hasNamespace = false;
  2125. UA_Boolean isNamespaceString = false;
  2126. size_t searchResultNamespace = 0;
  2127. ret = lookAheadForKey(UA_JSONKEY_NAMESPACE, ctx, parseCtx, &searchResultNamespace);
  2128. if(ret != UA_STATUSCODE_GOOD) {
  2129. dst->namespaceUri = UA_STRING_NULL;
  2130. } else {
  2131. hasNamespace = true;
  2132. jsmntok_t nsToken = parseCtx->tokenArray[searchResultNamespace];
  2133. if(nsToken.type == JSMN_STRING)
  2134. isNamespaceString = true;
  2135. }
  2136. DecodeEntry entries[4];
  2137. ret = prepareDecodeNodeIdJson(&dst->nodeId, ctx, parseCtx, &fieldCount, entries);
  2138. if(ret != UA_STATUSCODE_GOOD)
  2139. return ret;
  2140. if(hasNamespace) {
  2141. entries[fieldCount].fieldName = UA_JSONKEY_NAMESPACE;
  2142. if(isNamespaceString) {
  2143. entries[fieldCount].fieldPointer = &dst->namespaceUri;
  2144. entries[fieldCount].function = (decodeJsonSignature) String_decodeJson;
  2145. } else {
  2146. entries[fieldCount].fieldPointer = &dst->nodeId.namespaceIndex;
  2147. entries[fieldCount].function = (decodeJsonSignature) UInt16_decodeJson;
  2148. }
  2149. entries[fieldCount].found = false;
  2150. entries[fieldCount].type = NULL;
  2151. fieldCount++;
  2152. }
  2153. if(hasServerUri) {
  2154. entries[fieldCount].fieldName = UA_JSONKEY_SERVERURI;
  2155. entries[fieldCount].fieldPointer = &dst->serverIndex;
  2156. entries[fieldCount].function = (decodeJsonSignature) UInt32_decodeJson;
  2157. entries[fieldCount].found = false;
  2158. entries[fieldCount].type = NULL;
  2159. fieldCount++;
  2160. } else {
  2161. dst->serverIndex = 0;
  2162. }
  2163. return decodeFields(ctx, parseCtx, entries, fieldCount, type);
  2164. }
  2165. DECODE_JSON(DateTime) {
  2166. CHECK_STRING;
  2167. CHECK_TOKEN_BOUNDS;
  2168. size_t tokenSize;
  2169. char* tokenData;
  2170. GET_TOKEN(tokenData, tokenSize);
  2171. /* TODO: proper ISO 8601:2004 parsing, musl strptime!*/
  2172. /* DateTime ISO 8601:2004 without milli is 20 Characters, with millis 24 */
  2173. if(tokenSize != 20 && tokenSize != 24) {
  2174. return UA_STATUSCODE_BADDECODINGERROR;
  2175. }
  2176. /* sanity check */
  2177. if(tokenData[4] != '-' || tokenData[7] != '-' || tokenData[10] != 'T' ||
  2178. tokenData[13] != ':' || tokenData[16] != ':' ||
  2179. !(tokenData[19] == 'Z' || tokenData[19] == '.')) {
  2180. return UA_STATUSCODE_BADDECODINGERROR;
  2181. }
  2182. struct mytm dts;
  2183. memset(&dts, 0, sizeof(dts));
  2184. UA_UInt64 year = 0;
  2185. atoiUnsigned(&tokenData[0], 4, &year);
  2186. dts.tm_year = (UA_UInt16)year - 1900;
  2187. UA_UInt64 month = 0;
  2188. atoiUnsigned(&tokenData[5], 2, &month);
  2189. dts.tm_mon = (UA_UInt16)month - 1;
  2190. UA_UInt64 day = 0;
  2191. atoiUnsigned(&tokenData[8], 2, &day);
  2192. dts.tm_mday = (UA_UInt16)day;
  2193. UA_UInt64 hour = 0;
  2194. atoiUnsigned(&tokenData[11], 2, &hour);
  2195. dts.tm_hour = (UA_UInt16)hour;
  2196. UA_UInt64 min = 0;
  2197. atoiUnsigned(&tokenData[14], 2, &min);
  2198. dts.tm_min = (UA_UInt16)min;
  2199. UA_UInt64 sec = 0;
  2200. atoiUnsigned(&tokenData[17], 2, &sec);
  2201. dts.tm_sec = (UA_UInt16)sec;
  2202. UA_UInt64 msec = 0;
  2203. if(tokenSize == 24) {
  2204. atoiUnsigned(&tokenData[20], 3, &msec);
  2205. }
  2206. long long sinceunix = __tm_to_secs(&dts);
  2207. UA_DateTime dt = (UA_DateTime)((UA_UInt64)(sinceunix*UA_DATETIME_SEC +
  2208. UA_DATETIME_UNIX_EPOCH) +
  2209. (UA_UInt64)(UA_DATETIME_MSEC * msec));
  2210. *dst = dt;
  2211. if(moveToken)
  2212. parseCtx->index++;
  2213. return UA_STATUSCODE_GOOD;
  2214. }
  2215. DECODE_JSON(StatusCode) {
  2216. status ret = DECODE_DIRECT_JSON(dst, UInt32);
  2217. if(ret != UA_STATUSCODE_GOOD)
  2218. return ret;
  2219. if(moveToken)
  2220. parseCtx->index++;
  2221. return UA_STATUSCODE_GOOD;
  2222. }
  2223. static status
  2224. VariantDimension_decodeJson(void * dst, const UA_DataType *type,
  2225. CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) {
  2226. (void) type;
  2227. const UA_DataType *dimType = &UA_TYPES[UA_TYPES_UINT32];
  2228. return Array_decodeJson_internal((void**)dst, dimType, ctx, parseCtx, moveToken);
  2229. }
  2230. DECODE_JSON(Variant) {
  2231. ALLOW_NULL;
  2232. CHECK_OBJECT;
  2233. /* First search for the variant type in the json object. */
  2234. size_t searchResultType = 0;
  2235. status ret = lookAheadForKey(UA_JSONKEY_TYPE, ctx, parseCtx, &searchResultType);
  2236. if(ret != UA_STATUSCODE_GOOD)
  2237. return UA_STATUSCODE_BADDECODINGERROR;
  2238. size_t size = (size_t)(parseCtx->tokenArray[searchResultType].end - parseCtx->tokenArray[searchResultType].start);
  2239. /* check if size is zero or the type is not a number */
  2240. if(size < 1 || parseCtx->tokenArray[searchResultType].type != JSMN_PRIMITIVE) {
  2241. return UA_STATUSCODE_BADDECODINGERROR;
  2242. }
  2243. /*Parse the type*/
  2244. UA_UInt64 idTypeDecoded = 0;
  2245. char *idTypeEncoded = (char*)(ctx->pos + parseCtx->tokenArray[searchResultType].start);
  2246. status typeDecodeStatus = atoiUnsigned(idTypeEncoded, size, &idTypeDecoded);
  2247. /* value is not a valid number */
  2248. if(typeDecodeStatus != UA_STATUSCODE_GOOD) {
  2249. return typeDecodeStatus;
  2250. }
  2251. /*Set the type, Get the Type by nodeID!*/
  2252. UA_NodeId typeNodeId = UA_NODEID_NUMERIC(0, (UA_UInt32)idTypeDecoded);
  2253. const UA_DataType *bodyType = UA_findDataType(&typeNodeId);
  2254. if(bodyType == NULL) {
  2255. return UA_STATUSCODE_BADDECODINGERROR;
  2256. }
  2257. /*Set the type*/
  2258. dst->type = bodyType;
  2259. /* LookAhead BODY */
  2260. /* Does the variant contain an array? */
  2261. UA_Boolean isArray = false;
  2262. UA_Boolean isBodyNull = false;
  2263. /* Search for body */
  2264. size_t searchResultBody = 0;
  2265. ret = lookAheadForKey(UA_JSONKEY_BODY, ctx, parseCtx, &searchResultBody);
  2266. if(ret == UA_STATUSCODE_GOOD) { /* body found */
  2267. /* get body token */
  2268. jsmntok_t bodyToken = parseCtx->tokenArray[searchResultBody];
  2269. /*BODY is null?*/
  2270. if(isJsonTokenNull(ctx, &bodyToken)) {
  2271. dst->data = NULL;
  2272. isBodyNull = true;
  2273. }
  2274. if(bodyToken.type == JSMN_ARRAY) {
  2275. isArray = true;
  2276. size_t arraySize = 0;
  2277. arraySize = (size_t)parseCtx->tokenArray[searchResultBody].size;
  2278. dst->arrayLength = arraySize;
  2279. }
  2280. } else {
  2281. /*TODO: no body? set value NULL?*/
  2282. return UA_STATUSCODE_BADDECODINGERROR;
  2283. }
  2284. /* LookAhead DIMENSION */
  2285. UA_Boolean hasDimension = false;
  2286. /* Has the variant dimension? */
  2287. size_t searchResultDim = 0;
  2288. ret = lookAheadForKey(UA_JSONKEY_DIMENSION, ctx, parseCtx, &searchResultDim);
  2289. if(ret == UA_STATUSCODE_GOOD) {
  2290. hasDimension = true;
  2291. size_t dimensionSize = 0;
  2292. dimensionSize = (size_t)parseCtx->tokenArray[searchResultDim].size;
  2293. dst->arrayDimensionsSize = dimensionSize;
  2294. }
  2295. /* no array but has dimension. error? */
  2296. if(!isArray && hasDimension)
  2297. return UA_STATUSCODE_BADDECODINGERROR;
  2298. /* Get the datatype of the content. The type must be a builtin data type.
  2299. * All not-builtin types are wrapped in an ExtensionObject. */
  2300. if(bodyType->typeKind > UA_TYPES_DIAGNOSTICINFO)
  2301. return UA_STATUSCODE_BADDECODINGERROR;
  2302. /* A variant cannot contain a variant. But it can contain an array of
  2303. * variants */
  2304. if(bodyType->typeKind == UA_DATATYPEKIND_VARIANT && !isArray)
  2305. return UA_STATUSCODE_BADDECODINGERROR;
  2306. if(isArray) {
  2307. DecodeEntry entries[3] = {
  2308. {UA_JSONKEY_TYPE, NULL, NULL, false, NULL},
  2309. {UA_JSONKEY_BODY, &dst->data, (decodeJsonSignature) Array_decodeJson, false, NULL},
  2310. {UA_JSONKEY_DIMENSION, &dst->arrayDimensions,
  2311. (decodeJsonSignature) VariantDimension_decodeJson, false, NULL}};
  2312. if(!hasDimension) {
  2313. ret = decodeFields(ctx, parseCtx, entries, 2, bodyType); /*use first 2 fields*/
  2314. } else {
  2315. ret = decodeFields(ctx, parseCtx, entries, 3, bodyType); /*use all fields*/
  2316. }
  2317. } else if(bodyType->typeKind != UA_DATATYPEKIND_EXTENSIONOBJECT) {
  2318. /* Allocate Memory for Body */
  2319. if(!isBodyNull) {
  2320. dst->data = UA_new(bodyType);
  2321. if(!dst->data)
  2322. return UA_STATUSCODE_BADOUTOFMEMORY;
  2323. }
  2324. DecodeEntry entries[2] = {{UA_JSONKEY_TYPE, NULL, NULL, false, NULL},
  2325. {UA_JSONKEY_BODY, dst->data, (decodeJsonSignature) decodeJsonInternal, false, NULL}};
  2326. ret = decodeFields(ctx, parseCtx, entries, 2, bodyType);
  2327. } else { /* extensionObject */
  2328. DecodeEntry entries[2] = {{UA_JSONKEY_TYPE, NULL, NULL, false, NULL},
  2329. {UA_JSONKEY_BODY, dst,
  2330. (decodeJsonSignature) Variant_decodeJsonUnwrapExtensionObject, false, NULL}};
  2331. ret = decodeFields(ctx, parseCtx, entries, 2, bodyType);
  2332. }
  2333. return ret;
  2334. }
  2335. DECODE_JSON(DataValue) {
  2336. ALLOW_NULL;
  2337. CHECK_OBJECT;
  2338. DecodeEntry entries[6] = {
  2339. {UA_JSONKEY_VALUE, &dst->value, (decodeJsonSignature) Variant_decodeJson, false, NULL},
  2340. {UA_JSONKEY_STATUS, &dst->status, (decodeJsonSignature) StatusCode_decodeJson, false, NULL},
  2341. {UA_JSONKEY_SOURCETIMESTAMP, &dst->sourceTimestamp, (decodeJsonSignature) DateTime_decodeJson, false, NULL},
  2342. {UA_JSONKEY_SOURCEPICOSECONDS, &dst->sourcePicoseconds, (decodeJsonSignature) UInt16_decodeJson, false, NULL},
  2343. {UA_JSONKEY_SERVERTIMESTAMP, &dst->serverTimestamp, (decodeJsonSignature) DateTime_decodeJson, false, NULL},
  2344. {UA_JSONKEY_SERVERPICOSECONDS, &dst->serverPicoseconds, (decodeJsonSignature) UInt16_decodeJson, false, NULL}};
  2345. status ret = decodeFields(ctx, parseCtx, entries, 6, type);
  2346. dst->hasValue = entries[0].found; dst->hasStatus = entries[1].found;
  2347. dst->hasSourceTimestamp = entries[2].found; dst->hasSourcePicoseconds = entries[3].found;
  2348. dst->hasServerTimestamp = entries[4].found; dst->hasServerPicoseconds = entries[5].found;
  2349. return ret;
  2350. }
  2351. DECODE_JSON(ExtensionObject) {
  2352. ALLOW_NULL;
  2353. CHECK_OBJECT;
  2354. /* Search for Encoding */
  2355. size_t searchEncodingResult = 0;
  2356. status ret = lookAheadForKey(UA_JSONKEY_ENCODING, ctx, parseCtx, &searchEncodingResult);
  2357. /* If no encoding found it is structure encoding */
  2358. if(ret != UA_STATUSCODE_GOOD) {
  2359. UA_NodeId typeId;
  2360. UA_NodeId_init(&typeId);
  2361. size_t searchTypeIdResult = 0;
  2362. ret = lookAheadForKey(UA_JSONKEY_TYPEID, ctx, parseCtx, &searchTypeIdResult);
  2363. if(ret != UA_STATUSCODE_GOOD) {
  2364. /* TYPEID not found, abort */
  2365. return UA_STATUSCODE_BADENCODINGERROR;
  2366. }
  2367. /* parse the nodeid */
  2368. /*for restore*/
  2369. UA_UInt16 index = parseCtx->index;
  2370. parseCtx->index = (UA_UInt16)searchTypeIdResult;
  2371. ret = NodeId_decodeJson(&typeId, &UA_TYPES[UA_TYPES_NODEID], ctx, parseCtx, true);
  2372. if(ret != UA_STATUSCODE_GOOD)
  2373. return ret;
  2374. /*restore*/
  2375. parseCtx->index = index;
  2376. const UA_DataType *typeOfBody = UA_findDataType(&typeId);
  2377. if(!typeOfBody) {
  2378. /*dont decode body: 1. save as bytestring, 2. jump over*/
  2379. dst->encoding = UA_EXTENSIONOBJECT_ENCODED_BYTESTRING;
  2380. UA_NodeId_copy(&typeId, &dst->content.encoded.typeId);
  2381. /*Check if Object in Extentionobject*/
  2382. if(getJsmnType(parseCtx) != JSMN_OBJECT) {
  2383. UA_NodeId_deleteMembers(&typeId);
  2384. return UA_STATUSCODE_BADDECODINGERROR;
  2385. }
  2386. /*Search for Body to save*/
  2387. size_t searchBodyResult = 0;
  2388. ret = lookAheadForKey(UA_JSONKEY_BODY, ctx, parseCtx, &searchBodyResult);
  2389. if(ret != UA_STATUSCODE_GOOD) {
  2390. /*No Body*/
  2391. UA_NodeId_deleteMembers(&typeId);
  2392. return UA_STATUSCODE_BADDECODINGERROR;
  2393. }
  2394. if(searchBodyResult >= (size_t)parseCtx->tokenCount) {
  2395. /*index not in Tokenarray*/
  2396. UA_NodeId_deleteMembers(&typeId);
  2397. return UA_STATUSCODE_BADDECODINGERROR;
  2398. }
  2399. /* Get the size of the Object as a string, not the Object key count! */
  2400. UA_Int64 sizeOfJsonString =(parseCtx->tokenArray[searchBodyResult].end -
  2401. parseCtx->tokenArray[searchBodyResult].start);
  2402. char* bodyJsonString = (char*)(ctx->pos + parseCtx->tokenArray[searchBodyResult].start);
  2403. if(sizeOfJsonString <= 0) {
  2404. UA_NodeId_deleteMembers(&typeId);
  2405. return UA_STATUSCODE_BADDECODINGERROR;
  2406. }
  2407. /* Save encoded as bytestring. */
  2408. ret = UA_ByteString_allocBuffer(&dst->content.encoded.body, (size_t)sizeOfJsonString);
  2409. if(ret != UA_STATUSCODE_GOOD) {
  2410. UA_NodeId_deleteMembers(&typeId);
  2411. return ret;
  2412. }
  2413. memcpy(dst->content.encoded.body.data, bodyJsonString, (size_t)sizeOfJsonString);
  2414. size_t tokenAfteExtensionObject = 0;
  2415. jumpOverObject(ctx, parseCtx, &tokenAfteExtensionObject);
  2416. if(tokenAfteExtensionObject == 0) {
  2417. /*next object token not found*/
  2418. UA_NodeId_deleteMembers(&typeId);
  2419. UA_ByteString_deleteMembers(&dst->content.encoded.body);
  2420. return UA_STATUSCODE_BADDECODINGERROR;
  2421. }
  2422. parseCtx->index = (UA_UInt16)tokenAfteExtensionObject;
  2423. return UA_STATUSCODE_GOOD;
  2424. }
  2425. /*Type id not used anymore, typeOfBody has type*/
  2426. UA_NodeId_deleteMembers(&typeId);
  2427. /*Set Found Type*/
  2428. dst->content.decoded.type = typeOfBody;
  2429. dst->encoding = UA_EXTENSIONOBJECT_DECODED;
  2430. if(searchTypeIdResult != 0) {
  2431. dst->content.decoded.data = UA_new(typeOfBody);
  2432. if(!dst->content.decoded.data)
  2433. return UA_STATUSCODE_BADOUTOFMEMORY;
  2434. UA_NodeId typeId_dummy;
  2435. DecodeEntry entries[2] = {
  2436. {UA_JSONKEY_TYPEID, &typeId_dummy, (decodeJsonSignature) NodeId_decodeJson, false, NULL},
  2437. {UA_JSONKEY_BODY, dst->content.decoded.data,
  2438. (decodeJsonSignature) decodeJsonJumpTable[typeOfBody->typeKind], false, NULL}
  2439. };
  2440. return decodeFields(ctx, parseCtx, entries, 2, typeOfBody);
  2441. } else {
  2442. return UA_STATUSCODE_BADDECODINGERROR;
  2443. }
  2444. } else { /* UA_JSONKEY_ENCODING found */
  2445. /*Parse the encoding*/
  2446. UA_UInt64 encoding = 0;
  2447. char *extObjEncoding = (char*)(ctx->pos + parseCtx->tokenArray[searchEncodingResult].start);
  2448. size_t size = (size_t)(parseCtx->tokenArray[searchEncodingResult].end - parseCtx->tokenArray[searchEncodingResult].start);
  2449. atoiUnsigned(extObjEncoding, size, &encoding);
  2450. if(encoding == 1) {
  2451. /* BYTESTRING in Json Body */
  2452. dst->encoding = UA_EXTENSIONOBJECT_ENCODED_BYTESTRING;
  2453. UA_UInt16 encodingTypeJson;
  2454. DecodeEntry entries[3] = {
  2455. {UA_JSONKEY_ENCODING, &encodingTypeJson, (decodeJsonSignature) UInt16_decodeJson, false, NULL},
  2456. {UA_JSONKEY_BODY, &dst->content.encoded.body, (decodeJsonSignature) String_decodeJson, false, NULL},
  2457. {UA_JSONKEY_TYPEID, &dst->content.encoded.typeId, (decodeJsonSignature) NodeId_decodeJson, false, NULL}
  2458. };
  2459. return decodeFields(ctx, parseCtx, entries, 3, type);
  2460. } else if(encoding == 2) {
  2461. /* XmlElement in Json Body */
  2462. dst->encoding = UA_EXTENSIONOBJECT_ENCODED_XML;
  2463. UA_UInt16 encodingTypeJson;
  2464. DecodeEntry entries[3] = {
  2465. {UA_JSONKEY_ENCODING, &encodingTypeJson, (decodeJsonSignature) UInt16_decodeJson, false, NULL},
  2466. {UA_JSONKEY_BODY, &dst->content.encoded.body, (decodeJsonSignature) String_decodeJson, false, NULL},
  2467. {UA_JSONKEY_TYPEID, &dst->content.encoded.typeId, (decodeJsonSignature) NodeId_decodeJson, false, NULL}
  2468. };
  2469. return decodeFields(ctx, parseCtx, entries, 3, type);
  2470. } else {
  2471. return UA_STATUSCODE_BADDECODINGERROR;
  2472. }
  2473. }
  2474. return UA_STATUSCODE_BADNOTIMPLEMENTED;
  2475. }
  2476. static status
  2477. Variant_decodeJsonUnwrapExtensionObject(UA_Variant *dst, const UA_DataType *type,
  2478. CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) {
  2479. (void) type, (void) moveToken;
  2480. /*EXTENSIONOBJECT POSITION!*/
  2481. UA_UInt16 old_index = parseCtx->index;
  2482. UA_Boolean typeIdFound;
  2483. /* Decode the DataType */
  2484. UA_NodeId typeId;
  2485. UA_NodeId_init(&typeId);
  2486. size_t searchTypeIdResult = 0;
  2487. status ret = lookAheadForKey(UA_JSONKEY_TYPEID, ctx, parseCtx, &searchTypeIdResult);
  2488. if(ret != UA_STATUSCODE_GOOD) {
  2489. /*No Typeid found*/
  2490. typeIdFound = false;
  2491. /*return UA_STATUSCODE_BADDECODINGERROR;*/
  2492. } else {
  2493. typeIdFound = true;
  2494. /* parse the nodeid */
  2495. parseCtx->index = (UA_UInt16)searchTypeIdResult;
  2496. ret = NodeId_decodeJson(&typeId, &UA_TYPES[UA_TYPES_NODEID], ctx, parseCtx, true);
  2497. if(ret != UA_STATUSCODE_GOOD) {
  2498. UA_NodeId_deleteMembers(&typeId);
  2499. return ret;
  2500. }
  2501. /*restore index, ExtensionObject position*/
  2502. parseCtx->index = old_index;
  2503. }
  2504. /* ---Decode the EncodingByte--- */
  2505. if(!typeIdFound)
  2506. return UA_STATUSCODE_BADDECODINGERROR;
  2507. UA_Boolean encodingFound = false;
  2508. /*Search for Encoding*/
  2509. size_t searchEncodingResult = 0;
  2510. ret = lookAheadForKey(UA_JSONKEY_ENCODING, ctx, parseCtx, &searchEncodingResult);
  2511. UA_UInt64 encoding = 0;
  2512. /*If no encoding found it is Structure encoding*/
  2513. if(ret == UA_STATUSCODE_GOOD) { /*FOUND*/
  2514. encodingFound = true;
  2515. char *extObjEncoding = (char*)(ctx->pos + parseCtx->tokenArray[searchEncodingResult].start);
  2516. size_t size = (size_t)(parseCtx->tokenArray[searchEncodingResult].end
  2517. - parseCtx->tokenArray[searchEncodingResult].start);
  2518. atoiUnsigned(extObjEncoding, size, &encoding);
  2519. }
  2520. const UA_DataType *typeOfBody = UA_findDataType(&typeId);
  2521. if(encoding == 0 || typeOfBody != NULL) {
  2522. /*This value is 0 if the body is Structure encoded as a JSON object (see 5.4.6).*/
  2523. /* Found a valid type and it is structure encoded so it can be unwrapped */
  2524. dst->type = typeOfBody;
  2525. /* Allocate memory for type*/
  2526. dst->data = UA_new(dst->type);
  2527. if(!dst->data) {
  2528. UA_NodeId_deleteMembers(&typeId);
  2529. return UA_STATUSCODE_BADOUTOFMEMORY;
  2530. }
  2531. /* Decode the content */
  2532. UA_NodeId nodeIddummy;
  2533. DecodeEntry entries[3] =
  2534. {
  2535. {UA_JSONKEY_TYPEID, &nodeIddummy, (decodeJsonSignature) NodeId_decodeJson, false, NULL},
  2536. {UA_JSONKEY_BODY, dst->data,
  2537. (decodeJsonSignature) decodeJsonJumpTable[dst->type->typeKind], false, NULL},
  2538. {UA_JSONKEY_ENCODING, NULL, NULL, false, NULL}};
  2539. ret = decodeFields(ctx, parseCtx, entries, encodingFound ? 3:2, typeOfBody);
  2540. if(ret != UA_STATUSCODE_GOOD) {
  2541. UA_free(dst->data);
  2542. }
  2543. } else if(encoding == 1 || encoding == 2 || typeOfBody == NULL) {
  2544. UA_NodeId_deleteMembers(&typeId);
  2545. /* decode as ExtensionObject */
  2546. dst->type = &UA_TYPES[UA_TYPES_EXTENSIONOBJECT];
  2547. /* Allocate memory for extensionobject*/
  2548. dst->data = UA_new(dst->type);
  2549. if(!dst->data)
  2550. return UA_STATUSCODE_BADOUTOFMEMORY;
  2551. /* decode: Does not move tokenindex. */
  2552. ret = DECODE_DIRECT_JSON(dst->data, ExtensionObject);
  2553. if(ret != UA_STATUSCODE_GOOD)
  2554. UA_free(dst->data);
  2555. } else {
  2556. /*no recognized encoding type*/
  2557. return UA_STATUSCODE_BADDECODINGERROR;
  2558. }
  2559. return ret;
  2560. }
  2561. status DiagnosticInfoInner_decodeJson(void* dst, const UA_DataType* type,
  2562. CtxJson* ctx, ParseCtx* parseCtx, UA_Boolean moveToken);
  2563. DECODE_JSON(DiagnosticInfo) {
  2564. ALLOW_NULL;
  2565. CHECK_OBJECT;
  2566. DecodeEntry entries[7] = {
  2567. {UA_JSONKEY_SYMBOLICID, &dst->symbolicId, (decodeJsonSignature) Int32_decodeJson, false, NULL},
  2568. {UA_JSONKEY_NAMESPACEURI, &dst->namespaceUri, (decodeJsonSignature) Int32_decodeJson, false, NULL},
  2569. {UA_JSONKEY_LOCALIZEDTEXT, &dst->localizedText, (decodeJsonSignature) Int32_decodeJson, false, NULL},
  2570. {UA_JSONKEY_LOCALE, &dst->locale, (decodeJsonSignature) Int32_decodeJson, false, NULL},
  2571. {UA_JSONKEY_ADDITIONALINFO, &dst->additionalInfo, (decodeJsonSignature) String_decodeJson, false, NULL},
  2572. {UA_JSONKEY_INNERSTATUSCODE, &dst->innerStatusCode, (decodeJsonSignature) StatusCode_decodeJson, false, NULL},
  2573. {UA_JSONKEY_INNERDIAGNOSTICINFO, &dst->innerDiagnosticInfo, (decodeJsonSignature) DiagnosticInfoInner_decodeJson, false, NULL}};
  2574. status ret = decodeFields(ctx, parseCtx, entries, 7, type);
  2575. dst->hasSymbolicId = entries[0].found; dst->hasNamespaceUri = entries[1].found;
  2576. dst->hasLocalizedText = entries[2].found; dst->hasLocale = entries[3].found;
  2577. dst->hasAdditionalInfo = entries[4].found; dst->hasInnerStatusCode = entries[5].found;
  2578. dst->hasInnerDiagnosticInfo = entries[6].found;
  2579. return ret;
  2580. }
  2581. status
  2582. DiagnosticInfoInner_decodeJson(void* dst, const UA_DataType* type,
  2583. CtxJson* ctx, ParseCtx* parseCtx, UA_Boolean moveToken) {
  2584. UA_DiagnosticInfo *inner = (UA_DiagnosticInfo*)UA_calloc(1, sizeof(UA_DiagnosticInfo));
  2585. if(inner == NULL) {
  2586. return UA_STATUSCODE_BADOUTOFMEMORY;
  2587. }
  2588. memcpy(dst, &inner, sizeof(UA_DiagnosticInfo*)); /* Copy new Pointer do dest */
  2589. return DiagnosticInfo_decodeJson(inner, type, ctx, parseCtx, moveToken);
  2590. }
  2591. status
  2592. decodeFields(CtxJson *ctx, ParseCtx *parseCtx, DecodeEntry *entries,
  2593. size_t entryCount, const UA_DataType *type) {
  2594. CHECK_TOKEN_BOUNDS;
  2595. size_t objectCount = (size_t)(parseCtx->tokenArray[parseCtx->index].size);
  2596. status ret = UA_STATUSCODE_GOOD;
  2597. if(entryCount == 1) {
  2598. if(*(entries[0].fieldName) == 0) { /*No MemberName*/
  2599. return entries[0].function(entries[0].fieldPointer, type,
  2600. ctx, parseCtx, true); /*ENCODE DIRECT*/
  2601. }
  2602. } else if(entryCount == 0) {
  2603. return UA_STATUSCODE_BADDECODINGERROR;
  2604. }
  2605. parseCtx->index++; /*go to first key*/
  2606. CHECK_TOKEN_BOUNDS;
  2607. for (size_t currentObjectCount = 0; currentObjectCount < objectCount &&
  2608. parseCtx->index < parseCtx->tokenCount; currentObjectCount++) {
  2609. /* start searching at the index of currentObjectCount */
  2610. for (size_t i = currentObjectCount; i < entryCount + currentObjectCount; i++) {
  2611. /* Search for KEY, if found outer loop will be one less. Best case
  2612. * is objectCount if in order! */
  2613. size_t index = i % entryCount;
  2614. CHECK_TOKEN_BOUNDS;
  2615. if(jsoneq((char*) ctx->pos, &parseCtx->tokenArray[parseCtx->index],
  2616. entries[index].fieldName) != 0)
  2617. continue;
  2618. if(entries[index].found) {
  2619. /*Duplicate Key found, abort.*/
  2620. return UA_STATUSCODE_BADDECODINGERROR;
  2621. }
  2622. entries[index].found = true;
  2623. parseCtx->index++; /*goto value*/
  2624. CHECK_TOKEN_BOUNDS;
  2625. /* Find the data type.
  2626. * TODO: get rid of parameter type. Only forward via DecodeEntry.
  2627. */
  2628. const UA_DataType *membertype = type;
  2629. if(entries[index].type)
  2630. membertype = entries[index].type;
  2631. if(entries[index].function != NULL) {
  2632. ret = entries[index].function(entries[index].fieldPointer,
  2633. membertype, ctx, parseCtx, true); /*Move Token True*/
  2634. if(ret != UA_STATUSCODE_GOOD)
  2635. return ret;
  2636. } else {
  2637. /*overstep single value, this will not work if object or array
  2638. Only used not to double parse pre looked up type, but it has to be overstepped*/
  2639. parseCtx->index++;
  2640. }
  2641. break;
  2642. }
  2643. }
  2644. return ret;
  2645. }
  2646. static status
  2647. Array_decodeJson_internal(void **dst, const UA_DataType *type,
  2648. CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) {
  2649. (void) moveToken;
  2650. status ret;
  2651. if(parseCtx->tokenArray[parseCtx->index].type != JSMN_ARRAY)
  2652. return UA_STATUSCODE_BADDECODINGERROR;
  2653. size_t length = (size_t)parseCtx->tokenArray[parseCtx->index].size;
  2654. /* Save the length of the array */
  2655. size_t *p = (size_t*) dst - 1;
  2656. *p = length;
  2657. /* Return early for empty arrays */
  2658. if(length == 0) {
  2659. *dst = UA_EMPTY_ARRAY_SENTINEL;
  2660. return UA_STATUSCODE_GOOD;
  2661. }
  2662. /* Allocate memory */
  2663. *dst = UA_calloc(length, type->memSize);
  2664. if(*dst == NULL)
  2665. return UA_STATUSCODE_BADOUTOFMEMORY;
  2666. parseCtx->index++; /* We go to first Array member!*/
  2667. /* Decode array members */
  2668. uintptr_t ptr = (uintptr_t)*dst;
  2669. for(size_t i = 0; i < length; ++i) {
  2670. ret = decodeJsonJumpTable[type->typeKind]((void*)ptr, type, ctx, parseCtx, true);
  2671. if(ret != UA_STATUSCODE_GOOD) {
  2672. UA_Array_delete(*dst, i+1, type);
  2673. *dst = NULL;
  2674. return ret;
  2675. }
  2676. ptr += type->memSize;
  2677. }
  2678. return UA_STATUSCODE_GOOD;
  2679. }
  2680. /*Wrapper for array with valid decodingStructure.*/
  2681. static status
  2682. Array_decodeJson(void * dst, const UA_DataType *type, CtxJson *ctx,
  2683. ParseCtx *parseCtx, UA_Boolean moveToken) {
  2684. return Array_decodeJson_internal((void **)dst, type, ctx, parseCtx, moveToken);
  2685. }
  2686. static status
  2687. decodeJsonStructure(void *dst, const UA_DataType *type, CtxJson *ctx,
  2688. ParseCtx *parseCtx, UA_Boolean moveToken) {
  2689. (void) moveToken;
  2690. /* Check the recursion limit */
  2691. if(ctx->depth > UA_JSON_ENCODING_MAX_RECURSION)
  2692. return UA_STATUSCODE_BADENCODINGERROR;
  2693. ctx->depth++;
  2694. uintptr_t ptr = (uintptr_t)dst;
  2695. status ret = UA_STATUSCODE_GOOD;
  2696. u8 membersSize = type->membersSize;
  2697. const UA_DataType *typelists[2] = { UA_TYPES, &type[-type->typeIndex] };
  2698. UA_STACKARRAY(DecodeEntry, entries, membersSize);
  2699. for(size_t i = 0; i < membersSize && ret == UA_STATUSCODE_GOOD; ++i) {
  2700. const UA_DataTypeMember *m = &type->members[i];
  2701. const UA_DataType *mt = &typelists[!m->namespaceZero][m->memberTypeIndex];
  2702. entries[i].type = mt;
  2703. if(!m->isArray) {
  2704. ptr += m->padding;
  2705. entries[i].fieldName = m->memberName;
  2706. entries[i].fieldPointer = (void*)ptr;
  2707. entries[i].function = decodeJsonJumpTable[mt->typeKind];
  2708. entries[i].found = false;
  2709. ptr += mt->memSize;
  2710. } else {
  2711. ptr += m->padding;
  2712. ptr += sizeof(size_t);
  2713. entries[i].fieldName = m->memberName;
  2714. entries[i].fieldPointer = (void*)ptr;
  2715. entries[i].function = (decodeJsonSignature)Array_decodeJson;
  2716. entries[i].found = false;
  2717. ptr += sizeof(void*);
  2718. }
  2719. }
  2720. ret = decodeFields(ctx, parseCtx, entries, membersSize, type);
  2721. ctx->depth--;
  2722. return ret;
  2723. }
  2724. static status
  2725. decodeJsonNotImplemented(void *dst, const UA_DataType *type, CtxJson *ctx,
  2726. ParseCtx *parseCtx, UA_Boolean moveToken) {
  2727. (void)dst, (void)type, (void)ctx, (void)parseCtx, (void)moveToken;
  2728. return UA_STATUSCODE_BADNOTIMPLEMENTED;
  2729. }
  2730. const decodeJsonSignature decodeJsonJumpTable[UA_DATATYPEKINDS] = {
  2731. (decodeJsonSignature)Boolean_decodeJson,
  2732. (decodeJsonSignature)SByte_decodeJson, /* SByte */
  2733. (decodeJsonSignature)Byte_decodeJson,
  2734. (decodeJsonSignature)Int16_decodeJson, /* Int16 */
  2735. (decodeJsonSignature)UInt16_decodeJson,
  2736. (decodeJsonSignature)Int32_decodeJson, /* Int32 */
  2737. (decodeJsonSignature)UInt32_decodeJson,
  2738. (decodeJsonSignature)Int64_decodeJson, /* Int64 */
  2739. (decodeJsonSignature)UInt64_decodeJson,
  2740. (decodeJsonSignature)Float_decodeJson,
  2741. (decodeJsonSignature)Double_decodeJson,
  2742. (decodeJsonSignature)String_decodeJson,
  2743. (decodeJsonSignature)DateTime_decodeJson, /* DateTime */
  2744. (decodeJsonSignature)Guid_decodeJson,
  2745. (decodeJsonSignature)ByteString_decodeJson, /* ByteString */
  2746. (decodeJsonSignature)String_decodeJson, /* XmlElement */
  2747. (decodeJsonSignature)NodeId_decodeJson,
  2748. (decodeJsonSignature)ExpandedNodeId_decodeJson,
  2749. (decodeJsonSignature)StatusCode_decodeJson, /* StatusCode */
  2750. (decodeJsonSignature)QualifiedName_decodeJson, /* QualifiedName */
  2751. (decodeJsonSignature)LocalizedText_decodeJson,
  2752. (decodeJsonSignature)ExtensionObject_decodeJson,
  2753. (decodeJsonSignature)DataValue_decodeJson,
  2754. (decodeJsonSignature)Variant_decodeJson,
  2755. (decodeJsonSignature)DiagnosticInfo_decodeJson,
  2756. (decodeJsonSignature)decodeJsonNotImplemented, /* Decimal */
  2757. (decodeJsonSignature)Int32_decodeJson, /* Enum */
  2758. (decodeJsonSignature)decodeJsonStructure,
  2759. (decodeJsonSignature)decodeJsonNotImplemented, /* Structure with optional fields */
  2760. (decodeJsonSignature)decodeJsonNotImplemented, /* Union */
  2761. (decodeJsonSignature)decodeJsonNotImplemented /* BitfieldCluster */
  2762. };
  2763. decodeJsonSignature getDecodeSignature(u8 index) {
  2764. return decodeJsonJumpTable[index];
  2765. }
  2766. status
  2767. tokenize(ParseCtx *parseCtx, CtxJson *ctx, const UA_ByteString *src) {
  2768. /* Set up the context */
  2769. ctx->pos = &src->data[0];
  2770. ctx->end = &src->data[src->length];
  2771. ctx->depth = 0;
  2772. parseCtx->tokenCount = 0;
  2773. parseCtx->index = 0;
  2774. /*Set up tokenizer jsmn*/
  2775. jsmn_parser p;
  2776. jsmn_init(&p);
  2777. parseCtx->tokenCount = (UA_Int32)
  2778. jsmn_parse(&p, (char*)src->data, src->length,
  2779. parseCtx->tokenArray, UA_JSON_MAXTOKENCOUNT);
  2780. if(parseCtx->tokenCount < 0) {
  2781. if(parseCtx->tokenCount == JSMN_ERROR_NOMEM)
  2782. return UA_STATUSCODE_BADOUTOFMEMORY;
  2783. return UA_STATUSCODE_BADDECODINGERROR;
  2784. }
  2785. return UA_STATUSCODE_GOOD;
  2786. }
  2787. UA_StatusCode
  2788. decodeJsonInternal(void *dst, const UA_DataType *type,
  2789. CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) {
  2790. return decodeJsonJumpTable[type->typeKind](dst, type, ctx, parseCtx, moveToken);
  2791. }
  2792. status UA_FUNC_ATTR_WARN_UNUSED_RESULT
  2793. UA_decodeJson(const UA_ByteString *src, void *dst, const UA_DataType *type) {
  2794. #ifndef UA_ENABLE_TYPENAMES
  2795. return UA_STATUSCODE_BADNOTSUPPORTED;
  2796. #endif
  2797. if(dst == NULL || src == NULL || type == NULL) {
  2798. return UA_STATUSCODE_BADARGUMENTSMISSING;
  2799. }
  2800. /* Set up the context */
  2801. CtxJson ctx;
  2802. ParseCtx parseCtx;
  2803. parseCtx.tokenArray = (jsmntok_t*)UA_malloc(sizeof(jsmntok_t) * UA_JSON_MAXTOKENCOUNT);
  2804. if(!parseCtx.tokenArray)
  2805. return UA_STATUSCODE_BADOUTOFMEMORY;
  2806. status ret = tokenize(&parseCtx, &ctx, src);
  2807. if(ret != UA_STATUSCODE_GOOD)
  2808. goto cleanup;
  2809. /* Assume the top-level element is an object */
  2810. if(parseCtx.tokenCount < 1 || parseCtx.tokenArray[0].type != JSMN_OBJECT) {
  2811. if(parseCtx.tokenCount == 1) {
  2812. if(parseCtx.tokenArray[0].type == JSMN_PRIMITIVE ||
  2813. parseCtx.tokenArray[0].type == JSMN_STRING) {
  2814. /* Only a primitive to parse. Do it directly. */
  2815. memset(dst, 0, type->memSize); /* Initialize the value */
  2816. ret = decodeJsonJumpTable[type->typeKind](dst, type, &ctx, &parseCtx, true);
  2817. goto cleanup;
  2818. }
  2819. }
  2820. ret = UA_STATUSCODE_BADDECODINGERROR;
  2821. goto cleanup;
  2822. }
  2823. /* Decode */
  2824. memset(dst, 0, type->memSize); /* Initialize the value */
  2825. ret = decodeJsonJumpTable[type->typeKind](dst, type, &ctx, &parseCtx, true);
  2826. cleanup:
  2827. UA_free(parseCtx.tokenArray);
  2828. /* sanity check if all Tokens were processed */
  2829. if(!(parseCtx.index == parseCtx.tokenCount ||
  2830. parseCtx.index == parseCtx.tokenCount-1)) {
  2831. ret = UA_STATUSCODE_BADDECODINGERROR;
  2832. }
  2833. if(ret != UA_STATUSCODE_GOOD)
  2834. UA_deleteMembers(dst, type); /* Clean up */
  2835. return ret;
  2836. }