ua_types_encoding_json.c 111 KB

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