ua_server.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  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 2014-2017 (c) Florian Palm
  7. * Copyright 2015-2016 (c) Sten Grüner
  8. * Copyright 2015-2016 (c) Chris Iatrou
  9. * Copyright 2015 (c) LEvertz
  10. * Copyright 2015-2016 (c) Oleksiy Vasylyev
  11. * Copyright 2016 (c) Julian Grothoff
  12. * Copyright 2016-2017 (c) Stefan Profanter, fortiss GmbH
  13. * Copyright 2016 (c) Lorenz Haas
  14. * Copyright 2017 (c) frax2222
  15. * Copyright 2017 (c) Mark Giraud, Fraunhofer IOSB
  16. * Copyright 2018 (c) Hilscher Gesellschaft für Systemautomation mbH (Author: Martin Lang)
  17. * Copyright 2019 (c) Kalycito Infotech Private Limited
  18. */
  19. #include "ua_server_internal.h"
  20. #ifdef UA_ENABLE_PUBSUB_INFORMATIONMODEL
  21. #include "ua_pubsub_ns0.h"
  22. #endif
  23. #ifdef UA_ENABLE_SUBSCRIPTIONS
  24. #include "ua_subscription.h"
  25. #endif
  26. #ifdef UA_ENABLE_VALGRIND_INTERACTIVE
  27. #include <valgrind/memcheck.h>
  28. #endif
  29. /**********************/
  30. /* Namespace Handling */
  31. /**********************/
  32. /*
  33. * The NS1 Uri can be changed by the user to some custom string.
  34. * This method is called to initialize the NS1 Uri if it is not set before to the default Application URI.
  35. *
  36. * This is done as soon as the Namespace Array is read or written via node value read / write services,
  37. * or UA_Server_addNamespace, UA_Server_getNamespaceByName or UA_Server_run_startup is called.
  38. *
  39. * Therefore one has to set the custom NS1 URI before one of the previously mentioned steps.
  40. */
  41. void setupNs1Uri(UA_Server *server) {
  42. if (!server->namespaces[1].data) {
  43. UA_String_copy(&server->config.applicationDescription.applicationUri, &server->namespaces[1]);
  44. }
  45. }
  46. UA_UInt16 addNamespace(UA_Server *server, const UA_String name) {
  47. /* ensure that the uri for ns1 is set up from the app description */
  48. setupNs1Uri(server);
  49. /* Check if the namespace already exists in the server's namespace array */
  50. for(UA_UInt16 i = 0; i < server->namespacesSize; ++i) {
  51. if(UA_String_equal(&name, &server->namespaces[i]))
  52. return i;
  53. }
  54. /* Make the array bigger */
  55. UA_String *newNS = (UA_String*)UA_realloc(server->namespaces,
  56. sizeof(UA_String) * (server->namespacesSize + 1));
  57. if(!newNS)
  58. return 0;
  59. server->namespaces = newNS;
  60. /* Copy the namespace string */
  61. UA_StatusCode retval = UA_String_copy(&name, &server->namespaces[server->namespacesSize]);
  62. if(retval != UA_STATUSCODE_GOOD)
  63. return 0;
  64. /* Announce the change (otherwise, the array appears unchanged) */
  65. ++server->namespacesSize;
  66. return (UA_UInt16)(server->namespacesSize - 1);
  67. }
  68. UA_UInt16 UA_Server_addNamespace(UA_Server *server, const char* name) {
  69. /* Override const attribute to get string (dirty hack) */
  70. UA_String nameString;
  71. nameString.length = strlen(name);
  72. nameString.data = (UA_Byte*)(uintptr_t)name;
  73. return addNamespace(server, nameString);
  74. }
  75. UA_ServerConfig*
  76. UA_Server_getConfig(UA_Server *server)
  77. {
  78. if(!server)
  79. return NULL;
  80. return &server->config;
  81. }
  82. UA_StatusCode
  83. UA_Server_getNamespaceByName(UA_Server *server, const UA_String namespaceUri,
  84. size_t* foundIndex) {
  85. /* ensure that the uri for ns1 is set up from the app description */
  86. setupNs1Uri(server);
  87. for(size_t idx = 0; idx < server->namespacesSize; idx++) {
  88. if(!UA_String_equal(&server->namespaces[idx], &namespaceUri))
  89. continue;
  90. (*foundIndex) = idx;
  91. return UA_STATUSCODE_GOOD;
  92. }
  93. return UA_STATUSCODE_BADNOTFOUND;
  94. }
  95. UA_StatusCode
  96. UA_Server_forEachChildNodeCall(UA_Server *server, UA_NodeId parentNodeId,
  97. UA_NodeIteratorCallback callback, void *handle) {
  98. const UA_Node *parent = UA_Nodestore_getNode(server->nsCtx, &parentNodeId);
  99. if(!parent)
  100. return UA_STATUSCODE_BADNODEIDINVALID;
  101. /* TODO: We need to do an ugly copy of the references array since users may
  102. * delete references from within the callback. In single-threaded mode this
  103. * changes the same node we point at here. In multi-threaded mode, this
  104. * creates a new copy as nodes are truly immutable.
  105. * The callback could remove a node via the regular public API.
  106. * This can remove a member of the nodes-array we iterate over...
  107. * */
  108. UA_Node *parentCopy = UA_Node_copy_alloc(parent);
  109. if(!parentCopy) {
  110. UA_Nodestore_releaseNode(server->nsCtx, parent);
  111. return UA_STATUSCODE_BADUNEXPECTEDERROR;
  112. }
  113. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  114. for(size_t i = parentCopy->referencesSize; i > 0; --i) {
  115. UA_NodeReferenceKind *ref = &parentCopy->references[i - 1];
  116. for(size_t j = 0; j<ref->targetIdsSize; j++) {
  117. retval = callback(ref->targetIds[j].nodeId, ref->isInverse,
  118. ref->referenceTypeId, handle);
  119. if(retval != UA_STATUSCODE_GOOD)
  120. goto cleanup;
  121. }
  122. }
  123. cleanup:
  124. UA_Node_deleteMembers(parentCopy);
  125. UA_free(parentCopy);
  126. UA_Nodestore_releaseNode(server->nsCtx, parent);
  127. return retval;
  128. }
  129. /********************/
  130. /* Server Lifecycle */
  131. /********************/
  132. /* The server needs to be stopped before it can be deleted */
  133. void UA_Server_delete(UA_Server *server) {
  134. /* Delete all internal data */
  135. UA_SecureChannelManager_deleteMembers(&server->secureChannelManager);
  136. UA_SessionManager_deleteMembers(&server->sessionManager);
  137. UA_Array_delete(server->namespaces, server->namespacesSize, &UA_TYPES[UA_TYPES_STRING]);
  138. #ifdef UA_ENABLE_SUBSCRIPTIONS
  139. UA_MonitoredItem *mon, *mon_tmp;
  140. LIST_FOREACH_SAFE(mon, &server->localMonitoredItems, listEntry, mon_tmp) {
  141. LIST_REMOVE(mon, listEntry);
  142. UA_MonitoredItem_delete(server, mon);
  143. }
  144. #endif
  145. #ifdef UA_ENABLE_PUBSUB
  146. UA_PubSubManager_delete(server, &server->pubSubManager);
  147. #endif
  148. #ifdef UA_ENABLE_DISCOVERY
  149. UA_DiscoveryManager_deleteMembers(&server->discoveryManager, server);
  150. #endif
  151. /* Clean up the Admin Session */
  152. UA_Session_deleteMembersCleanup(&server->adminSession, server);
  153. /* Clean up the work queue */
  154. UA_WorkQueue_cleanup(&server->workQueue);
  155. /* Delete the timed work */
  156. UA_Timer_deleteMembers(&server->timer);
  157. /* Clean up the nodestore */
  158. UA_Nodestore_delete(server->nsCtx);
  159. /* Clean up the config */
  160. UA_ServerConfig_clean(&server->config);
  161. /* Delete the server itself */
  162. UA_free(server);
  163. }
  164. /* Recurring cleanup. Removing unused and timed-out channels and sessions */
  165. static void
  166. UA_Server_cleanup(UA_Server *server, void *_) {
  167. UA_DateTime nowMonotonic = UA_DateTime_nowMonotonic();
  168. UA_SessionManager_cleanupTimedOut(&server->sessionManager, nowMonotonic);
  169. UA_SecureChannelManager_cleanupTimedOut(&server->secureChannelManager, nowMonotonic);
  170. #ifdef UA_ENABLE_DISCOVERY
  171. UA_Discovery_cleanupTimedOut(server, nowMonotonic);
  172. #endif
  173. }
  174. /********************/
  175. /* Server Lifecycle */
  176. /********************/
  177. UA_Server *
  178. UA_Server_new() {
  179. /* Allocate the server */
  180. UA_Server *server = (UA_Server *)UA_calloc(1, sizeof(UA_Server));
  181. if(!server)
  182. return NULL;
  183. /* Init start time to zero, the actual start time will be sampled in
  184. * UA_Server_run_startup() */
  185. server->startTime = 0;
  186. /* Set a seed for non-cyptographic randomness */
  187. #ifndef UA_ENABLE_DETERMINISTIC_RNG
  188. UA_random_seed((UA_UInt64)UA_DateTime_now());
  189. #endif
  190. /* Initialize the handling of repeated callbacks */
  191. UA_Timer_init(&server->timer);
  192. UA_WorkQueue_init(&server->workQueue);
  193. /* Initialize the adminSession */
  194. UA_Session_init(&server->adminSession);
  195. server->adminSession.sessionId.identifierType = UA_NODEIDTYPE_GUID;
  196. server->adminSession.sessionId.identifier.guid.data1 = 1;
  197. server->adminSession.validTill = UA_INT64_MAX;
  198. /* Create Namespaces 0 and 1
  199. * Ns1 will be filled later with the uri from the app description */
  200. server->namespaces = (UA_String *)UA_Array_new(2, &UA_TYPES[UA_TYPES_STRING]);
  201. if(!server->namespaces) {
  202. UA_Server_delete(server);
  203. return NULL;
  204. }
  205. server->namespaces[0] = UA_STRING_ALLOC("http://opcfoundation.org/UA/");
  206. server->namespaces[1] = UA_STRING_NULL;
  207. server->namespacesSize = 2;
  208. /* Initialized SecureChannel and Session managers */
  209. UA_SecureChannelManager_init(&server->secureChannelManager, server);
  210. UA_SessionManager_init(&server->sessionManager, server);
  211. /* Add a regular callback for cleanup and maintenance. With a 10s interval. */
  212. UA_Server_addRepeatedCallback(server, (UA_ServerCallback)UA_Server_cleanup, NULL,
  213. 10000.0, NULL);
  214. /* Initialize namespace 0*/
  215. UA_StatusCode retVal = UA_Nodestore_new(&server->nsCtx);
  216. if(retVal != UA_STATUSCODE_GOOD)
  217. goto cleanup;
  218. retVal = UA_Server_initNS0(server);
  219. if(retVal != UA_STATUSCODE_GOOD)
  220. goto cleanup;
  221. /* Build PubSub information model */
  222. #ifdef UA_ENABLE_PUBSUB_INFORMATIONMODEL
  223. UA_Server_initPubSubNS0(server);
  224. #endif
  225. return server;
  226. cleanup:
  227. UA_Server_delete(server);
  228. return NULL;
  229. }
  230. /*******************/
  231. /* Timed Callbacks */
  232. /*******************/
  233. UA_StatusCode
  234. UA_Server_addTimedCallback(UA_Server *server, UA_ServerCallback callback,
  235. void *data, UA_DateTime date, UA_UInt64 *callbackId) {
  236. return UA_Timer_addTimedCallback(&server->timer,
  237. (UA_ApplicationCallback)callback,
  238. server, data, date, callbackId);
  239. }
  240. UA_StatusCode
  241. UA_Server_addRepeatedCallback(UA_Server *server, UA_ServerCallback callback,
  242. void *data, UA_Double interval_ms,
  243. UA_UInt64 *callbackId) {
  244. return UA_Timer_addRepeatedCallback(&server->timer,
  245. (UA_ApplicationCallback)callback,
  246. server, data, interval_ms, callbackId);
  247. }
  248. UA_StatusCode
  249. UA_Server_changeRepeatedCallbackInterval(UA_Server *server, UA_UInt64 callbackId,
  250. UA_Double interval_ms) {
  251. return UA_Timer_changeRepeatedCallbackInterval(&server->timer, callbackId,
  252. interval_ms);
  253. }
  254. void
  255. UA_Server_removeCallback(UA_Server *server, UA_UInt64 callbackId) {
  256. UA_Timer_removeCallback(&server->timer, callbackId);
  257. }
  258. UA_StatusCode UA_EXPORT
  259. UA_Server_updateCertificate(UA_Server *server,
  260. const UA_ByteString *oldCertificate,
  261. const UA_ByteString *newCertificate,
  262. const UA_ByteString *newPrivateKey,
  263. UA_Boolean closeSessions,
  264. UA_Boolean closeSecureChannels) {
  265. if (server == NULL || oldCertificate == NULL
  266. || newCertificate == NULL || newPrivateKey == NULL) {
  267. return UA_STATUSCODE_BADINTERNALERROR;
  268. }
  269. if (closeSessions) {
  270. UA_SessionManager *sm = &server->sessionManager;
  271. session_list_entry *current;
  272. LIST_FOREACH(current, &sm->sessions, pointers) {
  273. if (UA_ByteString_equal(oldCertificate,
  274. &current->session.header.channel->securityPolicy->localCertificate)) {
  275. UA_SessionManager_removeSession(sm, &current->session.header.authenticationToken);
  276. }
  277. }
  278. }
  279. if (closeSecureChannels) {
  280. UA_SecureChannelManager *cm = &server->secureChannelManager;
  281. channel_entry *entry;
  282. TAILQ_FOREACH(entry, &cm->channels, pointers) {
  283. if(UA_ByteString_equal(&entry->channel.securityPolicy->localCertificate, oldCertificate)){
  284. UA_SecureChannelManager_close(cm, entry->channel.securityToken.channelId);
  285. }
  286. }
  287. }
  288. size_t i = 0;
  289. while (i < server->config.endpointsSize) {
  290. UA_EndpointDescription *ed = &server->config.endpoints[i];
  291. if (UA_ByteString_equal(&ed->serverCertificate, oldCertificate)) {
  292. UA_String_deleteMembers(&ed->serverCertificate);
  293. UA_String_copy(newCertificate, &ed->serverCertificate);
  294. UA_SecurityPolicy *sp = UA_SecurityPolicy_getSecurityPolicyByUri(server, &server->config.endpoints[i].securityPolicyUri);
  295. if(!sp)
  296. return UA_STATUSCODE_BADINTERNALERROR;
  297. sp->updateCertificateAndPrivateKey(sp, *newCertificate, *newPrivateKey);
  298. }
  299. i++;
  300. }
  301. return UA_STATUSCODE_GOOD;
  302. }
  303. /***************************/
  304. /* Server lookup functions */
  305. /***************************/
  306. UA_SecurityPolicy *
  307. UA_SecurityPolicy_getSecurityPolicyByUri(const UA_Server *server,
  308. UA_ByteString *securityPolicyUri)
  309. {
  310. for(size_t i = 0; i < server->config.securityPoliciesSize; i++) {
  311. UA_SecurityPolicy *securityPolicyCandidate = &server->config.securityPolicies[i];
  312. if(UA_ByteString_equal(securityPolicyUri,
  313. &securityPolicyCandidate->policyUri))
  314. return securityPolicyCandidate;
  315. }
  316. return NULL;
  317. }
  318. #ifdef UA_ENABLE_ENCRYPTION
  319. /* The local ApplicationURI has to match the certificates of the
  320. * SecurityPolicies */
  321. static void
  322. verifyServerApplicationURI(const UA_Server *server) {
  323. #if UA_LOGLEVEL <= 400
  324. for(size_t i = 0; i < server->config.securityPoliciesSize; i++) {
  325. UA_SecurityPolicy *sp = &server->config.securityPolicies[i];
  326. if(!sp->certificateVerification)
  327. continue;
  328. UA_StatusCode retval =
  329. sp->certificateVerification->
  330. verifyApplicationURI(sp->certificateVerification->context,
  331. &sp->localCertificate,
  332. &server->config.applicationDescription.applicationUri);
  333. if(retval != UA_STATUSCODE_GOOD) {
  334. UA_LOG_WARNING(&server->config.logger, UA_LOGCATEGORY_SERVER,
  335. "The configured ApplicationURI does not match the URI "
  336. "specified in the certificate for the SecurityPolicy %.*s",
  337. (int)sp->policyUri.length, sp->policyUri.data);
  338. }
  339. }
  340. #endif
  341. }
  342. #endif
  343. /********************/
  344. /* Main Server Loop */
  345. /********************/
  346. #define UA_MAXTIMEOUT 50 /* Max timeout in ms between main-loop iterations */
  347. /* Start: Spin up the workers and the network layer and sample the server's
  348. * start time.
  349. * Iterate: Process repeated callbacks and events in the network layer. This
  350. * part can be driven from an external main-loop in an event-driven
  351. * single-threaded architecture.
  352. * Stop: Stop workers, finish all callbacks, stop the network layer, clean up */
  353. UA_StatusCode
  354. UA_Server_run_startup(UA_Server *server) {
  355. /* ensure that the uri for ns1 is set up from the app description */
  356. setupNs1Uri(server);
  357. /* write ServerArray with same ApplicationURI value as NamespaceArray */
  358. UA_StatusCode retVal = writeNs0VariableArray(server, UA_NS0ID_SERVER_SERVERARRAY,
  359. &server->config.applicationDescription.applicationUri,
  360. 1, &UA_TYPES[UA_TYPES_STRING]);
  361. if(retVal != UA_STATUSCODE_GOOD)
  362. return retVal;
  363. if(server->state > UA_SERVERLIFECYCLE_FRESH)
  364. return UA_STATUSCODE_GOOD;
  365. /* At least one endpoint has to be configured */
  366. if(server->config.endpointsSize == 0) {
  367. UA_LOG_WARNING(&server->config.logger, UA_LOGCATEGORY_SERVER,
  368. "There has to be at least one endpoint.");
  369. }
  370. /* Initialized discovery */
  371. #ifdef UA_ENABLE_DISCOVERY
  372. UA_DiscoveryManager_init(&server->discoveryManager, server);
  373. #endif
  374. /* Does the ApplicationURI match the local certificates? */
  375. #ifdef UA_ENABLE_ENCRYPTION
  376. verifyServerApplicationURI(server);
  377. #endif
  378. /* Sample the start time and set it to the Server object */
  379. server->startTime = UA_DateTime_now();
  380. UA_Variant var;
  381. UA_Variant_init(&var);
  382. UA_Variant_setScalar(&var, &server->startTime, &UA_TYPES[UA_TYPES_DATETIME]);
  383. UA_Server_writeValue(server,
  384. UA_NODEID_NUMERIC(0, UA_NS0ID_SERVER_SERVERSTATUS_STARTTIME),
  385. var);
  386. /* Start the networklayers */
  387. UA_StatusCode result = UA_STATUSCODE_GOOD;
  388. for(size_t i = 0; i < server->config.networkLayersSize; ++i) {
  389. UA_ServerNetworkLayer *nl = &server->config.networkLayers[i];
  390. result |= nl->start(nl, &server->config.customHostname);
  391. }
  392. /* Spin up the worker threads */
  393. #ifdef UA_ENABLE_MULTITHREADING
  394. UA_LOG_INFO(&server->config.logger, UA_LOGCATEGORY_SERVER,
  395. "Spinning up %u worker thread(s)", server->config.nThreads);
  396. UA_WorkQueue_start(&server->workQueue, server->config.nThreads);
  397. #endif
  398. /* Start the multicast discovery server */
  399. #ifdef UA_ENABLE_DISCOVERY_MULTICAST
  400. if(server->config.discovery.mdnsEnable)
  401. startMulticastDiscoveryServer(server);
  402. #endif
  403. server->state = UA_SERVERLIFECYCLE_FRESH;
  404. return result;
  405. }
  406. static void
  407. serverExecuteRepeatedCallback(UA_Server *server, UA_ApplicationCallback cb,
  408. void *callbackApplication, void *data) {
  409. #ifndef UA_ENABLE_MULTITHREADING
  410. cb(callbackApplication, data);
  411. #else
  412. UA_WorkQueue_enqueue(&server->workQueue, cb, callbackApplication, data);
  413. #endif
  414. }
  415. UA_UInt16
  416. UA_Server_run_iterate(UA_Server *server, UA_Boolean waitInternal) {
  417. /* Process repeated work */
  418. UA_DateTime now = UA_DateTime_nowMonotonic();
  419. UA_DateTime nextRepeated = UA_Timer_process(&server->timer, now,
  420. (UA_TimerExecutionCallback)serverExecuteRepeatedCallback, server);
  421. UA_DateTime latest = now + (UA_MAXTIMEOUT * UA_DATETIME_MSEC);
  422. if(nextRepeated > latest)
  423. nextRepeated = latest;
  424. UA_UInt16 timeout = 0;
  425. /* round always to upper value to avoid timeout to be set to 0
  426. * if(nextRepeated - now) < (UA_DATETIME_MSEC/2) */
  427. if(waitInternal)
  428. timeout = (UA_UInt16)(((nextRepeated - now) + (UA_DATETIME_MSEC - 1)) / UA_DATETIME_MSEC);
  429. /* Listen on the networklayer */
  430. for(size_t i = 0; i < server->config.networkLayersSize; ++i) {
  431. UA_ServerNetworkLayer *nl = &server->config.networkLayers[i];
  432. nl->listen(nl, server, timeout);
  433. }
  434. #if defined(UA_ENABLE_DISCOVERY_MULTICAST) && !defined(UA_ENABLE_MULTITHREADING)
  435. if(server->config.discovery.mdnsEnable) {
  436. // TODO multicastNextRepeat does not consider new input data (requests)
  437. // on the socket. It will be handled on the next call. if needed, we
  438. // need to use select with timeout on the multicast socket
  439. // server->mdnsSocket (see example in mdnsd library) on higher level.
  440. UA_DateTime multicastNextRepeat = 0;
  441. UA_StatusCode hasNext =
  442. iterateMulticastDiscoveryServer(server, &multicastNextRepeat, true);
  443. if(hasNext == UA_STATUSCODE_GOOD && multicastNextRepeat < nextRepeated)
  444. nextRepeated = multicastNextRepeat;
  445. }
  446. #endif
  447. #ifndef UA_ENABLE_MULTITHREADING
  448. UA_WorkQueue_manuallyProcessDelayed(&server->workQueue);
  449. #endif
  450. now = UA_DateTime_nowMonotonic();
  451. timeout = 0;
  452. if(nextRepeated > now)
  453. timeout = (UA_UInt16)((nextRepeated - now) / UA_DATETIME_MSEC);
  454. return timeout;
  455. }
  456. UA_StatusCode
  457. UA_Server_run_shutdown(UA_Server *server) {
  458. /* Stop the netowrk layer */
  459. for(size_t i = 0; i < server->config.networkLayersSize; ++i) {
  460. UA_ServerNetworkLayer *nl = &server->config.networkLayers[i];
  461. nl->stop(nl, server);
  462. }
  463. #ifdef UA_ENABLE_MULTITHREADING
  464. /* Shut down the workers */
  465. UA_LOG_INFO(&server->config.logger, UA_LOGCATEGORY_SERVER,
  466. "Shutting down %u worker thread(s)",
  467. (UA_UInt32)server->workQueue.workersSize);
  468. UA_WorkQueue_stop(&server->workQueue);
  469. #endif
  470. #ifdef UA_ENABLE_DISCOVERY_MULTICAST
  471. /* Stop multicast discovery */
  472. if(server->config.discovery.mdnsEnable)
  473. stopMulticastDiscoveryServer(server);
  474. #endif
  475. /* Execute all delayed callbacks */
  476. UA_WorkQueue_cleanup(&server->workQueue);
  477. return UA_STATUSCODE_GOOD;
  478. }
  479. UA_StatusCode
  480. UA_Server_run(UA_Server *server, const volatile UA_Boolean *running) {
  481. UA_StatusCode retval = UA_Server_run_startup(server);
  482. if(retval != UA_STATUSCODE_GOOD)
  483. return retval;
  484. #ifdef UA_ENABLE_VALGRIND_INTERACTIVE
  485. size_t loopCount = 0;
  486. #endif
  487. while(*running) {
  488. #ifdef UA_ENABLE_VALGRIND_INTERACTIVE
  489. if(loopCount == 0) {
  490. VALGRIND_DO_LEAK_CHECK;
  491. }
  492. ++loopCount;
  493. loopCount %= UA_VALGRIND_INTERACTIVE_INTERVAL;
  494. #endif
  495. UA_Server_run_iterate(server, true);
  496. }
  497. return UA_Server_run_shutdown(server);
  498. }
  499. #ifdef UA_ENABLE_HISTORIZING
  500. /* Allow insert of historical data */
  501. UA_Boolean
  502. UA_Server_AccessControl_allowHistoryUpdateUpdateData(UA_Server *server,
  503. const UA_NodeId *sessionId, void *sessionContext,
  504. const UA_NodeId *nodeId,
  505. UA_PerformUpdateType performInsertReplace,
  506. const UA_DataValue *value) {
  507. if(server->config.accessControl.allowHistoryUpdateUpdateData &&
  508. !server->config.accessControl.allowHistoryUpdateUpdateData(server, &server->config.accessControl,
  509. sessionId, sessionContext, nodeId,
  510. performInsertReplace, value)) {
  511. return false;
  512. }
  513. return true;
  514. }
  515. /* Allow delete of historical data */
  516. UA_Boolean
  517. UA_Server_AccessControl_allowHistoryUpdateDeleteRawModified(UA_Server *server,
  518. const UA_NodeId *sessionId, void *sessionContext,
  519. const UA_NodeId *nodeId,
  520. UA_DateTime startTimestamp,
  521. UA_DateTime endTimestamp,
  522. bool isDeleteModified) {
  523. if(server->config.accessControl.allowHistoryUpdateDeleteRawModified &&
  524. !server->config.accessControl.allowHistoryUpdateDeleteRawModified(server, &server->config.accessControl,
  525. sessionId, sessionContext, nodeId,
  526. startTimestamp, endTimestamp,
  527. isDeleteModified)) {
  528. return false;
  529. }
  530. return true;
  531. }
  532. #endif /* UA_ENABLE_HISTORIZING */