ua_types_encoding_json.c 110 KB

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