ua_server.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  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. const UA_ByteString *securityPolicyUri) {
  309. for(size_t i = 0; i < server->config.securityPoliciesSize; i++) {
  310. UA_SecurityPolicy *securityPolicyCandidate = &server->config.securityPolicies[i];
  311. if(UA_ByteString_equal(securityPolicyUri, &securityPolicyCandidate->policyUri))
  312. return securityPolicyCandidate;
  313. }
  314. return NULL;
  315. }
  316. #ifdef UA_ENABLE_ENCRYPTION
  317. /* The local ApplicationURI has to match the certificates of the
  318. * SecurityPolicies */
  319. static void
  320. verifyServerApplicationURI(const UA_Server *server) {
  321. #if UA_LOGLEVEL <= 400
  322. for(size_t i = 0; i < server->config.securityPoliciesSize; i++) {
  323. UA_SecurityPolicy *sp = &server->config.securityPolicies[i];
  324. if(!sp->certificateVerification)
  325. continue;
  326. UA_StatusCode retval =
  327. sp->certificateVerification->
  328. verifyApplicationURI(sp->certificateVerification->context,
  329. &sp->localCertificate,
  330. &server->config.applicationDescription.applicationUri);
  331. if(retval != UA_STATUSCODE_GOOD) {
  332. UA_LOG_WARNING(&server->config.logger, UA_LOGCATEGORY_SERVER,
  333. "The configured ApplicationURI does not match the URI "
  334. "specified in the certificate for the SecurityPolicy %.*s",
  335. (int)sp->policyUri.length, sp->policyUri.data);
  336. }
  337. }
  338. #endif
  339. }
  340. #endif
  341. /********************/
  342. /* Main Server Loop */
  343. /********************/
  344. #define UA_MAXTIMEOUT 50 /* Max timeout in ms between main-loop iterations */
  345. /* Start: Spin up the workers and the network layer and sample the server's
  346. * start time.
  347. * Iterate: Process repeated callbacks and events in the network layer. This
  348. * part can be driven from an external main-loop in an event-driven
  349. * single-threaded architecture.
  350. * Stop: Stop workers, finish all callbacks, stop the network layer, clean up */
  351. UA_StatusCode
  352. UA_Server_run_startup(UA_Server *server) {
  353. /* ensure that the uri for ns1 is set up from the app description */
  354. setupNs1Uri(server);
  355. /* write ServerArray with same ApplicationURI value as NamespaceArray */
  356. UA_StatusCode retVal = writeNs0VariableArray(server, UA_NS0ID_SERVER_SERVERARRAY,
  357. &server->config.applicationDescription.applicationUri,
  358. 1, &UA_TYPES[UA_TYPES_STRING]);
  359. if(retVal != UA_STATUSCODE_GOOD)
  360. return retVal;
  361. if(server->state > UA_SERVERLIFECYCLE_FRESH)
  362. return UA_STATUSCODE_GOOD;
  363. /* At least one endpoint has to be configured */
  364. if(server->config.endpointsSize == 0) {
  365. UA_LOG_WARNING(&server->config.logger, UA_LOGCATEGORY_SERVER,
  366. "There has to be at least one endpoint.");
  367. }
  368. /* Initialized discovery */
  369. #ifdef UA_ENABLE_DISCOVERY
  370. UA_DiscoveryManager_init(&server->discoveryManager, server);
  371. #endif
  372. /* Does the ApplicationURI match the local certificates? */
  373. #ifdef UA_ENABLE_ENCRYPTION
  374. verifyServerApplicationURI(server);
  375. #endif
  376. /* Sample the start time and set it to the Server object */
  377. server->startTime = UA_DateTime_now();
  378. UA_Variant var;
  379. UA_Variant_init(&var);
  380. UA_Variant_setScalar(&var, &server->startTime, &UA_TYPES[UA_TYPES_DATETIME]);
  381. UA_Server_writeValue(server,
  382. UA_NODEID_NUMERIC(0, UA_NS0ID_SERVER_SERVERSTATUS_STARTTIME),
  383. var);
  384. /* Start the networklayers */
  385. UA_StatusCode result = UA_STATUSCODE_GOOD;
  386. for(size_t i = 0; i < server->config.networkLayersSize; ++i) {
  387. UA_ServerNetworkLayer *nl = &server->config.networkLayers[i];
  388. result |= nl->start(nl, &server->config.customHostname);
  389. }
  390. /* Spin up the worker threads */
  391. #ifdef UA_ENABLE_MULTITHREADING
  392. UA_LOG_INFO(&server->config.logger, UA_LOGCATEGORY_SERVER,
  393. "Spinning up %u worker thread(s)", server->config.nThreads);
  394. UA_WorkQueue_start(&server->workQueue, server->config.nThreads);
  395. #endif
  396. /* Start the multicast discovery server */
  397. #ifdef UA_ENABLE_DISCOVERY_MULTICAST
  398. if(server->config.discovery.mdnsEnable)
  399. startMulticastDiscoveryServer(server);
  400. #endif
  401. server->state = UA_SERVERLIFECYCLE_FRESH;
  402. return result;
  403. }
  404. static void
  405. serverExecuteRepeatedCallback(UA_Server *server, UA_ApplicationCallback cb,
  406. void *callbackApplication, void *data) {
  407. #ifndef UA_ENABLE_MULTITHREADING
  408. cb(callbackApplication, data);
  409. #else
  410. UA_WorkQueue_enqueue(&server->workQueue, cb, callbackApplication, data);
  411. #endif
  412. }
  413. UA_UInt16
  414. UA_Server_run_iterate(UA_Server *server, UA_Boolean waitInternal) {
  415. /* Process repeated work */
  416. UA_DateTime now = UA_DateTime_nowMonotonic();
  417. UA_DateTime nextRepeated = UA_Timer_process(&server->timer, now,
  418. (UA_TimerExecutionCallback)serverExecuteRepeatedCallback, server);
  419. UA_DateTime latest = now + (UA_MAXTIMEOUT * UA_DATETIME_MSEC);
  420. if(nextRepeated > latest)
  421. nextRepeated = latest;
  422. UA_UInt16 timeout = 0;
  423. /* round always to upper value to avoid timeout to be set to 0
  424. * if(nextRepeated - now) < (UA_DATETIME_MSEC/2) */
  425. if(waitInternal)
  426. timeout = (UA_UInt16)(((nextRepeated - now) + (UA_DATETIME_MSEC - 1)) / UA_DATETIME_MSEC);
  427. /* Listen on the networklayer */
  428. for(size_t i = 0; i < server->config.networkLayersSize; ++i) {
  429. UA_ServerNetworkLayer *nl = &server->config.networkLayers[i];
  430. nl->listen(nl, server, timeout);
  431. }
  432. #if defined(UA_ENABLE_DISCOVERY_MULTICAST) && !defined(UA_ENABLE_MULTITHREADING)
  433. if(server->config.discovery.mdnsEnable) {
  434. // TODO multicastNextRepeat does not consider new input data (requests)
  435. // on the socket. It will be handled on the next call. if needed, we
  436. // need to use select with timeout on the multicast socket
  437. // server->mdnsSocket (see example in mdnsd library) on higher level.
  438. UA_DateTime multicastNextRepeat = 0;
  439. UA_StatusCode hasNext =
  440. iterateMulticastDiscoveryServer(server, &multicastNextRepeat, true);
  441. if(hasNext == UA_STATUSCODE_GOOD && multicastNextRepeat < nextRepeated)
  442. nextRepeated = multicastNextRepeat;
  443. }
  444. #endif
  445. #ifndef UA_ENABLE_MULTITHREADING
  446. UA_WorkQueue_manuallyProcessDelayed(&server->workQueue);
  447. #endif
  448. now = UA_DateTime_nowMonotonic();
  449. timeout = 0;
  450. if(nextRepeated > now)
  451. timeout = (UA_UInt16)((nextRepeated - now) / UA_DATETIME_MSEC);
  452. return timeout;
  453. }
  454. UA_StatusCode
  455. UA_Server_run_shutdown(UA_Server *server) {
  456. /* Stop the netowrk layer */
  457. for(size_t i = 0; i < server->config.networkLayersSize; ++i) {
  458. UA_ServerNetworkLayer *nl = &server->config.networkLayers[i];
  459. nl->stop(nl, server);
  460. }
  461. #ifdef UA_ENABLE_MULTITHREADING
  462. /* Shut down the workers */
  463. UA_LOG_INFO(&server->config.logger, UA_LOGCATEGORY_SERVER,
  464. "Shutting down %u worker thread(s)",
  465. (UA_UInt32)server->workQueue.workersSize);
  466. UA_WorkQueue_stop(&server->workQueue);
  467. #endif
  468. #ifdef UA_ENABLE_DISCOVERY_MULTICAST
  469. /* Stop multicast discovery */
  470. if(server->config.discovery.mdnsEnable)
  471. stopMulticastDiscoveryServer(server);
  472. #endif
  473. /* Execute all delayed callbacks */
  474. UA_WorkQueue_cleanup(&server->workQueue);
  475. return UA_STATUSCODE_GOOD;
  476. }
  477. UA_StatusCode
  478. UA_Server_run(UA_Server *server, const volatile UA_Boolean *running) {
  479. UA_StatusCode retval = UA_Server_run_startup(server);
  480. if(retval != UA_STATUSCODE_GOOD)
  481. return retval;
  482. #ifdef UA_ENABLE_VALGRIND_INTERACTIVE
  483. size_t loopCount = 0;
  484. #endif
  485. while(*running) {
  486. #ifdef UA_ENABLE_VALGRIND_INTERACTIVE
  487. if(loopCount == 0) {
  488. VALGRIND_DO_LEAK_CHECK;
  489. }
  490. ++loopCount;
  491. loopCount %= UA_VALGRIND_INTERACTIVE_INTERVAL;
  492. #endif
  493. UA_Server_run_iterate(server, true);
  494. }
  495. return UA_Server_run_shutdown(server);
  496. }
  497. #ifdef UA_ENABLE_HISTORIZING
  498. /* Allow insert of historical data */
  499. UA_Boolean
  500. UA_Server_AccessControl_allowHistoryUpdateUpdateData(UA_Server *server,
  501. const UA_NodeId *sessionId, void *sessionContext,
  502. const UA_NodeId *nodeId,
  503. UA_PerformUpdateType performInsertReplace,
  504. const UA_DataValue *value) {
  505. if(server->config.accessControl.allowHistoryUpdateUpdateData &&
  506. !server->config.accessControl.allowHistoryUpdateUpdateData(server, &server->config.accessControl,
  507. sessionId, sessionContext, nodeId,
  508. performInsertReplace, value)) {
  509. return false;
  510. }
  511. return true;
  512. }
  513. /* Allow delete of historical data */
  514. UA_Boolean
  515. UA_Server_AccessControl_allowHistoryUpdateDeleteRawModified(UA_Server *server,
  516. const UA_NodeId *sessionId, void *sessionContext,
  517. const UA_NodeId *nodeId,
  518. UA_DateTime startTimestamp,
  519. UA_DateTime endTimestamp,
  520. bool isDeleteModified) {
  521. if(server->config.accessControl.allowHistoryUpdateDeleteRawModified &&
  522. !server->config.accessControl.allowHistoryUpdateDeleteRawModified(server, &server->config.accessControl,
  523. sessionId, sessionContext, nodeId,
  524. startTimestamp, endTimestamp,
  525. isDeleteModified)) {
  526. return false;
  527. }
  528. return true;
  529. }
  530. #endif /* UA_ENABLE_HISTORIZING */