ua_services_attribute.c 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607
  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 <open62541/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_getNode(server->nsCtx, &vn->nodeId);
  116. UA_Nodestore_releaseNode(server->nsCtx, 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 = &range;
  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. } else {
  339. /* In case the ServerTimestamp has been set manually */
  340. v->hasServerTimestamp = false;
  341. }
  342. /* Handle source time stamp */
  343. if(id->attributeId == UA_ATTRIBUTEID_VALUE) {
  344. if(timestampsToReturn == UA_TIMESTAMPSTORETURN_SERVER ||
  345. timestampsToReturn == UA_TIMESTAMPSTORETURN_NEITHER) {
  346. v->hasSourceTimestamp = false;
  347. v->hasSourcePicoseconds = false;
  348. } else if(!v->hasSourceTimestamp) {
  349. v->sourceTimestamp = UA_DateTime_now();
  350. v->hasSourceTimestamp = true;
  351. }
  352. }
  353. }
  354. static UA_StatusCode
  355. Operation_Read(UA_Server *server, UA_Session *session, UA_MessageContext *mc,
  356. UA_TimestampsToReturn timestampsToReturn, const UA_ReadValueId *id) {
  357. UA_DataValue dv;
  358. UA_DataValue_init(&dv);
  359. /* Get the node */
  360. const UA_Node *node = UA_Nodestore_getNode(server->nsCtx, &id->nodeId);
  361. /* Perform the read operation */
  362. if(node) {
  363. ReadWithNode(node, server, session, timestampsToReturn, id, &dv);
  364. } else {
  365. dv.hasStatus = true;
  366. dv.status = UA_STATUSCODE_BADNODEIDUNKNOWN;
  367. }
  368. /* Encode (and send) the results */
  369. UA_StatusCode retval = UA_MessageContext_encode(mc, &dv, &UA_TYPES[UA_TYPES_DATAVALUE]);
  370. /* Free copied data and release the node */
  371. UA_Variant_deleteMembers(&dv.value);
  372. UA_Nodestore_releaseNode(server->nsCtx, node);
  373. return retval;
  374. }
  375. UA_StatusCode Service_Read(UA_Server *server, UA_Session *session, UA_MessageContext *mc,
  376. const UA_ReadRequest *request, UA_ResponseHeader *responseHeader) {
  377. UA_LOG_DEBUG_SESSION(&server->config.logger, session,
  378. "Processing ReadRequest");
  379. /* Check if the timestampstoreturn is valid */
  380. if(request->timestampsToReturn > UA_TIMESTAMPSTORETURN_NEITHER)
  381. responseHeader->serviceResult = UA_STATUSCODE_BADTIMESTAMPSTORETURNINVALID;
  382. if(request->nodesToReadSize == 0)
  383. responseHeader->serviceResult = UA_STATUSCODE_BADNOTHINGTODO;
  384. /* Check if maxAge is valid */
  385. if(request->maxAge < 0)
  386. responseHeader->serviceResult = UA_STATUSCODE_BADMAXAGEINVALID;
  387. /* Check if there are too many operations */
  388. if(server->config.maxNodesPerRead != 0 &&
  389. request->nodesToReadSize > server->config.maxNodesPerRead)
  390. responseHeader->serviceResult = UA_STATUSCODE_BADTOOMANYOPERATIONS;
  391. /* Encode the response header */
  392. UA_StatusCode retval =
  393. UA_MessageContext_encode(mc, responseHeader, &UA_TYPES[UA_TYPES_RESPONSEHEADER]);
  394. if(retval != UA_STATUSCODE_GOOD)
  395. return retval;
  396. /* Process nothing if we return an error code for the entire service */
  397. UA_Int32 arraySize = (UA_Int32)request->nodesToReadSize;
  398. if(responseHeader->serviceResult != UA_STATUSCODE_GOOD)
  399. arraySize = 0;
  400. /* Process all ReadValueIds */
  401. retval = UA_MessageContext_encode(mc, &arraySize, &UA_TYPES[UA_TYPES_INT32]);
  402. if(retval != UA_STATUSCODE_GOOD)
  403. return retval;
  404. for(UA_Int32 i = 0; i < arraySize; i++) {
  405. retval = Operation_Read(server, session, mc, request->timestampsToReturn,
  406. &request->nodesToRead[i]);
  407. if(retval != UA_STATUSCODE_GOOD)
  408. return retval;
  409. }
  410. /* Don't return any DiagnosticInfo */
  411. arraySize = -1;
  412. return UA_MessageContext_encode(mc, &arraySize, &UA_TYPES[UA_TYPES_INT32]);
  413. }
  414. UA_DataValue
  415. UA_Server_readWithSession(UA_Server *server, UA_Session *session,
  416. const UA_ReadValueId *item,
  417. UA_TimestampsToReturn timestampsToReturn) {
  418. UA_DataValue dv;
  419. UA_DataValue_init(&dv);
  420. /* Get the node */
  421. const UA_Node *node = UA_Nodestore_getNode(server->nsCtx, &item->nodeId);
  422. if(!node) {
  423. dv.hasStatus = true;
  424. dv.status = UA_STATUSCODE_BADNODEIDUNKNOWN;
  425. return dv;
  426. }
  427. /* Perform the read operation */
  428. ReadWithNode(node, server, session, timestampsToReturn, item, &dv);
  429. /* Do we have to copy the result before releasing the node? */
  430. if(dv.hasValue && dv.value.storageType == UA_VARIANT_DATA_NODELETE) {
  431. UA_DataValue dv2;
  432. UA_StatusCode retval = UA_DataValue_copy(&dv, &dv2);
  433. if(retval == UA_STATUSCODE_GOOD) {
  434. dv = dv2;
  435. } else {
  436. UA_DataValue_init(&dv);
  437. dv.hasStatus = true;
  438. dv.status = retval;
  439. }
  440. }
  441. /* Release the node and return */
  442. UA_Nodestore_releaseNode(server->nsCtx, node);
  443. return dv;
  444. }
  445. /* Exposes the Read service to local users */
  446. UA_DataValue
  447. UA_Server_read(UA_Server *server, const UA_ReadValueId *item,
  448. UA_TimestampsToReturn timestamps) {
  449. return UA_Server_readWithSession(server, &server->adminSession, item, timestamps);
  450. }
  451. /* Used in inline functions exposing the Read service with more syntactic sugar
  452. * for individual attributes */
  453. UA_StatusCode
  454. __UA_Server_read(UA_Server *server, const UA_NodeId *nodeId,
  455. const UA_AttributeId attributeId, void *v) {
  456. /* Call the read service */
  457. UA_ReadValueId item;
  458. UA_ReadValueId_init(&item);
  459. item.nodeId = *nodeId;
  460. item.attributeId = attributeId;
  461. UA_DataValue dv = UA_Server_read(server, &item, UA_TIMESTAMPSTORETURN_NEITHER);
  462. /* Check the return value */
  463. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  464. if(dv.hasStatus)
  465. retval = dv.status;
  466. else if(!dv.hasValue)
  467. retval = UA_STATUSCODE_BADUNEXPECTEDERROR;
  468. if(retval != UA_STATUSCODE_GOOD) {
  469. UA_DataValue_deleteMembers(&dv);
  470. return retval;
  471. }
  472. if(attributeId == UA_ATTRIBUTEID_VALUE ||
  473. attributeId == UA_ATTRIBUTEID_ARRAYDIMENSIONS) {
  474. /* Return the entire variant */
  475. memcpy(v, &dv.value, sizeof(UA_Variant));
  476. } else {
  477. /* Return the variant content only */
  478. memcpy(v, dv.value.data, dv.value.type->memSize);
  479. UA_free(dv.value.data);
  480. }
  481. return retval;
  482. }
  483. UA_StatusCode
  484. UA_Server_readObjectProperty(UA_Server *server, const UA_NodeId objectId,
  485. const UA_QualifiedName propertyName,
  486. UA_Variant *value) {
  487. UA_RelativePathElement rpe;
  488. UA_RelativePathElement_init(&rpe);
  489. rpe.referenceTypeId = UA_NODEID_NUMERIC(0, UA_NS0ID_HASPROPERTY);
  490. rpe.isInverse = false;
  491. rpe.includeSubtypes = false;
  492. rpe.targetName = propertyName;
  493. UA_BrowsePath bp;
  494. UA_BrowsePath_init(&bp);
  495. bp.startingNode = objectId;
  496. bp.relativePath.elementsSize = 1;
  497. bp.relativePath.elements = &rpe;
  498. UA_StatusCode retval;
  499. UA_BrowsePathResult bpr = UA_Server_translateBrowsePathToNodeIds(server, &bp);
  500. if(bpr.statusCode != UA_STATUSCODE_GOOD || bpr.targetsSize < 1) {
  501. retval = bpr.statusCode;
  502. UA_BrowsePathResult_deleteMembers(&bpr);
  503. return retval;
  504. }
  505. retval = UA_Server_readValue(server, bpr.targets[0].targetId.nodeId, value);
  506. UA_BrowsePathResult_deleteMembers(&bpr);
  507. return retval;
  508. }
  509. /*****************/
  510. /* Type Checking */
  511. /*****************/
  512. static UA_DataTypeKind
  513. typeEquivalence(const UA_DataType *t) {
  514. UA_DataTypeKind k = (UA_DataTypeKind)t->typeKind;
  515. if(k == UA_DATATYPEKIND_ENUM)
  516. return UA_DATATYPEKIND_INT32;
  517. return k;
  518. }
  519. static const UA_NodeId enumNodeId = {0, UA_NODEIDTYPE_NUMERIC, {UA_NS0ID_ENUMERATION}};
  520. UA_Boolean
  521. compatibleDataType(UA_Server *server, const UA_NodeId *dataType,
  522. const UA_NodeId *constraintDataType, UA_Boolean isValue) {
  523. /* Do not allow empty datatypes */
  524. if(UA_NodeId_isNull(dataType))
  525. return false;
  526. /* No constraint (TODO: use variant instead) */
  527. if(UA_NodeId_isNull(constraintDataType))
  528. return true;
  529. /* Same datatypes */
  530. if (UA_NodeId_equal(dataType, constraintDataType))
  531. return true;
  532. /* Variant allows any subtype */
  533. if(UA_NodeId_equal(constraintDataType, &UA_TYPES[UA_TYPES_VARIANT].typeId))
  534. return true;
  535. /* Is the value-type a subtype of the required type? */
  536. if(isNodeInTree(server->nsCtx, dataType, constraintDataType, &subtypeId, 1))
  537. return true;
  538. /* Enum allows Int32 (only) */
  539. if(UA_NodeId_equal(dataType, &UA_TYPES[UA_TYPES_INT32].typeId) &&
  540. isNodeInTree(server->nsCtx, constraintDataType, &enumNodeId, &subtypeId, 1))
  541. return true;
  542. /* More checks for the data type of real values (variants) */
  543. if(isValue) {
  544. /* If value is a built-in type: The target data type may be a sub type of
  545. * the built-in type. (e.g. UtcTime is sub-type of DateTime and has a
  546. * DateTime value). A type is builtin if its NodeId is in Namespace 0 and
  547. * has a numeric identifier <= 25 (DiagnosticInfo) */
  548. if(dataType->namespaceIndex == 0 &&
  549. dataType->identifierType == UA_NODEIDTYPE_NUMERIC &&
  550. dataType->identifier.numeric <= 25 &&
  551. isNodeInTree(server->nsCtx, constraintDataType,
  552. dataType, &subtypeId, 1))
  553. return true;
  554. }
  555. return false;
  556. }
  557. /* Test whether a ValueRank and the given arraydimensions are compatible.
  558. *
  559. * 5.6.2 Variable NodeClass: If the maximum is unknown the value shall be 0. The
  560. * number of elements shall be equal to the value of the ValueRank Attribute.
  561. * This Attribute shall be null if ValueRank <= 0. */
  562. UA_Boolean
  563. compatibleValueRankArrayDimensions(UA_Server *server, UA_Session *session,
  564. UA_Int32 valueRank, size_t arrayDimensionsSize) {
  565. /* ValueRank invalid */
  566. if(valueRank < UA_VALUERANK_SCALAR_OR_ONE_DIMENSION) {
  567. UA_LOG_INFO_SESSION(&server->config.logger, session,
  568. "The ValueRank is invalid (< -3)");
  569. return false;
  570. }
  571. /* case -3, UA_VALUERANK_SCALAR_OR_ONE_DIMENSION: the value can be a scalar or a one dimensional array */
  572. /* case -2, UA_VALUERANK_ANY: the value can be a scalar or an array with any number of dimensions */
  573. /* case -1, UA_VALUERANK_SCALAR: the value is a scalar */
  574. /* case 0, UA_VALUERANK_ONE_OR_MORE_DIMENSIONS: the value is an array with one or more dimensions */
  575. if(valueRank <= UA_VALUERANK_ONE_OR_MORE_DIMENSIONS) {
  576. if(arrayDimensionsSize > 0) {
  577. UA_LOG_INFO_SESSION(&server->config.logger, session,
  578. "No ArrayDimensions can be defined for a ValueRank <= 0");
  579. return false;
  580. }
  581. return true;
  582. }
  583. /* case >= 1, UA_VALUERANK_ONE_DIMENSION: the value is an array with the specified number of dimensions */
  584. if(arrayDimensionsSize != (size_t)valueRank) {
  585. UA_LOG_INFO_SESSION(&server->config.logger, session,
  586. "The number of ArrayDimensions is not equal to the (positive) ValueRank");
  587. return false;
  588. }
  589. return true;
  590. }
  591. UA_Boolean
  592. compatibleValueRanks(UA_Int32 valueRank, UA_Int32 constraintValueRank) {
  593. /* Check if the valuerank of the variabletype allows the change. */
  594. switch(constraintValueRank) {
  595. case UA_VALUERANK_SCALAR_OR_ONE_DIMENSION: /* the value can be a scalar or a one dimensional array */
  596. if(valueRank != UA_VALUERANK_SCALAR && valueRank != UA_VALUERANK_ONE_DIMENSION)
  597. return false;
  598. break;
  599. case UA_VALUERANK_ANY: /* the value can be a scalar or an array with any number of dimensions */
  600. break;
  601. case UA_VALUERANK_SCALAR: /* the value is a scalar */
  602. if(valueRank != UA_VALUERANK_SCALAR)
  603. return false;
  604. break;
  605. case UA_VALUERANK_ONE_OR_MORE_DIMENSIONS: /* the value is an array with one or more dimensions */
  606. if(valueRank < (UA_Int32) UA_VALUERANK_ONE_OR_MORE_DIMENSIONS)
  607. return false;
  608. break;
  609. default: /* >= 1: the value is an array with the specified number of dimensions */
  610. if(valueRank != constraintValueRank)
  611. return false;
  612. break;
  613. }
  614. return true;
  615. }
  616. /* Check if the ValueRank allows for the value dimension. This is more
  617. * permissive than checking for the ArrayDimensions attribute. Because the value
  618. * can have dimensions if the ValueRank < 0 */
  619. static UA_Boolean
  620. compatibleValueRankValue(UA_Int32 valueRank, const UA_Variant *value) {
  621. /* Invalid ValueRank */
  622. if(valueRank < UA_VALUERANK_SCALAR_OR_ONE_DIMENSION)
  623. return false;
  624. /* Empty arrays (-1) always match */
  625. if(!value->data)
  626. return true;
  627. size_t arrayDims = value->arrayDimensionsSize;
  628. if(arrayDims == 0 && !UA_Variant_isScalar(value))
  629. arrayDims = 1; /* array but no arraydimensions -> implicit array dimension 1 */
  630. /* We cannot simply use compatibleValueRankArrayDimensions since we can have
  631. * defined ArrayDimensions for the value if the ValueRank is -2 */
  632. switch(valueRank) {
  633. case UA_VALUERANK_SCALAR_OR_ONE_DIMENSION: /* The value can be a scalar or a one dimensional array */
  634. return (arrayDims <= 1);
  635. case UA_VALUERANK_ANY: /* The value can be a scalar or an array with any number of dimensions */
  636. return true;
  637. case UA_VALUERANK_SCALAR: /* The value is a scalar */
  638. return (arrayDims == 0);
  639. default:
  640. break;
  641. }
  642. UA_assert(valueRank >= UA_VALUERANK_ONE_OR_MORE_DIMENSIONS);
  643. /* case 0: the value is an array with one or more dimensions */
  644. return (arrayDims == (UA_UInt32)valueRank);
  645. }
  646. UA_Boolean
  647. compatibleArrayDimensions(size_t constraintArrayDimensionsSize,
  648. const UA_UInt32 *constraintArrayDimensions,
  649. size_t testArrayDimensionsSize,
  650. const UA_UInt32 *testArrayDimensions) {
  651. /* No array dimensions defined -> everything is permitted if the value rank fits */
  652. if(constraintArrayDimensionsSize == 0)
  653. return true;
  654. /* Dimension count must match */
  655. if(testArrayDimensionsSize != constraintArrayDimensionsSize)
  656. return false;
  657. /* Dimension lengths must not be larger than the constraint. Zero in the
  658. * constraint indicates a wildcard. */
  659. for(size_t i = 0; i < constraintArrayDimensionsSize; ++i) {
  660. if(constraintArrayDimensions[i] < testArrayDimensions[i] &&
  661. constraintArrayDimensions[i] != 0)
  662. return false;
  663. }
  664. return true;
  665. }
  666. UA_Boolean
  667. compatibleValueArrayDimensions(const UA_Variant *value, size_t targetArrayDimensionsSize,
  668. const UA_UInt32 *targetArrayDimensions) {
  669. size_t valueArrayDimensionsSize = value->arrayDimensionsSize;
  670. UA_UInt32 *valueArrayDimensions = value->arrayDimensions;
  671. UA_UInt32 tempArrayDimensions;
  672. if(!valueArrayDimensions && !UA_Variant_isScalar(value)) {
  673. valueArrayDimensionsSize = 1;
  674. tempArrayDimensions = (UA_UInt32)value->arrayLength;
  675. valueArrayDimensions = &tempArrayDimensions;
  676. }
  677. UA_assert(valueArrayDimensionsSize == 0 || valueArrayDimensions != NULL);
  678. return compatibleArrayDimensions(targetArrayDimensionsSize, targetArrayDimensions,
  679. valueArrayDimensionsSize, valueArrayDimensions);
  680. }
  681. UA_Boolean
  682. compatibleValue(UA_Server *server, UA_Session *session, const UA_NodeId *targetDataTypeId,
  683. UA_Int32 targetValueRank, size_t targetArrayDimensionsSize,
  684. const UA_UInt32 *targetArrayDimensions, const UA_Variant *value,
  685. const UA_NumericRange *range) {
  686. /* Empty value */
  687. if(!value->type) {
  688. /* Empty value is allowed for BaseDataType */
  689. if(UA_NodeId_equal(targetDataTypeId, &UA_TYPES[UA_TYPES_VARIANT].typeId) ||
  690. UA_NodeId_equal(targetDataTypeId, &UA_NODEID_NULL))
  691. return true;
  692. /* Allow empty node values since existing information models may have
  693. * variables with no value, e.g. OldValues - ns=0;i=3024. See also
  694. * #1889, https://github.com/open62541/open62541/pull/1889#issuecomment-403506538 */
  695. if(server->config.relaxEmptyValueConstraint) {
  696. UA_LOG_DEBUG_SESSION(&server->config.logger, session,
  697. "Only Variables with data type BaseDataType can contain an "
  698. "empty value. Allow via explicit constraint relaxation.");
  699. return true;
  700. }
  701. UA_LOG_INFO_SESSION(&server->config.logger, session,
  702. "Only Variables with data type BaseDataType can contain an empty value");
  703. return false;
  704. }
  705. /* Has the value a subtype of the required type? BaseDataType (Variant) can
  706. * be anything... */
  707. if(!compatibleDataType(server, &value->type->typeId, targetDataTypeId, true))
  708. return false;
  709. /* Array dimensions are checked later when writing the range */
  710. if(range)
  711. return true;
  712. /* See if the array dimensions match. */
  713. if(!compatibleValueArrayDimensions(value, targetArrayDimensionsSize, targetArrayDimensions))
  714. return false;
  715. /* Check if the valuerank allows for the value dimension */
  716. return compatibleValueRankValue(targetValueRank, value);
  717. }
  718. /*****************/
  719. /* Write Service */
  720. /*****************/
  721. static void
  722. adjustValue(UA_Server *server, UA_Variant *value,
  723. const UA_NodeId *targetDataTypeId) {
  724. const UA_DataType *targetDataType = UA_findDataType(targetDataTypeId);
  725. if(!targetDataType)
  726. return;
  727. /* A string is written to a byte array. the valuerank and array dimensions
  728. * are checked later */
  729. if(targetDataType == &UA_TYPES[UA_TYPES_BYTE] &&
  730. value->type == &UA_TYPES[UA_TYPES_BYTESTRING] &&
  731. UA_Variant_isScalar(value)) {
  732. UA_ByteString *str = (UA_ByteString*)value->data;
  733. value->type = &UA_TYPES[UA_TYPES_BYTE];
  734. value->arrayLength = str->length;
  735. value->data = str->data;
  736. return;
  737. }
  738. /* An enum was sent as an int32, or an opaque type as a bytestring. This
  739. * is detected with the typeIndex indicating the "true" datatype. */
  740. UA_DataTypeKind te1 = typeEquivalence(targetDataType);
  741. UA_DataTypeKind te2 = typeEquivalence(value->type);
  742. if(te1 == te2 && te1 <= UA_DATATYPEKIND_ENUM) {
  743. value->type = targetDataType;
  744. return;
  745. }
  746. /* No more possible equivalencies */
  747. }
  748. static UA_StatusCode
  749. writeArrayDimensionsAttribute(UA_Server *server, UA_Session *session,
  750. UA_VariableNode *node, const UA_VariableTypeNode *type,
  751. size_t arrayDimensionsSize, UA_UInt32 *arrayDimensions) {
  752. UA_assert(node != NULL);
  753. UA_assert(type != NULL);
  754. /* If this is a variabletype, there must be no instances or subtypes of it
  755. * when we do the change */
  756. if(node->nodeClass == UA_NODECLASS_VARIABLETYPE &&
  757. UA_Node_hasSubTypeOrInstances((UA_Node*)node)) {
  758. UA_LOG_INFO(&server->config.logger, UA_LOGCATEGORY_SERVER,
  759. "Cannot change a variable type with existing instances");
  760. return UA_STATUSCODE_BADINTERNALERROR;
  761. }
  762. /* Check that the array dimensions match with the valuerank */
  763. if(!compatibleValueRankArrayDimensions(server, session, node->valueRank, arrayDimensionsSize)) {
  764. UA_LOG_DEBUG(&server->config.logger, UA_LOGCATEGORY_SERVER,
  765. "Cannot write the ArrayDimensions. The ValueRank does not match.");
  766. return UA_STATUSCODE_BADTYPEMISMATCH;
  767. }
  768. /* Check if the array dimensions match with the wildcards in the
  769. * variabletype (dimension length 0) */
  770. if(type->arrayDimensions &&
  771. !compatibleArrayDimensions(type->arrayDimensionsSize, type->arrayDimensions,
  772. arrayDimensionsSize, arrayDimensions)) {
  773. UA_LOG_DEBUG(&server->config.logger, UA_LOGCATEGORY_SERVER,
  774. "Array dimensions in the variable type do not match");
  775. return UA_STATUSCODE_BADTYPEMISMATCH;
  776. }
  777. /* Check if the current value is compatible with the array dimensions */
  778. UA_DataValue value;
  779. UA_DataValue_init(&value);
  780. UA_StatusCode retval = readValueAttribute(server, session, node, &value);
  781. if(retval != UA_STATUSCODE_GOOD)
  782. return retval;
  783. if(value.hasValue) {
  784. if(!compatibleValueArrayDimensions(&value.value, arrayDimensionsSize, arrayDimensions))
  785. retval = UA_STATUSCODE_BADTYPEMISMATCH;
  786. UA_DataValue_deleteMembers(&value);
  787. if(retval != UA_STATUSCODE_GOOD) {
  788. UA_LOG_DEBUG(&server->config.logger, UA_LOGCATEGORY_SERVER,
  789. "Array dimensions in the current value do not match");
  790. return retval;
  791. }
  792. }
  793. /* Ok, apply */
  794. UA_UInt32 *oldArrayDimensions = node->arrayDimensions;
  795. size_t oldArrayDimensionsSize = node->arrayDimensionsSize;
  796. retval = UA_Array_copy(arrayDimensions, arrayDimensionsSize,
  797. (void**)&node->arrayDimensions,
  798. &UA_TYPES[UA_TYPES_UINT32]);
  799. if(retval != UA_STATUSCODE_GOOD)
  800. return retval;
  801. UA_Array_delete(oldArrayDimensions, oldArrayDimensionsSize, &UA_TYPES[UA_TYPES_UINT32]);
  802. node->arrayDimensionsSize = arrayDimensionsSize;
  803. return UA_STATUSCODE_GOOD;
  804. }
  805. /* Stack layout: ... | node | type */
  806. static UA_StatusCode
  807. writeValueRankAttribute(UA_Server *server, UA_Session *session,
  808. UA_VariableNode *node, const UA_VariableTypeNode *type,
  809. UA_Int32 valueRank) {
  810. UA_assert(node != NULL);
  811. UA_assert(type != NULL);
  812. UA_Int32 constraintValueRank = type->valueRank;
  813. /* If this is a variabletype, there must be no instances or subtypes of it
  814. * when we do the change */
  815. if(node->nodeClass == UA_NODECLASS_VARIABLETYPE &&
  816. UA_Node_hasSubTypeOrInstances((const UA_Node*)node))
  817. return UA_STATUSCODE_BADINTERNALERROR;
  818. /* Check if the valuerank of the variabletype allows the change. */
  819. if(!compatibleValueRanks(valueRank, constraintValueRank))
  820. return UA_STATUSCODE_BADTYPEMISMATCH;
  821. /* Check if the new valuerank is compatible with the array dimensions. Use
  822. * the read service to handle data sources. */
  823. size_t arrayDims = node->arrayDimensionsSize;
  824. if(arrayDims == 0) {
  825. /* the value could be an array with no arrayDimensions defined.
  826. dimensions zero indicate a scalar for compatibleValueRankArrayDimensions. */
  827. UA_DataValue value;
  828. UA_DataValue_init(&value);
  829. UA_StatusCode retval = readValueAttribute(server, session, node, &value);
  830. if(retval != UA_STATUSCODE_GOOD)
  831. return retval;
  832. if(!value.hasValue || !value.value.type) {
  833. /* no value -> apply */
  834. node->valueRank = valueRank;
  835. return UA_STATUSCODE_GOOD;
  836. }
  837. if(!UA_Variant_isScalar(&value.value))
  838. arrayDims = 1;
  839. UA_DataValue_deleteMembers(&value);
  840. }
  841. if(!compatibleValueRankArrayDimensions(server, session, valueRank, arrayDims))
  842. return UA_STATUSCODE_BADTYPEMISMATCH;
  843. /* All good, apply the change */
  844. node->valueRank = valueRank;
  845. return UA_STATUSCODE_GOOD;
  846. }
  847. static UA_StatusCode
  848. writeDataTypeAttribute(UA_Server *server, UA_Session *session,
  849. UA_VariableNode *node, const UA_VariableTypeNode *type,
  850. const UA_NodeId *dataType) {
  851. UA_assert(node != NULL);
  852. UA_assert(type != NULL);
  853. /* If this is a variabletype, there must be no instances or subtypes of it
  854. when we do the change */
  855. if(node->nodeClass == UA_NODECLASS_VARIABLETYPE &&
  856. UA_Node_hasSubTypeOrInstances((const UA_Node*)node))
  857. return UA_STATUSCODE_BADINTERNALERROR;
  858. /* Does the new type match the constraints of the variabletype? */
  859. if(!compatibleDataType(server, dataType, &type->dataType, false))
  860. return UA_STATUSCODE_BADTYPEMISMATCH;
  861. /* Check if the current value would match the new type */
  862. UA_DataValue value;
  863. UA_DataValue_init(&value);
  864. UA_StatusCode retval = readValueAttribute(server, session, node, &value);
  865. if(retval != UA_STATUSCODE_GOOD)
  866. return retval;
  867. if(value.hasValue) {
  868. if(!compatibleValue(server, session, dataType, node->valueRank,
  869. node->arrayDimensionsSize, node->arrayDimensions,
  870. &value.value, NULL))
  871. retval = UA_STATUSCODE_BADTYPEMISMATCH;
  872. UA_DataValue_deleteMembers(&value);
  873. if(retval != UA_STATUSCODE_GOOD) {
  874. UA_LOG_DEBUG(&server->config.logger, UA_LOGCATEGORY_SERVER,
  875. "The current value does not match the new data type");
  876. return retval;
  877. }
  878. }
  879. /* Replace the datatype nodeid */
  880. UA_NodeId dtCopy = node->dataType;
  881. retval = UA_NodeId_copy(dataType, &node->dataType);
  882. if(retval != UA_STATUSCODE_GOOD) {
  883. node->dataType = dtCopy;
  884. return retval;
  885. }
  886. UA_NodeId_deleteMembers(&dtCopy);
  887. return UA_STATUSCODE_GOOD;
  888. }
  889. static UA_StatusCode
  890. writeValueAttributeWithoutRange(UA_VariableNode *node, const UA_DataValue *value) {
  891. UA_DataValue new_value;
  892. UA_StatusCode retval = UA_DataValue_copy(value, &new_value);
  893. if(retval != UA_STATUSCODE_GOOD)
  894. return retval;
  895. UA_DataValue_deleteMembers(&node->value.data.value);
  896. node->value.data.value = new_value;
  897. return UA_STATUSCODE_GOOD;
  898. }
  899. static UA_StatusCode
  900. writeValueAttributeWithRange(UA_VariableNode *node, const UA_DataValue *value,
  901. const UA_NumericRange *rangeptr) {
  902. /* Value on both sides? */
  903. if(value->status != node->value.data.value.status ||
  904. !value->hasValue || !node->value.data.value.hasValue)
  905. return UA_STATUSCODE_BADINDEXRANGEINVALID;
  906. /* Make scalar a one-entry array for range matching */
  907. UA_Variant editableValue;
  908. const UA_Variant *v = &value->value;
  909. if(UA_Variant_isScalar(&value->value)) {
  910. editableValue = value->value;
  911. editableValue.arrayLength = 1;
  912. v = &editableValue;
  913. }
  914. /* Check that the type is an exact match and not only "compatible" */
  915. if(!node->value.data.value.value.type || !v->type ||
  916. !UA_NodeId_equal(&node->value.data.value.value.type->typeId,
  917. &v->type->typeId))
  918. return UA_STATUSCODE_BADTYPEMISMATCH;
  919. /* Write the value */
  920. UA_StatusCode retval = UA_Variant_setRangeCopy(&node->value.data.value.value,
  921. v->data, v->arrayLength, *rangeptr);
  922. if(retval != UA_STATUSCODE_GOOD)
  923. return retval;
  924. /* Write the status and timestamps */
  925. node->value.data.value.hasStatus = value->hasStatus;
  926. node->value.data.value.status = value->status;
  927. node->value.data.value.hasSourceTimestamp = value->hasSourceTimestamp;
  928. node->value.data.value.sourceTimestamp = value->sourceTimestamp;
  929. node->value.data.value.hasSourcePicoseconds = value->hasSourcePicoseconds;
  930. node->value.data.value.sourcePicoseconds = value->sourcePicoseconds;
  931. return UA_STATUSCODE_GOOD;
  932. }
  933. /* Stack layout: ... | node */
  934. static UA_StatusCode
  935. writeValueAttribute(UA_Server *server, UA_Session *session,
  936. UA_VariableNode *node, const UA_DataValue *value,
  937. const UA_String *indexRange) {
  938. UA_assert(node != NULL);
  939. /* Parse the range */
  940. UA_NumericRange range;
  941. UA_NumericRange *rangeptr = NULL;
  942. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  943. if(indexRange && indexRange->length > 0) {
  944. retval = UA_NumericRange_parseFromString(&range, indexRange);
  945. if(retval != UA_STATUSCODE_GOOD)
  946. return retval;
  947. rangeptr = &range;
  948. }
  949. /* Created an editable version. The data is not touched. Only the variant
  950. * "container". */
  951. UA_DataValue adjustedValue = *value;
  952. /* Type checking. May change the type of editableValue */
  953. if(value->hasValue && value->value.type) {
  954. adjustValue(server, &adjustedValue.value, &node->dataType);
  955. /* The value may be an extension object, especially the nodeset compiler
  956. * uses extension objects to write variable values. If value is an
  957. * extension object we check if the current node value is also an
  958. * extension object. */
  959. const UA_NodeId nodeDataType = UA_NODEID_NUMERIC(0, UA_NS0ID_STRUCTURE);
  960. const UA_NodeId *nodeDataTypePtr = &node->dataType;
  961. if(value->value.type->typeId.identifierType == UA_NODEIDTYPE_NUMERIC &&
  962. value->value.type->typeId.identifier.numeric == UA_NS0ID_STRUCTURE)
  963. nodeDataTypePtr = &nodeDataType;
  964. if(!compatibleValue(server, session, nodeDataTypePtr, node->valueRank,
  965. node->arrayDimensionsSize, node->arrayDimensions,
  966. &adjustedValue.value, rangeptr)) {
  967. if(rangeptr)
  968. UA_free(range.dimensions);
  969. return UA_STATUSCODE_BADTYPEMISMATCH;
  970. }
  971. }
  972. /* Set the source timestamp if there is none */
  973. UA_DateTime now = UA_DateTime_now();
  974. if(!adjustedValue.hasSourceTimestamp) {
  975. adjustedValue.sourceTimestamp = now;
  976. adjustedValue.hasSourceTimestamp = true;
  977. }
  978. if(!adjustedValue.hasServerTimestamp) {
  979. adjustedValue.serverTimestamp = now;
  980. adjustedValue.hasServerTimestamp = true;
  981. }
  982. /* Ok, do it */
  983. if(node->valueSource == UA_VALUESOURCE_DATA) {
  984. if(!rangeptr)
  985. retval = writeValueAttributeWithoutRange(node, &adjustedValue);
  986. else
  987. retval = writeValueAttributeWithRange(node, &adjustedValue, rangeptr);
  988. #ifdef UA_ENABLE_HISTORIZING
  989. /* node is a UA_VariableNode*, but it may also point to a UA_VariableTypeNode */
  990. /* UA_VariableTypeNode doesn't have the historizing attribute */
  991. if(retval == UA_STATUSCODE_GOOD && node->nodeClass == UA_NODECLASS_VARIABLE &&
  992. server->config.historyDatabase.setValue)
  993. server->config.historyDatabase.setValue(server, server->config.historyDatabase.context,
  994. &session->sessionId, session->sessionHandle,
  995. &node->nodeId, node->historizing, &adjustedValue);
  996. #endif
  997. /* Callback after writing */
  998. if(retval == UA_STATUSCODE_GOOD && node->value.data.callback.onWrite)
  999. node->value.data.callback.onWrite(server, &session->sessionId,
  1000. session->sessionHandle, &node->nodeId,
  1001. node->context, rangeptr,
  1002. &adjustedValue);
  1003. } else {
  1004. if(node->value.dataSource.write) {
  1005. retval = node->value.dataSource.write(server, &session->sessionId,
  1006. session->sessionHandle, &node->nodeId,
  1007. node->context, rangeptr, &adjustedValue);
  1008. } else {
  1009. retval = UA_STATUSCODE_BADWRITENOTSUPPORTED;
  1010. }
  1011. }
  1012. /* Clean up */
  1013. if(rangeptr)
  1014. UA_free(range.dimensions);
  1015. return retval;
  1016. }
  1017. static UA_StatusCode
  1018. writeIsAbstractAttribute(UA_Node *node, UA_Boolean value) {
  1019. switch(node->nodeClass) {
  1020. case UA_NODECLASS_OBJECTTYPE:
  1021. ((UA_ObjectTypeNode*)node)->isAbstract = value;
  1022. break;
  1023. case UA_NODECLASS_REFERENCETYPE:
  1024. ((UA_ReferenceTypeNode*)node)->isAbstract = value;
  1025. break;
  1026. case UA_NODECLASS_VARIABLETYPE:
  1027. ((UA_VariableTypeNode*)node)->isAbstract = value;
  1028. break;
  1029. case UA_NODECLASS_DATATYPE:
  1030. ((UA_DataTypeNode*)node)->isAbstract = value;
  1031. break;
  1032. default:
  1033. return UA_STATUSCODE_BADNODECLASSINVALID;
  1034. }
  1035. return UA_STATUSCODE_GOOD;
  1036. }
  1037. /*****************/
  1038. /* Write Service */
  1039. /*****************/
  1040. #define CHECK_DATATYPE_SCALAR(EXP_DT) \
  1041. if(!wvalue->value.hasValue || \
  1042. &UA_TYPES[UA_TYPES_##EXP_DT] != wvalue->value.value.type || \
  1043. !UA_Variant_isScalar(&wvalue->value.value)) { \
  1044. retval = UA_STATUSCODE_BADTYPEMISMATCH; \
  1045. break; \
  1046. }
  1047. #define CHECK_DATATYPE_ARRAY(EXP_DT) \
  1048. if(!wvalue->value.hasValue || \
  1049. &UA_TYPES[UA_TYPES_##EXP_DT] != wvalue->value.value.type || \
  1050. UA_Variant_isScalar(&wvalue->value.value)) { \
  1051. retval = UA_STATUSCODE_BADTYPEMISMATCH; \
  1052. break; \
  1053. }
  1054. #define CHECK_NODECLASS_WRITE(CLASS) \
  1055. if((node->nodeClass & (CLASS)) == 0) { \
  1056. retval = UA_STATUSCODE_BADNODECLASSINVALID; \
  1057. break; \
  1058. }
  1059. #define CHECK_USERWRITEMASK(mask) \
  1060. if(!(userWriteMask & (mask))) { \
  1061. retval = UA_STATUSCODE_BADUSERACCESSDENIED; \
  1062. break; \
  1063. }
  1064. #define GET_NODETYPE \
  1065. type = (const UA_VariableTypeNode*) \
  1066. getNodeType(server, node); \
  1067. if(!type) { \
  1068. retval = UA_STATUSCODE_BADTYPEMISMATCH; \
  1069. break; \
  1070. }
  1071. /* This function implements the main part of the write service and operates on a
  1072. copy of the node (not in single-threaded mode). */
  1073. static UA_StatusCode
  1074. copyAttributeIntoNode(UA_Server *server, UA_Session *session,
  1075. UA_Node *node, const UA_WriteValue *wvalue) {
  1076. const void *value = wvalue->value.value.data;
  1077. UA_UInt32 userWriteMask = getUserWriteMask(server, session, node);
  1078. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  1079. const UA_VariableTypeNode *type;
  1080. switch(wvalue->attributeId) {
  1081. case UA_ATTRIBUTEID_NODEID:
  1082. case UA_ATTRIBUTEID_NODECLASS:
  1083. case UA_ATTRIBUTEID_USERWRITEMASK:
  1084. case UA_ATTRIBUTEID_USERACCESSLEVEL:
  1085. case UA_ATTRIBUTEID_USEREXECUTABLE:
  1086. retval = UA_STATUSCODE_BADWRITENOTSUPPORTED;
  1087. break;
  1088. case UA_ATTRIBUTEID_BROWSENAME:
  1089. CHECK_USERWRITEMASK(UA_WRITEMASK_BROWSENAME);
  1090. CHECK_DATATYPE_SCALAR(QUALIFIEDNAME);
  1091. UA_QualifiedName_deleteMembers(&node->browseName);
  1092. UA_QualifiedName_copy((const UA_QualifiedName *)value, &node->browseName);
  1093. break;
  1094. case UA_ATTRIBUTEID_DISPLAYNAME:
  1095. CHECK_USERWRITEMASK(UA_WRITEMASK_DISPLAYNAME);
  1096. CHECK_DATATYPE_SCALAR(LOCALIZEDTEXT);
  1097. UA_LocalizedText_deleteMembers(&node->displayName);
  1098. UA_LocalizedText_copy((const UA_LocalizedText *)value, &node->displayName);
  1099. break;
  1100. case UA_ATTRIBUTEID_DESCRIPTION:
  1101. CHECK_USERWRITEMASK(UA_WRITEMASK_DESCRIPTION);
  1102. CHECK_DATATYPE_SCALAR(LOCALIZEDTEXT);
  1103. UA_LocalizedText_deleteMembers(&node->description);
  1104. UA_LocalizedText_copy((const UA_LocalizedText *)value, &node->description);
  1105. break;
  1106. case UA_ATTRIBUTEID_WRITEMASK:
  1107. CHECK_USERWRITEMASK(UA_WRITEMASK_WRITEMASK);
  1108. CHECK_DATATYPE_SCALAR(UINT32);
  1109. node->writeMask = *(const UA_UInt32*)value;
  1110. break;
  1111. case UA_ATTRIBUTEID_ISABSTRACT:
  1112. CHECK_USERWRITEMASK(UA_WRITEMASK_ISABSTRACT);
  1113. CHECK_DATATYPE_SCALAR(BOOLEAN);
  1114. retval = writeIsAbstractAttribute(node, *(const UA_Boolean*)value);
  1115. break;
  1116. case UA_ATTRIBUTEID_SYMMETRIC:
  1117. CHECK_NODECLASS_WRITE(UA_NODECLASS_REFERENCETYPE);
  1118. CHECK_USERWRITEMASK(UA_WRITEMASK_SYMMETRIC);
  1119. CHECK_DATATYPE_SCALAR(BOOLEAN);
  1120. ((UA_ReferenceTypeNode*)node)->symmetric = *(const UA_Boolean*)value;
  1121. break;
  1122. case UA_ATTRIBUTEID_INVERSENAME:
  1123. CHECK_NODECLASS_WRITE(UA_NODECLASS_REFERENCETYPE);
  1124. CHECK_USERWRITEMASK(UA_WRITEMASK_INVERSENAME);
  1125. CHECK_DATATYPE_SCALAR(LOCALIZEDTEXT);
  1126. UA_LocalizedText_deleteMembers(&((UA_ReferenceTypeNode*)node)->inverseName);
  1127. UA_LocalizedText_copy((const UA_LocalizedText *)value,
  1128. &((UA_ReferenceTypeNode*)node)->inverseName);
  1129. break;
  1130. case UA_ATTRIBUTEID_CONTAINSNOLOOPS:
  1131. CHECK_NODECLASS_WRITE(UA_NODECLASS_VIEW);
  1132. CHECK_USERWRITEMASK(UA_WRITEMASK_CONTAINSNOLOOPS);
  1133. CHECK_DATATYPE_SCALAR(BOOLEAN);
  1134. ((UA_ViewNode*)node)->containsNoLoops = *(const UA_Boolean*)value;
  1135. break;
  1136. case UA_ATTRIBUTEID_EVENTNOTIFIER:
  1137. CHECK_NODECLASS_WRITE(UA_NODECLASS_VIEW | UA_NODECLASS_OBJECT);
  1138. CHECK_USERWRITEMASK(UA_WRITEMASK_EVENTNOTIFIER);
  1139. CHECK_DATATYPE_SCALAR(BYTE);
  1140. if(node->nodeClass == UA_NODECLASS_VIEW) {
  1141. ((UA_ViewNode*)node)->eventNotifier = *(const UA_Byte*)value;
  1142. } else {
  1143. ((UA_ObjectNode*)node)->eventNotifier = *(const UA_Byte*)value;
  1144. }
  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_releaseNode(server->nsCtx, (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_releaseNode(server->nsCtx, (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_releaseNode(server->nsCtx, (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. void
  1359. Service_HistoryUpdate(UA_Server *server, UA_Session *session,
  1360. const UA_HistoryUpdateRequest *request,
  1361. UA_HistoryUpdateResponse *response) {
  1362. response->resultsSize = request->historyUpdateDetailsSize;
  1363. response->results = (UA_HistoryUpdateResult*)UA_Array_new(response->resultsSize, &UA_TYPES[UA_TYPES_HISTORYUPDATERESULT]);
  1364. if (!response->results) {
  1365. response->resultsSize = 0;
  1366. response->responseHeader.serviceResult = UA_STATUSCODE_BADOUTOFMEMORY;
  1367. return;
  1368. }
  1369. for (size_t i = 0; i < request->historyUpdateDetailsSize; ++i) {
  1370. UA_HistoryUpdateResult_init(&response->results[i]);
  1371. if(request->historyUpdateDetails[i].encoding != UA_EXTENSIONOBJECT_DECODED) {
  1372. response->results[i].statusCode = UA_STATUSCODE_BADNOTSUPPORTED;
  1373. continue;
  1374. }
  1375. if (request->historyUpdateDetails[i].content.decoded.type
  1376. == &UA_TYPES[UA_TYPES_UPDATEDATADETAILS]) {
  1377. if (server->config.historyDatabase.updateData) {
  1378. server->config.historyDatabase.updateData(server,
  1379. server->config.historyDatabase.context,
  1380. &session->sessionId, session->sessionHandle,
  1381. &request->requestHeader,
  1382. (UA_UpdateDataDetails*)request->historyUpdateDetails[i].content.decoded.data,
  1383. &response->results[i]);
  1384. } else {
  1385. response->results[i].statusCode = UA_STATUSCODE_BADNOTSUPPORTED;
  1386. }
  1387. continue;
  1388. } else
  1389. if (request->historyUpdateDetails[i].content.decoded.type
  1390. == &UA_TYPES[UA_TYPES_DELETERAWMODIFIEDDETAILS]) {
  1391. if (server->config.historyDatabase.deleteRawModified) {
  1392. server->config.historyDatabase.deleteRawModified(server,
  1393. server->config.historyDatabase.context,
  1394. &session->sessionId, session->sessionHandle,
  1395. &request->requestHeader,
  1396. (UA_DeleteRawModifiedDetails*)request->historyUpdateDetails[i].content.decoded.data,
  1397. &response->results[i]);
  1398. } else {
  1399. response->results[i].statusCode = UA_STATUSCODE_BADNOTSUPPORTED;
  1400. }
  1401. continue;
  1402. } else {
  1403. response->results[i].statusCode = UA_STATUSCODE_BADNOTSUPPORTED;
  1404. continue;
  1405. }
  1406. }
  1407. response->responseHeader.serviceResult = UA_STATUSCODE_GOOD;
  1408. }
  1409. #endif
  1410. UA_StatusCode UA_EXPORT
  1411. UA_Server_writeObjectProperty(UA_Server *server, const UA_NodeId objectId,
  1412. const UA_QualifiedName propertyName,
  1413. const UA_Variant value) {
  1414. UA_RelativePathElement rpe;
  1415. UA_RelativePathElement_init(&rpe);
  1416. rpe.referenceTypeId = UA_NODEID_NUMERIC(0, UA_NS0ID_HASPROPERTY);
  1417. rpe.isInverse = false;
  1418. rpe.includeSubtypes = false;
  1419. rpe.targetName = propertyName;
  1420. UA_BrowsePath bp;
  1421. UA_BrowsePath_init(&bp);
  1422. bp.startingNode = objectId;
  1423. bp.relativePath.elementsSize = 1;
  1424. bp.relativePath.elements = &rpe;
  1425. UA_StatusCode retval;
  1426. UA_BrowsePathResult bpr = UA_Server_translateBrowsePathToNodeIds(server, &bp);
  1427. if(bpr.statusCode != UA_STATUSCODE_GOOD || bpr.targetsSize < 1) {
  1428. retval = bpr.statusCode;
  1429. UA_BrowsePathResult_deleteMembers(&bpr);
  1430. return retval;
  1431. }
  1432. retval = UA_Server_writeValue(server, bpr.targets[0].targetId.nodeId, value);
  1433. UA_BrowsePathResult_deleteMembers(&bpr);
  1434. return retval;
  1435. }
  1436. UA_StatusCode UA_EXPORT
  1437. UA_Server_writeObjectProperty_scalar(UA_Server *server, const UA_NodeId objectId,
  1438. const UA_QualifiedName propertyName,
  1439. const void *value, const UA_DataType *type) {
  1440. UA_Variant var;
  1441. UA_Variant_init(&var);
  1442. UA_Variant_setScalar(&var, (void*)(uintptr_t)value, type);
  1443. return UA_Server_writeObjectProperty(server, objectId, propertyName, var);
  1444. }