ua_types_encoding_json.c 110 KB

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