ua_services_attribute.c 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555
  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 2015-2016 (c) Sten Grüner
  7. * Copyright 2014-2017 (c) Florian Palm
  8. * Copyright 2015 (c) Christian Fimmers
  9. * Copyright 2015-2016 (c) Chris Iatrou
  10. * Copyright 2015-2016 (c) Oleksiy Vasylyev
  11. * Copyright 2015 (c) wuyangtang
  12. * Copyright 2017 (c) Stefan Profanter, fortiss GmbH
  13. * Copyright 2016 (c) Lorenz Haas
  14. * Copyright 2017 (c) frax2222
  15. * Copyright 2017 (c) Thomas Bender
  16. * Copyright 2017 (c) Julian Grothoff
  17. * Copyright 2017 (c) Jonas Green
  18. * Copyright 2017 (c) Henrik Norrman
  19. */
  20. #include "ua_server_internal.h"
  21. #include "ua_types_encoding_binary.h"
  22. #include "ua_services.h"
  23. #ifdef UA_ENABLE_HISTORIZING
  24. #include "ua_plugin_historydatabase.h"
  25. #endif
  26. /******************/
  27. /* Access Control */
  28. /******************/
  29. static UA_UInt32
  30. getUserWriteMask(UA_Server *server, const UA_Session *session,
  31. const UA_Node *node) {
  32. if(session == &server->adminSession)
  33. return 0xFFFFFFFF; /* the local admin user has all rights */
  34. return node->writeMask &
  35. server->config.accessControl.getUserRightsMask(server, &server->config.accessControl,
  36. &session->sessionId, session->sessionHandle,
  37. &node->nodeId, node->context);
  38. }
  39. static UA_Byte
  40. getAccessLevel(UA_Server *server, const UA_Session *session,
  41. const UA_VariableNode *node) {
  42. if(session == &server->adminSession)
  43. return 0xFF; /* the local admin user has all rights */
  44. return node->accessLevel;
  45. }
  46. static UA_Byte
  47. getUserAccessLevel(UA_Server *server, const UA_Session *session,
  48. const UA_VariableNode *node) {
  49. if(session == &server->adminSession)
  50. return 0xFF; /* the local admin user has all rights */
  51. return node->accessLevel &
  52. server->config.accessControl.getUserAccessLevel(server, &server->config.accessControl,
  53. &session->sessionId, session->sessionHandle,
  54. &node->nodeId, node->context);
  55. }
  56. static UA_Boolean
  57. getUserExecutable(UA_Server *server, const UA_Session *session,
  58. const UA_MethodNode *node) {
  59. if(session == &server->adminSession)
  60. return true; /* the local admin user has all rights */
  61. return node->executable &
  62. server->config.accessControl.getUserExecutable(server, &server->config.accessControl,
  63. &session->sessionId, session->sessionHandle,
  64. &node->nodeId, node->context);
  65. }
  66. /****************/
  67. /* Read Service */
  68. /****************/
  69. static UA_StatusCode
  70. readArrayDimensionsAttribute(const UA_VariableNode *vn, UA_DataValue *v) {
  71. UA_Variant_setArray(&v->value, vn->arrayDimensions,
  72. vn->arrayDimensionsSize, &UA_TYPES[UA_TYPES_UINT32]);
  73. v->value.storageType = UA_VARIANT_DATA_NODELETE;
  74. return UA_STATUSCODE_GOOD;
  75. }
  76. static void
  77. setScalarNoDelete(UA_Variant *v, const void * UA_RESTRICT p,
  78. const UA_DataType *type) {
  79. UA_Variant_setScalar(v, (void*)(uintptr_t)p, type);
  80. v->storageType = UA_VARIANT_DATA_NODELETE;
  81. }
  82. static UA_StatusCode
  83. readIsAbstractAttribute(const UA_Node *node, UA_Variant *v) {
  84. const UA_Boolean *isAbstract;
  85. switch(node->nodeClass) {
  86. case UA_NODECLASS_REFERENCETYPE:
  87. isAbstract = &((const UA_ReferenceTypeNode*)node)->isAbstract;
  88. break;
  89. case UA_NODECLASS_OBJECTTYPE:
  90. isAbstract = &((const UA_ObjectTypeNode*)node)->isAbstract;
  91. break;
  92. case UA_NODECLASS_VARIABLETYPE:
  93. isAbstract = &((const UA_VariableTypeNode*)node)->isAbstract;
  94. break;
  95. case UA_NODECLASS_DATATYPE:
  96. isAbstract = &((const UA_DataTypeNode*)node)->isAbstract;
  97. break;
  98. default:
  99. return UA_STATUSCODE_BADATTRIBUTEIDINVALID;
  100. }
  101. setScalarNoDelete(v, isAbstract, &UA_TYPES[UA_TYPES_BOOLEAN]);
  102. v->storageType = UA_VARIANT_DATA_NODELETE;
  103. return UA_STATUSCODE_GOOD;
  104. }
  105. static UA_StatusCode
  106. readValueAttributeFromNode(UA_Server *server, UA_Session *session,
  107. const UA_VariableNode *vn, UA_DataValue *v,
  108. UA_NumericRange *rangeptr) {
  109. if(vn->value.data.callback.onRead) {
  110. vn->value.data.callback.onRead(server, &session->sessionId,
  111. session->sessionHandle, &vn->nodeId,
  112. vn->context, rangeptr, &vn->value.data.value);
  113. const UA_Node *old = (const UA_Node *)vn;
  114. /* Reopen the node to see the changes from onRead */
  115. vn = (const UA_VariableNode*)UA_Nodestore_get(server, &vn->nodeId);
  116. UA_Nodestore_release(server, old);
  117. }
  118. if(rangeptr)
  119. return UA_Variant_copyRange(&vn->value.data.value.value, &v->value, *rangeptr);
  120. *v = vn->value.data.value;
  121. v->value.storageType = UA_VARIANT_DATA_NODELETE;
  122. return UA_STATUSCODE_GOOD;
  123. }
  124. static UA_StatusCode
  125. readValueAttributeFromDataSource(UA_Server *server, UA_Session *session,
  126. const UA_VariableNode *vn, UA_DataValue *v,
  127. UA_TimestampsToReturn timestamps,
  128. UA_NumericRange *rangeptr) {
  129. if(!vn->value.dataSource.read)
  130. return UA_STATUSCODE_BADINTERNALERROR;
  131. UA_Boolean sourceTimeStamp = (timestamps == UA_TIMESTAMPSTORETURN_SOURCE ||
  132. timestamps == UA_TIMESTAMPSTORETURN_BOTH);
  133. return vn->value.dataSource.read(server, &session->sessionId, session->sessionHandle,
  134. &vn->nodeId, vn->context, sourceTimeStamp, rangeptr, v);
  135. }
  136. static UA_StatusCode
  137. readValueAttributeComplete(UA_Server *server, UA_Session *session,
  138. const UA_VariableNode *vn, UA_TimestampsToReturn timestamps,
  139. const UA_String *indexRange, UA_DataValue *v) {
  140. /* Compute the index range */
  141. UA_NumericRange range;
  142. UA_NumericRange *rangeptr = NULL;
  143. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  144. if(indexRange && indexRange->length > 0) {
  145. retval = UA_NumericRange_parseFromString(&range, indexRange);
  146. if(retval != UA_STATUSCODE_GOOD)
  147. return retval;
  148. rangeptr = ⦥
  149. }
  150. /* Read the value */
  151. if(vn->valueSource == UA_VALUESOURCE_DATA)
  152. retval = readValueAttributeFromNode(server, session, vn, v, rangeptr);
  153. else
  154. retval = readValueAttributeFromDataSource(server, session, vn, v, timestamps, rangeptr);
  155. /* Clean up */
  156. if(rangeptr)
  157. UA_free(range.dimensions);
  158. return retval;
  159. }
  160. UA_StatusCode
  161. readValueAttribute(UA_Server *server, UA_Session *session,
  162. const UA_VariableNode *vn, UA_DataValue *v) {
  163. return readValueAttributeComplete(server, session, vn, UA_TIMESTAMPSTORETURN_NEITHER, NULL, v);
  164. }
  165. static const UA_String binEncoding = {sizeof("Default Binary")-1, (UA_Byte*)"Default Binary"};
  166. static const UA_String xmlEncoding = {sizeof("Default XML")-1, (UA_Byte*)"Default XML"};
  167. static const UA_String jsonEncoding = {sizeof("Default JSON")-1, (UA_Byte*)"Default JSON"};
  168. #define CHECK_NODECLASS(CLASS) \
  169. if(!(node->nodeClass & (CLASS))) { \
  170. retval = UA_STATUSCODE_BADATTRIBUTEIDINVALID; \
  171. break; \
  172. }
  173. /* Returns a datavalue that may point into the node via the
  174. * UA_VARIANT_DATA_NODELETE tag. Don't access the returned DataValue once the
  175. * node has been released! */
  176. void
  177. ReadWithNode(const UA_Node *node, UA_Server *server, UA_Session *session,
  178. UA_TimestampsToReturn timestampsToReturn,
  179. const UA_ReadValueId *id, UA_DataValue *v) {
  180. UA_LOG_DEBUG_SESSION(&server->config.logger, session,
  181. "Read the attribute %i", id->attributeId);
  182. /* Only Binary Encoding is supported */
  183. if(id->dataEncoding.name.length > 0 &&
  184. !UA_String_equal(&binEncoding, &id->dataEncoding.name)) {
  185. if(UA_String_equal(&xmlEncoding, &id->dataEncoding.name) ||
  186. UA_String_equal(&jsonEncoding, &id->dataEncoding.name))
  187. v->status = UA_STATUSCODE_BADDATAENCODINGUNSUPPORTED;
  188. else
  189. v->status = UA_STATUSCODE_BADDATAENCODINGINVALID;
  190. v->hasStatus = true;
  191. return;
  192. }
  193. /* Index range for an attribute other than value */
  194. if(id->indexRange.length > 0 && id->attributeId != UA_ATTRIBUTEID_VALUE) {
  195. v->hasStatus = true;
  196. v->status = UA_STATUSCODE_BADINDEXRANGENODATA;
  197. return;
  198. }
  199. /* Read the attribute */
  200. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  201. switch(id->attributeId) {
  202. case UA_ATTRIBUTEID_NODEID:
  203. setScalarNoDelete(&v->value, &node->nodeId, &UA_TYPES[UA_TYPES_NODEID]);
  204. break;
  205. case UA_ATTRIBUTEID_NODECLASS:
  206. setScalarNoDelete(&v->value, &node->nodeClass, &UA_TYPES[UA_TYPES_NODECLASS]);
  207. break;
  208. case UA_ATTRIBUTEID_BROWSENAME:
  209. setScalarNoDelete(&v->value, &node->browseName, &UA_TYPES[UA_TYPES_QUALIFIEDNAME]);
  210. break;
  211. case UA_ATTRIBUTEID_DISPLAYNAME:
  212. setScalarNoDelete(&v->value, &node->displayName, &UA_TYPES[UA_TYPES_LOCALIZEDTEXT]);
  213. break;
  214. case UA_ATTRIBUTEID_DESCRIPTION:
  215. setScalarNoDelete(&v->value, &node->description, &UA_TYPES[UA_TYPES_LOCALIZEDTEXT]);
  216. break;
  217. case UA_ATTRIBUTEID_WRITEMASK:
  218. setScalarNoDelete(&v->value, &node->writeMask, &UA_TYPES[UA_TYPES_UINT32]);
  219. break;
  220. case UA_ATTRIBUTEID_USERWRITEMASK: {
  221. UA_UInt32 userWriteMask = getUserWriteMask(server, session, node);
  222. retval = UA_Variant_setScalarCopy(&v->value, &userWriteMask, &UA_TYPES[UA_TYPES_UINT32]);
  223. break; }
  224. case UA_ATTRIBUTEID_ISABSTRACT:
  225. retval = readIsAbstractAttribute(node, &v->value);
  226. break;
  227. case UA_ATTRIBUTEID_SYMMETRIC:
  228. CHECK_NODECLASS(UA_NODECLASS_REFERENCETYPE);
  229. setScalarNoDelete(&v->value, &((const UA_ReferenceTypeNode*)node)->symmetric,
  230. &UA_TYPES[UA_TYPES_BOOLEAN]);
  231. break;
  232. case UA_ATTRIBUTEID_INVERSENAME:
  233. CHECK_NODECLASS(UA_NODECLASS_REFERENCETYPE);
  234. setScalarNoDelete(&v->value, &((const UA_ReferenceTypeNode*)node)->inverseName,
  235. &UA_TYPES[UA_TYPES_LOCALIZEDTEXT]);
  236. break;
  237. case UA_ATTRIBUTEID_CONTAINSNOLOOPS:
  238. CHECK_NODECLASS(UA_NODECLASS_VIEW);
  239. setScalarNoDelete(&v->value, &((const UA_ViewNode*)node)->containsNoLoops,
  240. &UA_TYPES[UA_TYPES_BOOLEAN]);
  241. break;
  242. case UA_ATTRIBUTEID_EVENTNOTIFIER:
  243. CHECK_NODECLASS(UA_NODECLASS_VIEW | UA_NODECLASS_OBJECT);
  244. if(node->nodeClass == UA_NODECLASS_VIEW) {
  245. setScalarNoDelete(&v->value, &((const UA_ViewNode*)node)->eventNotifier,
  246. &UA_TYPES[UA_TYPES_BYTE]);
  247. }
  248. else{
  249. setScalarNoDelete(&v->value, &((const UA_ObjectNode*)node)->eventNotifier,
  250. &UA_TYPES[UA_TYPES_BYTE]);
  251. }
  252. break;
  253. case UA_ATTRIBUTEID_VALUE: {
  254. CHECK_NODECLASS(UA_NODECLASS_VARIABLE | UA_NODECLASS_VARIABLETYPE);
  255. /* VariableTypes don't have the AccessLevel concept. Always allow reading the value. */
  256. if(node->nodeClass == UA_NODECLASS_VARIABLE) {
  257. /* The access to a value variable is granted via the AccessLevel
  258. * and UserAccessLevel attributes */
  259. UA_Byte accessLevel = getAccessLevel(server, session, (const UA_VariableNode*)node);
  260. if(!(accessLevel & (UA_ACCESSLEVELMASK_READ))) {
  261. retval = UA_STATUSCODE_BADNOTREADABLE;
  262. break;
  263. }
  264. accessLevel = getUserAccessLevel(server, session,
  265. (const UA_VariableNode*)node);
  266. if(!(accessLevel & (UA_ACCESSLEVELMASK_READ))) {
  267. retval = UA_STATUSCODE_BADUSERACCESSDENIED;
  268. break;
  269. }
  270. }
  271. retval = readValueAttributeComplete(server, session, (const UA_VariableNode*)node,
  272. timestampsToReturn, &id->indexRange, v);
  273. break;
  274. }
  275. case UA_ATTRIBUTEID_DATATYPE:
  276. CHECK_NODECLASS(UA_NODECLASS_VARIABLE | UA_NODECLASS_VARIABLETYPE);
  277. setScalarNoDelete(&v->value, &((const UA_VariableTypeNode*)node)->dataType,
  278. &UA_TYPES[UA_TYPES_NODEID]);
  279. break;
  280. case UA_ATTRIBUTEID_VALUERANK:
  281. CHECK_NODECLASS(UA_NODECLASS_VARIABLE | UA_NODECLASS_VARIABLETYPE);
  282. setScalarNoDelete(&v->value, &((const UA_VariableTypeNode*)node)->valueRank,
  283. &UA_TYPES[UA_TYPES_INT32]);
  284. break;
  285. case UA_ATTRIBUTEID_ARRAYDIMENSIONS:
  286. CHECK_NODECLASS(UA_NODECLASS_VARIABLE | UA_NODECLASS_VARIABLETYPE);
  287. retval = readArrayDimensionsAttribute((const UA_VariableNode*)node, v);
  288. break;
  289. case UA_ATTRIBUTEID_ACCESSLEVEL:
  290. CHECK_NODECLASS(UA_NODECLASS_VARIABLE);
  291. setScalarNoDelete(&v->value, &((const UA_VariableNode*)node)->accessLevel,
  292. &UA_TYPES[UA_TYPES_BYTE]);
  293. break;
  294. case UA_ATTRIBUTEID_USERACCESSLEVEL: {
  295. CHECK_NODECLASS(UA_NODECLASS_VARIABLE);
  296. UA_Byte userAccessLevel = getUserAccessLevel(server, session,
  297. (const UA_VariableNode*)node);
  298. retval = UA_Variant_setScalarCopy(&v->value, &userAccessLevel, &UA_TYPES[UA_TYPES_BYTE]);
  299. break; }
  300. case UA_ATTRIBUTEID_MINIMUMSAMPLINGINTERVAL:
  301. CHECK_NODECLASS(UA_NODECLASS_VARIABLE);
  302. setScalarNoDelete(&v->value, &((const UA_VariableNode*)node)->minimumSamplingInterval,
  303. &UA_TYPES[UA_TYPES_DOUBLE]);
  304. break;
  305. case UA_ATTRIBUTEID_HISTORIZING:
  306. CHECK_NODECLASS(UA_NODECLASS_VARIABLE);
  307. setScalarNoDelete(&v->value, &((const UA_VariableNode*)node)->historizing,
  308. &UA_TYPES[UA_TYPES_BOOLEAN]);
  309. break;
  310. case UA_ATTRIBUTEID_EXECUTABLE:
  311. CHECK_NODECLASS(UA_NODECLASS_METHOD);
  312. setScalarNoDelete(&v->value, &((const UA_MethodNode*)node)->executable,
  313. &UA_TYPES[UA_TYPES_BOOLEAN]);
  314. break;
  315. case UA_ATTRIBUTEID_USEREXECUTABLE: {
  316. CHECK_NODECLASS(UA_NODECLASS_METHOD);
  317. UA_Boolean userExecutable = getUserExecutable(server, session,
  318. (const UA_MethodNode*)node);
  319. retval = UA_Variant_setScalarCopy(&v->value, &userExecutable, &UA_TYPES[UA_TYPES_BOOLEAN]);
  320. break; }
  321. default:
  322. retval = UA_STATUSCODE_BADATTRIBUTEIDINVALID;
  323. }
  324. /* Return error code when reading has failed */
  325. if(retval != UA_STATUSCODE_GOOD) {
  326. v->hasStatus = true;
  327. v->status = retval;
  328. return;
  329. }
  330. v->hasValue = true;
  331. /* Create server timestamp */
  332. if(timestampsToReturn == UA_TIMESTAMPSTORETURN_SERVER ||
  333. timestampsToReturn == UA_TIMESTAMPSTORETURN_BOTH) {
  334. if (!v->hasServerTimestamp) {
  335. v->serverTimestamp = UA_DateTime_now();
  336. v->hasServerTimestamp = true;
  337. }
  338. }
  339. /* Handle source time stamp */
  340. if(id->attributeId == UA_ATTRIBUTEID_VALUE) {
  341. if(timestampsToReturn == UA_TIMESTAMPSTORETURN_SERVER ||
  342. timestampsToReturn == UA_TIMESTAMPSTORETURN_NEITHER) {
  343. v->hasSourceTimestamp = false;
  344. v->hasSourcePicoseconds = false;
  345. } else if(!v->hasSourceTimestamp) {
  346. v->sourceTimestamp = UA_DateTime_now();
  347. v->hasSourceTimestamp = true;
  348. }
  349. }
  350. }
  351. static UA_StatusCode
  352. Operation_Read(UA_Server *server, UA_Session *session, UA_MessageContext *mc,
  353. UA_TimestampsToReturn timestampsToReturn, const UA_ReadValueId *id) {
  354. UA_DataValue dv;
  355. UA_DataValue_init(&dv);
  356. /* Get the node */
  357. const UA_Node *node = UA_Nodestore_get(server, &id->nodeId);
  358. /* Perform the read operation */
  359. if(node) {
  360. ReadWithNode(node, server, session, timestampsToReturn, id, &dv);
  361. } else {
  362. dv.hasStatus = true;
  363. dv.status = UA_STATUSCODE_BADNODEIDUNKNOWN;
  364. }
  365. /* Encode (and send) the results */
  366. UA_StatusCode retval = UA_MessageContext_encode(mc, &dv, &UA_TYPES[UA_TYPES_DATAVALUE]);
  367. /* Free copied data and release the node */
  368. UA_Variant_deleteMembers(&dv.value);
  369. UA_Nodestore_release(server, node);
  370. return retval;
  371. }
  372. UA_StatusCode Service_Read(UA_Server *server, UA_Session *session, UA_MessageContext *mc,
  373. const UA_ReadRequest *request, UA_ResponseHeader *responseHeader) {
  374. UA_LOG_DEBUG_SESSION(&server->config.logger, session,
  375. "Processing ReadRequest");
  376. /* Check if the timestampstoreturn is valid */
  377. if(request->timestampsToReturn > UA_TIMESTAMPSTORETURN_NEITHER)
  378. responseHeader->serviceResult = UA_STATUSCODE_BADTIMESTAMPSTORETURNINVALID;
  379. if(request->nodesToReadSize == 0)
  380. responseHeader->serviceResult = UA_STATUSCODE_BADNOTHINGTODO;
  381. /* Check if maxAge is valid */
  382. if(request->maxAge < 0)
  383. responseHeader->serviceResult = UA_STATUSCODE_BADMAXAGEINVALID;
  384. /* Check if there are too many operations */
  385. if(server->config.maxNodesPerRead != 0 &&
  386. request->nodesToReadSize > server->config.maxNodesPerRead)
  387. responseHeader->serviceResult = UA_STATUSCODE_BADTOOMANYOPERATIONS;
  388. /* Encode the response header */
  389. UA_StatusCode retval =
  390. UA_MessageContext_encode(mc, responseHeader, &UA_TYPES[UA_TYPES_RESPONSEHEADER]);
  391. if(retval != UA_STATUSCODE_GOOD)
  392. return retval;
  393. /* Process nothing if we return an error code for the entire service */
  394. UA_Int32 arraySize = (UA_Int32)request->nodesToReadSize;
  395. if(responseHeader->serviceResult != UA_STATUSCODE_GOOD)
  396. arraySize = 0;
  397. /* Process all ReadValueIds */
  398. retval = UA_MessageContext_encode(mc, &arraySize, &UA_TYPES[UA_TYPES_INT32]);
  399. if(retval != UA_STATUSCODE_GOOD)
  400. return retval;
  401. for(UA_Int32 i = 0; i < arraySize; i++) {
  402. retval = Operation_Read(server, session, mc, request->timestampsToReturn,
  403. &request->nodesToRead[i]);
  404. if(retval != UA_STATUSCODE_GOOD)
  405. return retval;
  406. }
  407. /* Don't return any DiagnosticInfo */
  408. arraySize = -1;
  409. return UA_MessageContext_encode(mc, &arraySize, &UA_TYPES[UA_TYPES_INT32]);
  410. }
  411. UA_DataValue
  412. UA_Server_readWithSession(UA_Server *server, UA_Session *session,
  413. const UA_ReadValueId *item,
  414. UA_TimestampsToReturn timestampsToReturn) {
  415. UA_DataValue dv;
  416. UA_DataValue_init(&dv);
  417. /* Get the node */
  418. const UA_Node *node = UA_Nodestore_get(server, &item->nodeId);
  419. if(!node) {
  420. dv.hasStatus = true;
  421. dv.status = UA_STATUSCODE_BADNODEIDUNKNOWN;
  422. return dv;
  423. }
  424. /* Perform the read operation */
  425. ReadWithNode(node, server, session, timestampsToReturn, item, &dv);
  426. /* Do we have to copy the result before releasing the node? */
  427. if(dv.hasValue && dv.value.storageType == UA_VARIANT_DATA_NODELETE) {
  428. UA_DataValue dv2;
  429. UA_StatusCode retval = UA_DataValue_copy(&dv, &dv2);
  430. if(retval == UA_STATUSCODE_GOOD) {
  431. dv = dv2;
  432. } else {
  433. UA_DataValue_init(&dv);
  434. dv.hasStatus = true;
  435. dv.status = retval;
  436. }
  437. }
  438. /* Release the node and return */
  439. UA_Nodestore_release(server, node);
  440. return dv;
  441. }
  442. /* Exposes the Read service to local users */
  443. UA_DataValue
  444. UA_Server_read(UA_Server *server, const UA_ReadValueId *item,
  445. UA_TimestampsToReturn timestamps) {
  446. return UA_Server_readWithSession(server, &server->adminSession, item, timestamps);
  447. }
  448. /* Used in inline functions exposing the Read service with more syntactic sugar
  449. * for individual attributes */
  450. UA_StatusCode
  451. __UA_Server_read(UA_Server *server, const UA_NodeId *nodeId,
  452. const UA_AttributeId attributeId, void *v) {
  453. /* Call the read service */
  454. UA_ReadValueId item;
  455. UA_ReadValueId_init(&item);
  456. item.nodeId = *nodeId;
  457. item.attributeId = attributeId;
  458. UA_DataValue dv = UA_Server_read(server, &item, UA_TIMESTAMPSTORETURN_NEITHER);
  459. /* Check the return value */
  460. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  461. if(dv.hasStatus)
  462. retval = dv.status;
  463. else if(!dv.hasValue)
  464. retval = UA_STATUSCODE_BADUNEXPECTEDERROR;
  465. if(retval != UA_STATUSCODE_GOOD) {
  466. UA_DataValue_deleteMembers(&dv);
  467. return retval;
  468. }
  469. if(attributeId == UA_ATTRIBUTEID_VALUE ||
  470. attributeId == UA_ATTRIBUTEID_ARRAYDIMENSIONS) {
  471. /* Return the entire variant */
  472. memcpy(v, &dv.value, sizeof(UA_Variant));
  473. } else {
  474. /* Return the variant content only */
  475. memcpy(v, dv.value.data, dv.value.type->memSize);
  476. UA_free(dv.value.data);
  477. }
  478. return retval;
  479. }
  480. UA_StatusCode
  481. UA_Server_readObjectProperty(UA_Server *server, const UA_NodeId objectId,
  482. const UA_QualifiedName propertyName,
  483. UA_Variant *value) {
  484. UA_RelativePathElement rpe;
  485. UA_RelativePathElement_init(&rpe);
  486. rpe.referenceTypeId = UA_NODEID_NUMERIC(0, UA_NS0ID_HASPROPERTY);
  487. rpe.isInverse = false;
  488. rpe.includeSubtypes = false;
  489. rpe.targetName = propertyName;
  490. UA_BrowsePath bp;
  491. UA_BrowsePath_init(&bp);
  492. bp.startingNode = objectId;
  493. bp.relativePath.elementsSize = 1;
  494. bp.relativePath.elements = &rpe;
  495. UA_StatusCode retval;
  496. UA_BrowsePathResult bpr = UA_Server_translateBrowsePathToNodeIds(server, &bp);
  497. if(bpr.statusCode != UA_STATUSCODE_GOOD || bpr.targetsSize < 1) {
  498. retval = bpr.statusCode;
  499. UA_BrowsePathResult_deleteMembers(&bpr);
  500. return retval;
  501. }
  502. retval = UA_Server_readValue(server, bpr.targets[0].targetId.nodeId, value);
  503. UA_BrowsePathResult_deleteMembers(&bpr);
  504. return retval;
  505. }
  506. /*****************/
  507. /* Type Checking */
  508. /*****************/
  509. enum type_equivalence {
  510. TYPE_EQUIVALENCE_NONE,
  511. TYPE_EQUIVALENCE_ENUM,
  512. TYPE_EQUIVALENCE_OPAQUE
  513. };
  514. static enum type_equivalence
  515. typeEquivalence(const UA_DataType *t) {
  516. if(t->membersSize != 1 || !t->members[0].namespaceZero)
  517. return TYPE_EQUIVALENCE_NONE;
  518. if(t->members[0].memberTypeIndex == UA_TYPES_INT32)
  519. return TYPE_EQUIVALENCE_ENUM;
  520. if(t->members[0].memberTypeIndex == UA_TYPES_BYTE && t->members[0].isArray)
  521. return TYPE_EQUIVALENCE_OPAQUE;
  522. return TYPE_EQUIVALENCE_NONE;
  523. }
  524. static const UA_NodeId enumNodeId = {0, UA_NODEIDTYPE_NUMERIC, {UA_NS0ID_ENUMERATION}};
  525. UA_Boolean
  526. compatibleDataType(UA_Server *server, const UA_NodeId *dataType,
  527. const UA_NodeId *constraintDataType, UA_Boolean isValue) {
  528. /* Do not allow empty datatypes */
  529. if(UA_NodeId_isNull(dataType))
  530. return false;
  531. /* No constraint (TODO: use variant instead) */
  532. if(UA_NodeId_isNull(constraintDataType))
  533. return true;
  534. /* Same datatypes */
  535. if (UA_NodeId_equal(dataType, constraintDataType))
  536. return true;
  537. /* Variant allows any subtype */
  538. if(UA_NodeId_equal(constraintDataType, &UA_TYPES[UA_TYPES_VARIANT].typeId))
  539. return true;
  540. /* Is the value-type a subtype of the required type? */
  541. if(isNodeInTree(&server->config.nodestore, dataType, constraintDataType, &subtypeId, 1))
  542. return true;
  543. /* Enum allows Int32 (only) */
  544. if(UA_NodeId_equal(dataType, &UA_TYPES[UA_TYPES_INT32].typeId) &&
  545. isNodeInTree(&server->config.nodestore, constraintDataType, &enumNodeId, &subtypeId, 1))
  546. return true;
  547. /* More checks for the data type of real values (variants) */
  548. if(isValue) {
  549. /* If value is a built-in type: The target data type may be a sub type of
  550. * the built-in type. (e.g. UtcTime is sub-type of DateTime and has a
  551. * DateTime value). A type is builtin if its NodeId is in Namespace 0 and
  552. * has a numeric identifier <= 25 (DiagnosticInfo) */
  553. if(dataType->namespaceIndex == 0 &&
  554. dataType->identifierType == UA_NODEIDTYPE_NUMERIC &&
  555. dataType->identifier.numeric <= 25 &&
  556. isNodeInTree(&server->config.nodestore, constraintDataType,
  557. dataType, &subtypeId, 1))
  558. return true;
  559. }
  560. return false;
  561. }
  562. /* Test whether a ValueRank and the given arraydimensions are compatible.
  563. *
  564. * 5.6.2 Variable NodeClass: If the maximum is unknown the value shall be 0. The
  565. * number of elements shall be equal to the value of the ValueRank Attribute.
  566. * This Attribute shall be null if ValueRank <= 0. */
  567. UA_Boolean
  568. compatibleValueRankArrayDimensions(UA_Server *server, UA_Session *session,
  569. UA_Int32 valueRank, size_t arrayDimensionsSize) {
  570. /* ValueRank invalid */
  571. if(valueRank < UA_VALUERANK_SCALAR_OR_ONE_DIMENSION) {
  572. UA_LOG_INFO_SESSION(&server->config.logger, session,
  573. "The ValueRank is invalid (< -3)");
  574. return false;
  575. }
  576. /* case -3, UA_VALUERANK_SCALAR_OR_ONE_DIMENSION: the value can be a scalar or a one dimensional array */
  577. /* case -2, UA_VALUERANK_ANY: the value can be a scalar or an array with any number of dimensions */
  578. /* case -1, UA_VALUERANK_SCALAR: the value is a scalar */
  579. /* case 0, UA_VALUERANK_ONE_OR_MORE_DIMENSIONS: the value is an array with one or more dimensions */
  580. if(valueRank <= UA_VALUERANK_ONE_OR_MORE_DIMENSIONS) {
  581. if(arrayDimensionsSize > 0) {
  582. UA_LOG_INFO_SESSION(&server->config.logger, session,
  583. "No ArrayDimensions can be defined for a ValueRank <= 0");
  584. return false;
  585. }
  586. return true;
  587. }
  588. /* case >= 1, UA_VALUERANK_ONE_DIMENSION: the value is an array with the specified number of dimensions */
  589. if(arrayDimensionsSize != (size_t)valueRank) {
  590. UA_LOG_INFO_SESSION(&server->config.logger, session,
  591. "The number of ArrayDimensions is not equal to the (positive) ValueRank");
  592. return false;
  593. }
  594. return true;
  595. }
  596. UA_Boolean
  597. compatibleValueRanks(UA_Int32 valueRank, UA_Int32 constraintValueRank) {
  598. /* Check if the valuerank of the variabletype allows the change. */
  599. switch(constraintValueRank) {
  600. case UA_VALUERANK_SCALAR_OR_ONE_DIMENSION: /* the value can be a scalar or a one dimensional array */
  601. if(valueRank != UA_VALUERANK_SCALAR && valueRank != UA_VALUERANK_ONE_DIMENSION)
  602. return false;
  603. break;
  604. case UA_VALUERANK_ANY: /* the value can be a scalar or an array with any number of dimensions */
  605. break;
  606. case UA_VALUERANK_SCALAR: /* the value is a scalar */
  607. if(valueRank != UA_VALUERANK_SCALAR)
  608. return false;
  609. break;
  610. case UA_VALUERANK_ONE_OR_MORE_DIMENSIONS: /* the value is an array with one or more dimensions */
  611. if(valueRank < (UA_Int32) UA_VALUERANK_ONE_OR_MORE_DIMENSIONS)
  612. return false;
  613. break;
  614. default: /* >= 1: the value is an array with the specified number of dimensions */
  615. if(valueRank != constraintValueRank)
  616. return false;
  617. break;
  618. }
  619. return true;
  620. }
  621. /* Check if the ValueRank allows for the value dimension. This is more
  622. * permissive than checking for the ArrayDimensions attribute. Because the value
  623. * can have dimensions if the ValueRank < 0 */
  624. static UA_Boolean
  625. compatibleValueRankValue(UA_Int32 valueRank, const UA_Variant *value) {
  626. /* Invalid ValueRank */
  627. if(valueRank < UA_VALUERANK_SCALAR_OR_ONE_DIMENSION)
  628. return false;
  629. /* Empty arrays (-1) always match */
  630. if(!value->data)
  631. return true;
  632. size_t arrayDims = value->arrayDimensionsSize;
  633. if(arrayDims == 0 && !UA_Variant_isScalar(value))
  634. arrayDims = 1; /* array but no arraydimensions -> implicit array dimension 1 */
  635. /* We cannot simply use compatibleValueRankArrayDimensions since we can have
  636. * defined ArrayDimensions for the value if the ValueRank is -2 */
  637. switch(valueRank) {
  638. case UA_VALUERANK_SCALAR_OR_ONE_DIMENSION: /* The value can be a scalar or a one dimensional array */
  639. return (arrayDims <= 1);
  640. case UA_VALUERANK_ANY: /* The value can be a scalar or an array with any number of dimensions */
  641. return true;
  642. case UA_VALUERANK_SCALAR: /* The value is a scalar */
  643. return (arrayDims == 0);
  644. default:
  645. break;
  646. }
  647. UA_assert(valueRank >= UA_VALUERANK_ONE_OR_MORE_DIMENSIONS);
  648. /* case 0: the value is an array with one or more dimensions */
  649. return (arrayDims == (UA_UInt32)valueRank);
  650. }
  651. UA_Boolean
  652. compatibleArrayDimensions(size_t constraintArrayDimensionsSize,
  653. const UA_UInt32 *constraintArrayDimensions,
  654. size_t testArrayDimensionsSize,
  655. const UA_UInt32 *testArrayDimensions) {
  656. /* No array dimensions defined -> everything is permitted if the value rank fits */
  657. if(constraintArrayDimensionsSize == 0)
  658. return true;
  659. /* Dimension count must match */
  660. if(testArrayDimensionsSize != constraintArrayDimensionsSize)
  661. return false;
  662. /* Dimension lengths must match; zero in the constraint is a wildcard */
  663. for(size_t i = 0; i < constraintArrayDimensionsSize; ++i) {
  664. if(constraintArrayDimensions[i] != testArrayDimensions[i] &&
  665. constraintArrayDimensions[i] != 0)
  666. return false;
  667. }
  668. return true;
  669. }
  670. UA_Boolean
  671. compatibleValueArrayDimensions(const UA_Variant *value, size_t targetArrayDimensionsSize,
  672. const UA_UInt32 *targetArrayDimensions) {
  673. size_t valueArrayDimensionsSize = value->arrayDimensionsSize;
  674. UA_UInt32 *valueArrayDimensions = value->arrayDimensions;
  675. UA_UInt32 tempArrayDimensions;
  676. if(!valueArrayDimensions && !UA_Variant_isScalar(value)) {
  677. valueArrayDimensionsSize = 1;
  678. tempArrayDimensions = (UA_UInt32)value->arrayLength;
  679. valueArrayDimensions = &tempArrayDimensions;
  680. }
  681. UA_assert(valueArrayDimensionsSize == 0 || valueArrayDimensions != NULL);
  682. return compatibleArrayDimensions(targetArrayDimensionsSize, targetArrayDimensions,
  683. valueArrayDimensionsSize, valueArrayDimensions);
  684. }
  685. UA_Boolean
  686. compatibleValue(UA_Server *server, UA_Session *session, const UA_NodeId *targetDataTypeId,
  687. UA_Int32 targetValueRank, size_t targetArrayDimensionsSize,
  688. const UA_UInt32 *targetArrayDimensions, const UA_Variant *value,
  689. const UA_NumericRange *range) {
  690. /* Empty value */
  691. if(!value->type) {
  692. /* Empty value is allowed for BaseDataType */
  693. if(UA_NodeId_equal(targetDataTypeId, &UA_TYPES[UA_TYPES_VARIANT].typeId) ||
  694. UA_NodeId_equal(targetDataTypeId, &UA_NODEID_NULL))
  695. return true;
  696. /* Allow empty node values since existing information models may have
  697. * variables with no value, e.g. OldValues - ns=0;i=3024. See also
  698. * #1889, https://github.com/open62541/open62541/pull/1889#issuecomment-403506538 */
  699. if(server->config.relaxEmptyValueConstraint) {
  700. UA_LOG_DEBUG_SESSION(&server->config.logger, session,
  701. "Only Variables with data type BaseDataType can contain an "
  702. "empty value. Allow via explicit constraint relaxation.");
  703. return true;
  704. }
  705. UA_LOG_INFO_SESSION(&server->config.logger, session,
  706. "Only Variables with data type BaseDataType can contain an empty value");
  707. return false;
  708. }
  709. /* Has the value a subtype of the required type? BaseDataType (Variant) can
  710. * be anything... */
  711. if(!compatibleDataType(server, &value->type->typeId, targetDataTypeId, true))
  712. return false;
  713. /* Array dimensions are checked later when writing the range */
  714. if(range)
  715. return true;
  716. /* See if the array dimensions match. */
  717. if(!compatibleValueArrayDimensions(value, targetArrayDimensionsSize, targetArrayDimensions))
  718. return false;
  719. /* Check if the valuerank allows for the value dimension */
  720. return compatibleValueRankValue(targetValueRank, value);
  721. }
  722. /*****************/
  723. /* Write Service */
  724. /*****************/
  725. static void
  726. adjustValue(UA_Server *server, UA_Variant *value,
  727. const UA_NodeId *targetDataTypeId) {
  728. const UA_DataType *targetDataType = UA_findDataType(targetDataTypeId);
  729. if(!targetDataType)
  730. return;
  731. /* A string is written to a byte array. the valuerank and array dimensions
  732. * are checked later */
  733. if(targetDataType == &UA_TYPES[UA_TYPES_BYTE] &&
  734. value->type == &UA_TYPES[UA_TYPES_BYTESTRING] &&
  735. UA_Variant_isScalar(value)) {
  736. UA_ByteString *str = (UA_ByteString*)value->data;
  737. value->type = &UA_TYPES[UA_TYPES_BYTE];
  738. value->arrayLength = str->length;
  739. value->data = str->data;
  740. return;
  741. }
  742. /* An enum was sent as an int32, or an opaque type as a bytestring. This
  743. * is detected with the typeIndex indicating the "true" datatype. */
  744. enum type_equivalence te1 = typeEquivalence(targetDataType);
  745. enum type_equivalence te2 = typeEquivalence(value->type);
  746. if(te1 != TYPE_EQUIVALENCE_NONE && te1 == te2) {
  747. value->type = targetDataType;
  748. return;
  749. }
  750. /* No more possible equivalencies */
  751. }
  752. static UA_StatusCode
  753. writeArrayDimensionsAttribute(UA_Server *server, UA_Session *session,
  754. UA_VariableNode *node, const UA_VariableTypeNode *type,
  755. size_t arrayDimensionsSize, UA_UInt32 *arrayDimensions) {
  756. UA_assert(node != NULL);
  757. UA_assert(type != NULL);
  758. /* If this is a variabletype, there must be no instances or subtypes of it
  759. * when we do the change */
  760. if(node->nodeClass == UA_NODECLASS_VARIABLETYPE &&
  761. UA_Node_hasSubTypeOrInstances((UA_Node*)node)) {
  762. UA_LOG_INFO(&server->config.logger, UA_LOGCATEGORY_SERVER,
  763. "Cannot change a variable type with existing instances");
  764. return UA_STATUSCODE_BADINTERNALERROR;
  765. }
  766. /* Check that the array dimensions match with the valuerank */
  767. if(!compatibleValueRankArrayDimensions(server, session, node->valueRank, arrayDimensionsSize)) {
  768. UA_LOG_DEBUG(&server->config.logger, UA_LOGCATEGORY_SERVER,
  769. "Cannot write the ArrayDimensions. The ValueRank does not match.");
  770. return UA_STATUSCODE_BADTYPEMISMATCH;
  771. }
  772. /* Check if the array dimensions match with the wildcards in the
  773. * variabletype (dimension length 0) */
  774. if(type->arrayDimensions &&
  775. !compatibleArrayDimensions(type->arrayDimensionsSize, type->arrayDimensions,
  776. arrayDimensionsSize, arrayDimensions)) {
  777. UA_LOG_DEBUG(&server->config.logger, UA_LOGCATEGORY_SERVER,
  778. "Array dimensions in the variable type do not match");
  779. return UA_STATUSCODE_BADTYPEMISMATCH;
  780. }
  781. /* Check if the current value is compatible with the array dimensions */
  782. UA_DataValue value;
  783. UA_DataValue_init(&value);
  784. UA_StatusCode retval = readValueAttribute(server, session, node, &value);
  785. if(retval != UA_STATUSCODE_GOOD)
  786. return retval;
  787. if(value.hasValue) {
  788. if(!compatibleValueArrayDimensions(&value.value, arrayDimensionsSize, arrayDimensions))
  789. retval = UA_STATUSCODE_BADTYPEMISMATCH;
  790. UA_DataValue_deleteMembers(&value);
  791. if(retval != UA_STATUSCODE_GOOD) {
  792. UA_LOG_DEBUG(&server->config.logger, UA_LOGCATEGORY_SERVER,
  793. "Array dimensions in the current value do not match");
  794. return retval;
  795. }
  796. }
  797. /* Ok, apply */
  798. UA_UInt32 *oldArrayDimensions = node->arrayDimensions;
  799. size_t oldArrayDimensionsSize = node->arrayDimensionsSize;
  800. retval = UA_Array_copy(arrayDimensions, arrayDimensionsSize,
  801. (void**)&node->arrayDimensions,
  802. &UA_TYPES[UA_TYPES_UINT32]);
  803. if(retval != UA_STATUSCODE_GOOD)
  804. return retval;
  805. UA_Array_delete(oldArrayDimensions, oldArrayDimensionsSize, &UA_TYPES[UA_TYPES_UINT32]);
  806. node->arrayDimensionsSize = arrayDimensionsSize;
  807. return UA_STATUSCODE_GOOD;
  808. }
  809. /* Stack layout: ... | node | type */
  810. static UA_StatusCode
  811. writeValueRankAttribute(UA_Server *server, UA_Session *session,
  812. UA_VariableNode *node, const UA_VariableTypeNode *type,
  813. UA_Int32 valueRank) {
  814. UA_assert(node != NULL);
  815. UA_assert(type != NULL);
  816. UA_Int32 constraintValueRank = type->valueRank;
  817. /* If this is a variabletype, there must be no instances or subtypes of it
  818. * when we do the change */
  819. if(node->nodeClass == UA_NODECLASS_VARIABLETYPE &&
  820. UA_Node_hasSubTypeOrInstances((const UA_Node*)node))
  821. return UA_STATUSCODE_BADINTERNALERROR;
  822. /* Check if the valuerank of the variabletype allows the change. */
  823. if(!compatibleValueRanks(valueRank, constraintValueRank))
  824. return UA_STATUSCODE_BADTYPEMISMATCH;
  825. /* Check if the new valuerank is compatible with the array dimensions. Use
  826. * the read service to handle data sources. */
  827. size_t arrayDims = node->arrayDimensionsSize;
  828. if(arrayDims == 0) {
  829. /* the value could be an array with no arrayDimensions defined.
  830. dimensions zero indicate a scalar for compatibleValueRankArrayDimensions. */
  831. UA_DataValue value;
  832. UA_DataValue_init(&value);
  833. UA_StatusCode retval = readValueAttribute(server, session, node, &value);
  834. if(retval != UA_STATUSCODE_GOOD)
  835. return retval;
  836. if(!value.hasValue || !value.value.type) {
  837. /* no value -> apply */
  838. node->valueRank = valueRank;
  839. return UA_STATUSCODE_GOOD;
  840. }
  841. if(!UA_Variant_isScalar(&value.value))
  842. arrayDims = 1;
  843. UA_DataValue_deleteMembers(&value);
  844. }
  845. if(!compatibleValueRankArrayDimensions(server, session, valueRank, arrayDims))
  846. return UA_STATUSCODE_BADTYPEMISMATCH;
  847. /* All good, apply the change */
  848. node->valueRank = valueRank;
  849. return UA_STATUSCODE_GOOD;
  850. }
  851. static UA_StatusCode
  852. writeDataTypeAttribute(UA_Server *server, UA_Session *session,
  853. UA_VariableNode *node, const UA_VariableTypeNode *type,
  854. const UA_NodeId *dataType) {
  855. UA_assert(node != NULL);
  856. UA_assert(type != NULL);
  857. /* If this is a variabletype, there must be no instances or subtypes of it
  858. when we do the change */
  859. if(node->nodeClass == UA_NODECLASS_VARIABLETYPE &&
  860. UA_Node_hasSubTypeOrInstances((const UA_Node*)node))
  861. return UA_STATUSCODE_BADINTERNALERROR;
  862. /* Does the new type match the constraints of the variabletype? */
  863. if(!compatibleDataType(server, dataType, &type->dataType, false))
  864. return UA_STATUSCODE_BADTYPEMISMATCH;
  865. /* Check if the current value would match the new type */
  866. UA_DataValue value;
  867. UA_DataValue_init(&value);
  868. UA_StatusCode retval = readValueAttribute(server, session, node, &value);
  869. if(retval != UA_STATUSCODE_GOOD)
  870. return retval;
  871. if(value.hasValue) {
  872. if(!compatibleValue(server, session, dataType, node->valueRank,
  873. node->arrayDimensionsSize, node->arrayDimensions,
  874. &value.value, NULL))
  875. retval = UA_STATUSCODE_BADTYPEMISMATCH;
  876. UA_DataValue_deleteMembers(&value);
  877. if(retval != UA_STATUSCODE_GOOD) {
  878. UA_LOG_DEBUG(&server->config.logger, UA_LOGCATEGORY_SERVER,
  879. "The current value does not match the new data type");
  880. return retval;
  881. }
  882. }
  883. /* Replace the datatype nodeid */
  884. UA_NodeId dtCopy = node->dataType;
  885. retval = UA_NodeId_copy(dataType, &node->dataType);
  886. if(retval != UA_STATUSCODE_GOOD) {
  887. node->dataType = dtCopy;
  888. return retval;
  889. }
  890. UA_NodeId_deleteMembers(&dtCopy);
  891. return UA_STATUSCODE_GOOD;
  892. }
  893. static UA_StatusCode
  894. writeValueAttributeWithoutRange(UA_VariableNode *node, const UA_DataValue *value) {
  895. UA_DataValue new_value;
  896. UA_StatusCode retval = UA_DataValue_copy(value, &new_value);
  897. if(retval != UA_STATUSCODE_GOOD)
  898. return retval;
  899. UA_DataValue_deleteMembers(&node->value.data.value);
  900. node->value.data.value = new_value;
  901. return UA_STATUSCODE_GOOD;
  902. }
  903. static UA_StatusCode
  904. writeValueAttributeWithRange(UA_VariableNode *node, const UA_DataValue *value,
  905. const UA_NumericRange *rangeptr) {
  906. /* Value on both sides? */
  907. if(value->status != node->value.data.value.status ||
  908. !value->hasValue || !node->value.data.value.hasValue)
  909. return UA_STATUSCODE_BADINDEXRANGEINVALID;
  910. /* Make scalar a one-entry array for range matching */
  911. UA_Variant editableValue;
  912. const UA_Variant *v = &value->value;
  913. if(UA_Variant_isScalar(&value->value)) {
  914. editableValue = value->value;
  915. editableValue.arrayLength = 1;
  916. v = &editableValue;
  917. }
  918. /* Check that the type is an exact match and not only "compatible" */
  919. if(!node->value.data.value.value.type || !v->type ||
  920. !UA_NodeId_equal(&node->value.data.value.value.type->typeId,
  921. &v->type->typeId))
  922. return UA_STATUSCODE_BADTYPEMISMATCH;
  923. /* Write the value */
  924. UA_StatusCode retval = UA_Variant_setRangeCopy(&node->value.data.value.value,
  925. v->data, v->arrayLength, *rangeptr);
  926. if(retval != UA_STATUSCODE_GOOD)
  927. return retval;
  928. /* Write the status and timestamps */
  929. node->value.data.value.hasStatus = value->hasStatus;
  930. node->value.data.value.status = value->status;
  931. node->value.data.value.hasSourceTimestamp = value->hasSourceTimestamp;
  932. node->value.data.value.sourceTimestamp = value->sourceTimestamp;
  933. node->value.data.value.hasSourcePicoseconds = value->hasSourcePicoseconds;
  934. node->value.data.value.sourcePicoseconds = value->sourcePicoseconds;
  935. return UA_STATUSCODE_GOOD;
  936. }
  937. /* Stack layout: ... | node */
  938. static UA_StatusCode
  939. writeValueAttribute(UA_Server *server, UA_Session *session,
  940. UA_VariableNode *node, const UA_DataValue *value,
  941. const UA_String *indexRange) {
  942. UA_assert(node != NULL);
  943. /* Parse the range */
  944. UA_NumericRange range;
  945. UA_NumericRange *rangeptr = NULL;
  946. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  947. if(indexRange && indexRange->length > 0) {
  948. retval = UA_NumericRange_parseFromString(&range, indexRange);
  949. if(retval != UA_STATUSCODE_GOOD)
  950. return retval;
  951. rangeptr = &range;
  952. }
  953. /* Created an editable version. The data is not touched. Only the variant
  954. * "container". */
  955. UA_DataValue adjustedValue = *value;
  956. /* Type checking. May change the type of editableValue */
  957. if(value->hasValue && value->value.type) {
  958. adjustValue(server, &adjustedValue.value, &node->dataType);
  959. /* The value may be an extension object, especially the nodeset compiler
  960. * uses extension objects to write variable values. If value is an
  961. * extension object we check if the current node value is also an
  962. * extension object. */
  963. const UA_NodeId nodeDataType = UA_NODEID_NUMERIC(0, UA_NS0ID_STRUCTURE);
  964. const UA_NodeId *nodeDataTypePtr = &node->dataType;
  965. if(value->value.type->typeId.identifierType == UA_NODEIDTYPE_NUMERIC &&
  966. value->value.type->typeId.identifier.numeric == UA_NS0ID_STRUCTURE)
  967. nodeDataTypePtr = &nodeDataType;
  968. if(!compatibleValue(server, session, nodeDataTypePtr, node->valueRank,
  969. node->arrayDimensionsSize, node->arrayDimensions,
  970. &adjustedValue.value, rangeptr)) {
  971. if(rangeptr)
  972. UA_free(range.dimensions);
  973. return UA_STATUSCODE_BADTYPEMISMATCH;
  974. }
  975. }
  976. /* Set the source timestamp if there is none */
  977. UA_DateTime now = UA_DateTime_now();
  978. if(!adjustedValue.hasSourceTimestamp) {
  979. adjustedValue.sourceTimestamp = now;
  980. adjustedValue.hasSourceTimestamp = true;
  981. }
  982. if(!adjustedValue.hasServerTimestamp) {
  983. adjustedValue.serverTimestamp = now;
  984. adjustedValue.hasServerTimestamp = true;
  985. }
  986. /* Ok, do it */
  987. if(node->valueSource == UA_VALUESOURCE_DATA) {
  988. if(!rangeptr)
  989. retval = writeValueAttributeWithoutRange(node, &adjustedValue);
  990. else
  991. retval = writeValueAttributeWithRange(node, &adjustedValue, rangeptr);
  992. #ifdef UA_ENABLE_HISTORIZING
  993. /* node is a UA_VariableNode*, but it may also point to a UA_VariableTypeNode */
  994. /* UA_VariableTypeNode doesn't have the historizing attribute */
  995. if(retval == UA_STATUSCODE_GOOD && node->nodeClass == UA_NODECLASS_VARIABLE &&
  996. server->config.historyDatabase.setValue)
  997. server->config.historyDatabase.setValue(server, server->config.historyDatabase.context,
  998. &session->sessionId, session->sessionHandle,
  999. &node->nodeId, node->historizing, &adjustedValue);
  1000. #endif
  1001. /* Callback after writing */
  1002. if(retval == UA_STATUSCODE_GOOD && node->value.data.callback.onWrite)
  1003. node->value.data.callback.onWrite(server, &session->sessionId,
  1004. session->sessionHandle, &node->nodeId,
  1005. node->context, rangeptr,
  1006. &adjustedValue);
  1007. } else {
  1008. if(node->value.dataSource.write) {
  1009. retval = node->value.dataSource.write(server, &session->sessionId,
  1010. session->sessionHandle, &node->nodeId,
  1011. node->context, rangeptr, &adjustedValue);
  1012. } else {
  1013. retval = UA_STATUSCODE_BADWRITENOTSUPPORTED;
  1014. }
  1015. }
  1016. /* Clean up */
  1017. if(rangeptr)
  1018. UA_free(range.dimensions);
  1019. return retval;
  1020. }
  1021. static UA_StatusCode
  1022. writeIsAbstractAttribute(UA_Node *node, UA_Boolean value) {
  1023. switch(node->nodeClass) {
  1024. case UA_NODECLASS_OBJECTTYPE:
  1025. ((UA_ObjectTypeNode*)node)->isAbstract = value;
  1026. break;
  1027. case UA_NODECLASS_REFERENCETYPE:
  1028. ((UA_ReferenceTypeNode*)node)->isAbstract = value;
  1029. break;
  1030. case UA_NODECLASS_VARIABLETYPE:
  1031. ((UA_VariableTypeNode*)node)->isAbstract = value;
  1032. break;
  1033. case UA_NODECLASS_DATATYPE:
  1034. ((UA_DataTypeNode*)node)->isAbstract = value;
  1035. break;
  1036. default:
  1037. return UA_STATUSCODE_BADNODECLASSINVALID;
  1038. }
  1039. return UA_STATUSCODE_GOOD;
  1040. }
  1041. /*****************/
  1042. /* Write Service */
  1043. /*****************/
  1044. #define CHECK_DATATYPE_SCALAR(EXP_DT) \
  1045. if(!wvalue->value.hasValue || \
  1046. &UA_TYPES[UA_TYPES_##EXP_DT] != wvalue->value.value.type || \
  1047. !UA_Variant_isScalar(&wvalue->value.value)) { \
  1048. retval = UA_STATUSCODE_BADTYPEMISMATCH; \
  1049. break; \
  1050. }
  1051. #define CHECK_DATATYPE_ARRAY(EXP_DT) \
  1052. if(!wvalue->value.hasValue || \
  1053. &UA_TYPES[UA_TYPES_##EXP_DT] != wvalue->value.value.type || \
  1054. UA_Variant_isScalar(&wvalue->value.value)) { \
  1055. retval = UA_STATUSCODE_BADTYPEMISMATCH; \
  1056. break; \
  1057. }
  1058. #define CHECK_NODECLASS_WRITE(CLASS) \
  1059. if((node->nodeClass & (CLASS)) == 0) { \
  1060. retval = UA_STATUSCODE_BADNODECLASSINVALID; \
  1061. break; \
  1062. }
  1063. #define CHECK_USERWRITEMASK(mask) \
  1064. if(!(userWriteMask & (mask))) { \
  1065. retval = UA_STATUSCODE_BADUSERACCESSDENIED; \
  1066. break; \
  1067. }
  1068. #define GET_NODETYPE \
  1069. type = (const UA_VariableTypeNode*) \
  1070. getNodeType(server, node); \
  1071. if(!type) { \
  1072. retval = UA_STATUSCODE_BADTYPEMISMATCH; \
  1073. break; \
  1074. }
  1075. /* This function implements the main part of the write service and operates on a
  1076. copy of the node (not in single-threaded mode). */
  1077. static UA_StatusCode
  1078. copyAttributeIntoNode(UA_Server *server, UA_Session *session,
  1079. UA_Node *node, const UA_WriteValue *wvalue) {
  1080. const void *value = wvalue->value.value.data;
  1081. UA_UInt32 userWriteMask = getUserWriteMask(server, session, node);
  1082. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  1083. const UA_VariableTypeNode *type;
  1084. switch(wvalue->attributeId) {
  1085. case UA_ATTRIBUTEID_NODEID:
  1086. case UA_ATTRIBUTEID_NODECLASS:
  1087. case UA_ATTRIBUTEID_USERWRITEMASK:
  1088. case UA_ATTRIBUTEID_USERACCESSLEVEL:
  1089. case UA_ATTRIBUTEID_USEREXECUTABLE:
  1090. retval = UA_STATUSCODE_BADWRITENOTSUPPORTED;
  1091. break;
  1092. case UA_ATTRIBUTEID_BROWSENAME:
  1093. CHECK_USERWRITEMASK(UA_WRITEMASK_BROWSENAME);
  1094. CHECK_DATATYPE_SCALAR(QUALIFIEDNAME);
  1095. UA_QualifiedName_deleteMembers(&node->browseName);
  1096. UA_QualifiedName_copy((const UA_QualifiedName *)value, &node->browseName);
  1097. break;
  1098. case UA_ATTRIBUTEID_DISPLAYNAME:
  1099. CHECK_USERWRITEMASK(UA_WRITEMASK_DISPLAYNAME);
  1100. CHECK_DATATYPE_SCALAR(LOCALIZEDTEXT);
  1101. UA_LocalizedText_deleteMembers(&node->displayName);
  1102. UA_LocalizedText_copy((const UA_LocalizedText *)value, &node->displayName);
  1103. break;
  1104. case UA_ATTRIBUTEID_DESCRIPTION:
  1105. CHECK_USERWRITEMASK(UA_WRITEMASK_DESCRIPTION);
  1106. CHECK_DATATYPE_SCALAR(LOCALIZEDTEXT);
  1107. UA_LocalizedText_deleteMembers(&node->description);
  1108. UA_LocalizedText_copy((const UA_LocalizedText *)value, &node->description);
  1109. break;
  1110. case UA_ATTRIBUTEID_WRITEMASK:
  1111. CHECK_USERWRITEMASK(UA_WRITEMASK_WRITEMASK);
  1112. CHECK_DATATYPE_SCALAR(UINT32);
  1113. node->writeMask = *(const UA_UInt32*)value;
  1114. break;
  1115. case UA_ATTRIBUTEID_ISABSTRACT:
  1116. CHECK_USERWRITEMASK(UA_WRITEMASK_ISABSTRACT);
  1117. CHECK_DATATYPE_SCALAR(BOOLEAN);
  1118. retval = writeIsAbstractAttribute(node, *(const UA_Boolean*)value);
  1119. break;
  1120. case UA_ATTRIBUTEID_SYMMETRIC:
  1121. CHECK_NODECLASS_WRITE(UA_NODECLASS_REFERENCETYPE);
  1122. CHECK_USERWRITEMASK(UA_WRITEMASK_SYMMETRIC);
  1123. CHECK_DATATYPE_SCALAR(BOOLEAN);
  1124. ((UA_ReferenceTypeNode*)node)->symmetric = *(const UA_Boolean*)value;
  1125. break;
  1126. case UA_ATTRIBUTEID_INVERSENAME:
  1127. CHECK_NODECLASS_WRITE(UA_NODECLASS_REFERENCETYPE);
  1128. CHECK_USERWRITEMASK(UA_WRITEMASK_INVERSENAME);
  1129. CHECK_DATATYPE_SCALAR(LOCALIZEDTEXT);
  1130. UA_LocalizedText_deleteMembers(&((UA_ReferenceTypeNode*)node)->inverseName);
  1131. UA_LocalizedText_copy((const UA_LocalizedText *)value,
  1132. &((UA_ReferenceTypeNode*)node)->inverseName);
  1133. break;
  1134. case UA_ATTRIBUTEID_CONTAINSNOLOOPS:
  1135. CHECK_NODECLASS_WRITE(UA_NODECLASS_VIEW);
  1136. CHECK_USERWRITEMASK(UA_WRITEMASK_CONTAINSNOLOOPS);
  1137. CHECK_DATATYPE_SCALAR(BOOLEAN);
  1138. ((UA_ViewNode*)node)->containsNoLoops = *(const UA_Boolean*)value;
  1139. break;
  1140. case UA_ATTRIBUTEID_EVENTNOTIFIER:
  1141. CHECK_NODECLASS_WRITE(UA_NODECLASS_VIEW | UA_NODECLASS_OBJECT);
  1142. CHECK_USERWRITEMASK(UA_WRITEMASK_EVENTNOTIFIER);
  1143. CHECK_DATATYPE_SCALAR(BYTE);
  1144. ((UA_ViewNode*)node)->eventNotifier = *(const UA_Byte*)value;
  1145. break;
  1146. case UA_ATTRIBUTEID_VALUE:
  1147. CHECK_NODECLASS_WRITE(UA_NODECLASS_VARIABLE | UA_NODECLASS_VARIABLETYPE);
  1148. if(node->nodeClass == UA_NODECLASS_VARIABLE) {
  1149. /* The access to a value variable is granted via the AccessLevel
  1150. * and UserAccessLevel attributes */
  1151. UA_Byte accessLevel = getAccessLevel(server, session, (const UA_VariableNode*)node);
  1152. if(!(accessLevel & (UA_ACCESSLEVELMASK_WRITE))) {
  1153. retval = UA_STATUSCODE_BADNOTWRITABLE;
  1154. break;
  1155. }
  1156. accessLevel = getUserAccessLevel(server, session,
  1157. (const UA_VariableNode*)node);
  1158. if(!(accessLevel & (UA_ACCESSLEVELMASK_WRITE))) {
  1159. retval = UA_STATUSCODE_BADUSERACCESSDENIED;
  1160. break;
  1161. }
  1162. } else { /* UA_NODECLASS_VARIABLETYPE */
  1163. CHECK_USERWRITEMASK(UA_WRITEMASK_VALUEFORVARIABLETYPE);
  1164. }
  1165. retval = writeValueAttribute(server, session, (UA_VariableNode*)node,
  1166. &wvalue->value, &wvalue->indexRange);
  1167. break;
  1168. case UA_ATTRIBUTEID_DATATYPE:
  1169. CHECK_NODECLASS_WRITE(UA_NODECLASS_VARIABLE | UA_NODECLASS_VARIABLETYPE);
  1170. CHECK_USERWRITEMASK(UA_WRITEMASK_DATATYPE);
  1171. CHECK_DATATYPE_SCALAR(NODEID);
  1172. GET_NODETYPE
  1173. retval = writeDataTypeAttribute(server, session, (UA_VariableNode*)node,
  1174. type, (const UA_NodeId*)value);
  1175. UA_Nodestore_release(server, (const UA_Node*)type);
  1176. break;
  1177. case UA_ATTRIBUTEID_VALUERANK:
  1178. CHECK_NODECLASS_WRITE(UA_NODECLASS_VARIABLE | UA_NODECLASS_VARIABLETYPE);
  1179. CHECK_USERWRITEMASK(UA_WRITEMASK_VALUERANK);
  1180. CHECK_DATATYPE_SCALAR(INT32);
  1181. GET_NODETYPE
  1182. retval = writeValueRankAttribute(server, session, (UA_VariableNode*)node,
  1183. type, *(const UA_Int32*)value);
  1184. UA_Nodestore_release(server, (const UA_Node*)type);
  1185. break;
  1186. case UA_ATTRIBUTEID_ARRAYDIMENSIONS:
  1187. CHECK_NODECLASS_WRITE(UA_NODECLASS_VARIABLE | UA_NODECLASS_VARIABLETYPE);
  1188. CHECK_USERWRITEMASK(UA_WRITEMASK_ARRRAYDIMENSIONS);
  1189. CHECK_DATATYPE_ARRAY(UINT32);
  1190. GET_NODETYPE
  1191. retval = writeArrayDimensionsAttribute(server, session, (UA_VariableNode*)node,
  1192. type, wvalue->value.value.arrayLength,
  1193. (UA_UInt32 *)wvalue->value.value.data);
  1194. UA_Nodestore_release(server, (const UA_Node*)type);
  1195. break;
  1196. case UA_ATTRIBUTEID_ACCESSLEVEL:
  1197. CHECK_NODECLASS_WRITE(UA_NODECLASS_VARIABLE);
  1198. CHECK_USERWRITEMASK(UA_WRITEMASK_ACCESSLEVEL);
  1199. CHECK_DATATYPE_SCALAR(BYTE);
  1200. ((UA_VariableNode*)node)->accessLevel = *(const UA_Byte*)value;
  1201. break;
  1202. case UA_ATTRIBUTEID_MINIMUMSAMPLINGINTERVAL:
  1203. CHECK_NODECLASS_WRITE(UA_NODECLASS_VARIABLE);
  1204. CHECK_USERWRITEMASK(UA_WRITEMASK_MINIMUMSAMPLINGINTERVAL);
  1205. CHECK_DATATYPE_SCALAR(DOUBLE);
  1206. ((UA_VariableNode*)node)->minimumSamplingInterval = *(const UA_Double*)value;
  1207. break;
  1208. case UA_ATTRIBUTEID_HISTORIZING:
  1209. CHECK_NODECLASS_WRITE(UA_NODECLASS_VARIABLE);
  1210. CHECK_USERWRITEMASK(UA_WRITEMASK_HISTORIZING);
  1211. CHECK_DATATYPE_SCALAR(BOOLEAN);
  1212. ((UA_VariableNode*)node)->historizing = *(const UA_Boolean*)value;
  1213. break;
  1214. case UA_ATTRIBUTEID_EXECUTABLE:
  1215. CHECK_NODECLASS_WRITE(UA_NODECLASS_METHOD);
  1216. CHECK_USERWRITEMASK(UA_WRITEMASK_EXECUTABLE);
  1217. CHECK_DATATYPE_SCALAR(BOOLEAN);
  1218. ((UA_MethodNode*)node)->executable = *(const UA_Boolean*)value;
  1219. break;
  1220. default:
  1221. retval = UA_STATUSCODE_BADATTRIBUTEIDINVALID;
  1222. break;
  1223. }
  1224. if(retval != UA_STATUSCODE_GOOD)
  1225. UA_LOG_INFO_SESSION(&server->config.logger, session,
  1226. "WriteRequest returned status code %s",
  1227. UA_StatusCode_name(retval));
  1228. return retval;
  1229. }
  1230. static void
  1231. Operation_Write(UA_Server *server, UA_Session *session, void *context,
  1232. UA_WriteValue *wv, UA_StatusCode *result) {
  1233. *result = UA_Server_editNode(server, session, &wv->nodeId,
  1234. (UA_EditNodeCallback)copyAttributeIntoNode, wv);
  1235. }
  1236. void
  1237. Service_Write(UA_Server *server, UA_Session *session,
  1238. const UA_WriteRequest *request,
  1239. UA_WriteResponse *response) {
  1240. UA_LOG_DEBUG_SESSION(&server->config.logger, session,
  1241. "Processing WriteRequest");
  1242. if(server->config.maxNodesPerWrite != 0 &&
  1243. request->nodesToWriteSize > server->config.maxNodesPerWrite) {
  1244. response->responseHeader.serviceResult = UA_STATUSCODE_BADTOOMANYOPERATIONS;
  1245. return;
  1246. }
  1247. response->responseHeader.serviceResult =
  1248. UA_Server_processServiceOperations(server, session, (UA_ServiceOperation)Operation_Write, NULL,
  1249. &request->nodesToWriteSize, &UA_TYPES[UA_TYPES_WRITEVALUE],
  1250. &response->resultsSize, &UA_TYPES[UA_TYPES_STATUSCODE]);
  1251. }
  1252. UA_StatusCode
  1253. UA_Server_writeWithSession(UA_Server *server, UA_Session *session,
  1254. const UA_WriteValue *value) {
  1255. return UA_Server_editNode(server, session, &value->nodeId,
  1256. (UA_EditNodeCallback)copyAttributeIntoNode,
  1257. /* casting away const qualifier because callback uses const anyway */
  1258. (UA_WriteValue *)(uintptr_t)value);
  1259. }
  1260. UA_StatusCode
  1261. UA_Server_write(UA_Server *server, const UA_WriteValue *value) {
  1262. return UA_Server_editNode(server, &server->adminSession, &value->nodeId,
  1263. (UA_EditNodeCallback)copyAttributeIntoNode,
  1264. /* casting away const qualifier because callback uses const anyway */
  1265. (UA_WriteValue *)(uintptr_t)value);
  1266. }
  1267. /* Convenience function to be wrapped into inline functions */
  1268. UA_StatusCode
  1269. __UA_Server_write(UA_Server *server, const UA_NodeId *nodeId,
  1270. const UA_AttributeId attributeId,
  1271. const UA_DataType *attr_type,
  1272. const void *attr) {
  1273. UA_WriteValue wvalue;
  1274. UA_WriteValue_init(&wvalue);
  1275. wvalue.nodeId = *nodeId;
  1276. wvalue.attributeId = attributeId;
  1277. wvalue.value.hasValue = true;
  1278. if(attr_type != &UA_TYPES[UA_TYPES_VARIANT]) {
  1279. /* hacked cast. the target WriteValue is used as const anyway */
  1280. UA_Variant_setScalar(&wvalue.value.value,
  1281. (void*)(uintptr_t)attr, attr_type);
  1282. } else {
  1283. wvalue.value.value = *(const UA_Variant*)attr;
  1284. }
  1285. return UA_Server_write(server, &wvalue);
  1286. }
  1287. #ifdef UA_ENABLE_HISTORIZING
  1288. void
  1289. Service_HistoryRead(UA_Server *server, UA_Session *session,
  1290. const UA_HistoryReadRequest *request,
  1291. UA_HistoryReadResponse *response) {
  1292. if(request->historyReadDetails.encoding != UA_EXTENSIONOBJECT_DECODED) {
  1293. response->responseHeader.serviceResult = UA_STATUSCODE_BADNOTSUPPORTED;
  1294. return;
  1295. }
  1296. if(request->historyReadDetails.content.decoded.type != &UA_TYPES[UA_TYPES_READRAWMODIFIEDDETAILS]) {
  1297. /* TODO handle more request->historyReadDetails.content.decoded.type types */
  1298. response->responseHeader.serviceResult = UA_STATUSCODE_BADHISTORYOPERATIONUNSUPPORTED;
  1299. return;
  1300. }
  1301. /* History read with ReadRawModifiedDetails */
  1302. UA_ReadRawModifiedDetails * details = (UA_ReadRawModifiedDetails*)
  1303. request->historyReadDetails.content.decoded.data;
  1304. if(details->isReadModified) {
  1305. // TODO add server->config.historyReadService.read_modified
  1306. response->responseHeader.serviceResult = UA_STATUSCODE_BADHISTORYOPERATIONUNSUPPORTED;
  1307. return;
  1308. }
  1309. /* Something to do? */
  1310. if(request->nodesToReadSize == 0) {
  1311. response->responseHeader.serviceResult = UA_STATUSCODE_BADNOTHINGTODO;
  1312. return;
  1313. }
  1314. /* Check if there are too many operations */
  1315. if(server->config.maxNodesPerRead != 0 &&
  1316. request->nodesToReadSize > server->config.maxNodesPerRead) {
  1317. response->responseHeader.serviceResult = UA_STATUSCODE_BADTOOMANYOPERATIONS;
  1318. return;
  1319. }
  1320. /* The history database is not configured */
  1321. if(!server->config.historyDatabase.readRaw) {
  1322. response->responseHeader.serviceResult = UA_STATUSCODE_BADHISTORYOPERATIONUNSUPPORTED;
  1323. return;
  1324. }
  1325. /* Allocate a temporary array to forward the result pointers to the
  1326. * backend */
  1327. UA_HistoryData ** historyData = (UA_HistoryData **)
  1328. UA_calloc(request->nodesToReadSize, sizeof(UA_HistoryData*));
  1329. if(!historyData) {
  1330. response->responseHeader.serviceResult = UA_STATUSCODE_BADOUTOFMEMORY;
  1331. return;
  1332. }
  1333. /* Allocate the results array */
  1334. response->results = (UA_HistoryReadResult*)UA_Array_new(request->nodesToReadSize,
  1335. &UA_TYPES[UA_TYPES_HISTORYREADRESULT]);
  1336. if(!response->results) {
  1337. UA_free(historyData);
  1338. response->responseHeader.serviceResult = UA_STATUSCODE_BADOUTOFMEMORY;
  1339. return;
  1340. }
  1341. response->resultsSize = request->nodesToReadSize;
  1342. for(size_t i = 0; i < response->resultsSize; ++i) {
  1343. UA_HistoryData * data = UA_HistoryData_new();
  1344. response->results[i].historyData.encoding = UA_EXTENSIONOBJECT_DECODED;
  1345. response->results[i].historyData.content.decoded.type = &UA_TYPES[UA_TYPES_HISTORYDATA];
  1346. response->results[i].historyData.content.decoded.data = data;
  1347. historyData[i] = data;
  1348. }
  1349. server->config.historyDatabase.readRaw(server, server->config.historyDatabase.context,
  1350. &session->sessionId, session->sessionHandle,
  1351. &request->requestHeader, details,
  1352. request->timestampsToReturn,
  1353. request->releaseContinuationPoints,
  1354. request->nodesToReadSize, request->nodesToRead,
  1355. response, historyData);
  1356. UA_free(historyData);
  1357. }
  1358. #endif
  1359. UA_StatusCode UA_EXPORT
  1360. UA_Server_writeObjectProperty(UA_Server *server, const UA_NodeId objectId,
  1361. const UA_QualifiedName propertyName,
  1362. const UA_Variant value) {
  1363. UA_RelativePathElement rpe;
  1364. UA_RelativePathElement_init(&rpe);
  1365. rpe.referenceTypeId = UA_NODEID_NUMERIC(0, UA_NS0ID_HASPROPERTY);
  1366. rpe.isInverse = false;
  1367. rpe.includeSubtypes = false;
  1368. rpe.targetName = propertyName;
  1369. UA_BrowsePath bp;
  1370. UA_BrowsePath_init(&bp);
  1371. bp.startingNode = objectId;
  1372. bp.relativePath.elementsSize = 1;
  1373. bp.relativePath.elements = &rpe;
  1374. UA_StatusCode retval;
  1375. UA_BrowsePathResult bpr = UA_Server_translateBrowsePathToNodeIds(server, &bp);
  1376. if(bpr.statusCode != UA_STATUSCODE_GOOD || bpr.targetsSize < 1) {
  1377. retval = bpr.statusCode;
  1378. UA_BrowsePathResult_deleteMembers(&bpr);
  1379. return retval;
  1380. }
  1381. retval = UA_Server_writeValue(server, bpr.targets[0].targetId.nodeId, value);
  1382. UA_BrowsePathResult_deleteMembers(&bpr);
  1383. return retval;
  1384. }
  1385. UA_StatusCode UA_EXPORT
  1386. UA_Server_writeObjectProperty_scalar(UA_Server *server, const UA_NodeId objectId,
  1387. const UA_QualifiedName propertyName,
  1388. const void *value, const UA_DataType *type) {
  1389. UA_Variant var;
  1390. UA_Variant_init(&var);
  1391. UA_Variant_setScalar(&var, (void*)(uintptr_t)value, type);
  1392. return UA_Server_writeObjectProperty(server, objectId, propertyName, var);
  1393. }