ua_types_encoding_json.c 109 KB

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