ua_types_encoding_json.c 112 KB

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