ua_server.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  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. static UA_Server *
  178. UA_Server_init(UA_Server *server) {
  179. /* Init start time to zero, the actual start time will be sampled in
  180. * UA_Server_run_startup() */
  181. server->startTime = 0;
  182. /* Set a seed for non-cyptographic randomness */
  183. #ifndef UA_ENABLE_DETERMINISTIC_RNG
  184. UA_random_seed((UA_UInt64)UA_DateTime_now());
  185. #endif
  186. /* Initialize the handling of repeated callbacks */
  187. UA_Timer_init(&server->timer);
  188. UA_WorkQueue_init(&server->workQueue);
  189. /* Initialize the adminSession */
  190. UA_Session_init(&server->adminSession);
  191. server->adminSession.sessionId.identifierType = UA_NODEIDTYPE_GUID;
  192. server->adminSession.sessionId.identifier.guid.data1 = 1;
  193. server->adminSession.validTill = UA_INT64_MAX;
  194. /* Create Namespaces 0 and 1
  195. * Ns1 will be filled later with the uri from the app description */
  196. server->namespaces = (UA_String *)UA_Array_new(2, &UA_TYPES[UA_TYPES_STRING]);
  197. if(!server->namespaces) {
  198. UA_Server_delete(server);
  199. return NULL;
  200. }
  201. server->namespaces[0] = UA_STRING_ALLOC("http://opcfoundation.org/UA/");
  202. server->namespaces[1] = UA_STRING_NULL;
  203. server->namespacesSize = 2;
  204. /* Initialized SecureChannel and Session managers */
  205. UA_SecureChannelManager_init(&server->secureChannelManager, server);
  206. UA_SessionManager_init(&server->sessionManager, server);
  207. /* Add a regular callback for cleanup and maintenance. With a 10s interval. */
  208. UA_Server_addRepeatedCallback(server, (UA_ServerCallback)UA_Server_cleanup, NULL,
  209. 10000.0, NULL);
  210. /* Initialize namespace 0*/
  211. UA_StatusCode retVal = UA_Nodestore_new(&server->nsCtx);
  212. if(retVal != UA_STATUSCODE_GOOD)
  213. goto cleanup;
  214. retVal = UA_Server_initNS0(server);
  215. if(retVal != UA_STATUSCODE_GOOD)
  216. goto cleanup;
  217. /* Build PubSub information model */
  218. #ifdef UA_ENABLE_PUBSUB_INFORMATIONMODEL
  219. UA_Server_initPubSubNS0(server);
  220. #endif
  221. return server;
  222. cleanup:
  223. UA_Server_delete(server);
  224. return NULL;
  225. }
  226. UA_Server *
  227. UA_Server_new() {
  228. /* Allocate the server */
  229. UA_Server *server = (UA_Server *)UA_calloc(1, sizeof(UA_Server));
  230. if(!server)
  231. return NULL;
  232. return UA_Server_init(server);
  233. }
  234. UA_Server *
  235. UA_Server_newWithConfig(const UA_ServerConfig *config) {
  236. UA_Server *server = (UA_Server *)UA_calloc(1, sizeof(UA_Server));
  237. if(!server)
  238. return NULL;
  239. if(config)
  240. server->config = *config;
  241. return UA_Server_init(server);
  242. }
  243. /* Returns if the server should be shut down immediately */
  244. static UA_Boolean
  245. setServerShutdown(UA_Server *server) {
  246. if(server->endTime != 0)
  247. return false;
  248. if(server->config.shutdownDelay == 0)
  249. return true;
  250. UA_LOG_WARNING(&server->config.logger, UA_LOGCATEGORY_SERVER,
  251. "Shutting down the server with a delay of %i ms", (int)server->config.shutdownDelay);
  252. server->endTime = UA_DateTime_now() + (UA_DateTime)(server->config.shutdownDelay * UA_DATETIME_MSEC);
  253. return false;
  254. }
  255. /*******************/
  256. /* Timed Callbacks */
  257. /*******************/
  258. UA_StatusCode
  259. UA_Server_addTimedCallback(UA_Server *server, UA_ServerCallback callback,
  260. void *data, UA_DateTime date, UA_UInt64 *callbackId) {
  261. return UA_Timer_addTimedCallback(&server->timer,
  262. (UA_ApplicationCallback)callback,
  263. server, data, date, callbackId);
  264. }
  265. UA_StatusCode
  266. UA_Server_addRepeatedCallback(UA_Server *server, UA_ServerCallback callback,
  267. void *data, UA_Double interval_ms,
  268. UA_UInt64 *callbackId) {
  269. return UA_Timer_addRepeatedCallback(&server->timer,
  270. (UA_ApplicationCallback)callback,
  271. server, data, interval_ms, callbackId);
  272. }
  273. UA_StatusCode
  274. UA_Server_changeRepeatedCallbackInterval(UA_Server *server, UA_UInt64 callbackId,
  275. UA_Double interval_ms) {
  276. return UA_Timer_changeRepeatedCallbackInterval(&server->timer, callbackId,
  277. interval_ms);
  278. }
  279. void
  280. UA_Server_removeCallback(UA_Server *server, UA_UInt64 callbackId) {
  281. UA_Timer_removeCallback(&server->timer, callbackId);
  282. }
  283. UA_StatusCode UA_EXPORT
  284. UA_Server_updateCertificate(UA_Server *server,
  285. const UA_ByteString *oldCertificate,
  286. const UA_ByteString *newCertificate,
  287. const UA_ByteString *newPrivateKey,
  288. UA_Boolean closeSessions,
  289. UA_Boolean closeSecureChannels) {
  290. if (server == NULL || oldCertificate == NULL
  291. || newCertificate == NULL || newPrivateKey == NULL) {
  292. return UA_STATUSCODE_BADINTERNALERROR;
  293. }
  294. if (closeSessions) {
  295. UA_SessionManager *sm = &server->sessionManager;
  296. session_list_entry *current;
  297. LIST_FOREACH(current, &sm->sessions, pointers) {
  298. if (UA_ByteString_equal(oldCertificate,
  299. &current->session.header.channel->securityPolicy->localCertificate)) {
  300. UA_SessionManager_removeSession(sm, &current->session.header.authenticationToken);
  301. }
  302. }
  303. }
  304. if (closeSecureChannels) {
  305. UA_SecureChannelManager *cm = &server->secureChannelManager;
  306. channel_entry *entry;
  307. TAILQ_FOREACH(entry, &cm->channels, pointers) {
  308. if(UA_ByteString_equal(&entry->channel.securityPolicy->localCertificate, oldCertificate)){
  309. UA_SecureChannelManager_close(cm, entry->channel.securityToken.channelId);
  310. }
  311. }
  312. }
  313. size_t i = 0;
  314. while (i < server->config.endpointsSize) {
  315. UA_EndpointDescription *ed = &server->config.endpoints[i];
  316. if (UA_ByteString_equal(&ed->serverCertificate, oldCertificate)) {
  317. UA_String_deleteMembers(&ed->serverCertificate);
  318. UA_String_copy(newCertificate, &ed->serverCertificate);
  319. UA_SecurityPolicy *sp = UA_SecurityPolicy_getSecurityPolicyByUri(server, &server->config.endpoints[i].securityPolicyUri);
  320. if(!sp)
  321. return UA_STATUSCODE_BADINTERNALERROR;
  322. sp->updateCertificateAndPrivateKey(sp, *newCertificate, *newPrivateKey);
  323. }
  324. i++;
  325. }
  326. return UA_STATUSCODE_GOOD;
  327. }
  328. /***************************/
  329. /* Server lookup functions */
  330. /***************************/
  331. UA_SecurityPolicy *
  332. UA_SecurityPolicy_getSecurityPolicyByUri(const UA_Server *server,
  333. const UA_ByteString *securityPolicyUri) {
  334. for(size_t i = 0; i < server->config.securityPoliciesSize; i++) {
  335. UA_SecurityPolicy *securityPolicyCandidate = &server->config.securityPolicies[i];
  336. if(UA_ByteString_equal(securityPolicyUri, &securityPolicyCandidate->policyUri))
  337. return securityPolicyCandidate;
  338. }
  339. return NULL;
  340. }
  341. #ifdef UA_ENABLE_ENCRYPTION
  342. /* The local ApplicationURI has to match the certificates of the
  343. * SecurityPolicies */
  344. static void
  345. verifyServerApplicationURI(const UA_Server *server) {
  346. #if UA_LOGLEVEL <= 400
  347. for(size_t i = 0; i < server->config.securityPoliciesSize; i++) {
  348. UA_SecurityPolicy *sp = &server->config.securityPolicies[i];
  349. if(!sp->certificateVerification)
  350. continue;
  351. UA_StatusCode retval =
  352. sp->certificateVerification->
  353. verifyApplicationURI(sp->certificateVerification->context,
  354. &sp->localCertificate,
  355. &server->config.applicationDescription.applicationUri);
  356. if(retval != UA_STATUSCODE_GOOD) {
  357. UA_LOG_WARNING(&server->config.logger, UA_LOGCATEGORY_SERVER,
  358. "The configured ApplicationURI does not match the URI "
  359. "specified in the certificate for the SecurityPolicy %.*s",
  360. (int)sp->policyUri.length, sp->policyUri.data);
  361. }
  362. }
  363. #endif
  364. }
  365. #endif
  366. /********************/
  367. /* Main Server Loop */
  368. /********************/
  369. #define UA_MAXTIMEOUT 50 /* Max timeout in ms between main-loop iterations */
  370. /* Start: Spin up the workers and the network layer and sample the server's
  371. * start time.
  372. * Iterate: Process repeated callbacks and events in the network layer. This
  373. * part can be driven from an external main-loop in an event-driven
  374. * single-threaded architecture.
  375. * Stop: Stop workers, finish all callbacks, stop the network layer, clean up */
  376. UA_StatusCode
  377. UA_Server_run_startup(UA_Server *server) {
  378. /* ensure that the uri for ns1 is set up from the app description */
  379. setupNs1Uri(server);
  380. /* write ServerArray with same ApplicationURI value as NamespaceArray */
  381. UA_StatusCode retVal = writeNs0VariableArray(server, UA_NS0ID_SERVER_SERVERARRAY,
  382. &server->config.applicationDescription.applicationUri,
  383. 1, &UA_TYPES[UA_TYPES_STRING]);
  384. if(retVal != UA_STATUSCODE_GOOD)
  385. return retVal;
  386. if(server->state > UA_SERVERLIFECYCLE_FRESH)
  387. return UA_STATUSCODE_GOOD;
  388. /* At least one endpoint has to be configured */
  389. if(server->config.endpointsSize == 0) {
  390. UA_LOG_WARNING(&server->config.logger, UA_LOGCATEGORY_SERVER,
  391. "There has to be at least one endpoint.");
  392. }
  393. /* Initialized discovery */
  394. #ifdef UA_ENABLE_DISCOVERY
  395. UA_DiscoveryManager_init(&server->discoveryManager, server);
  396. #endif
  397. /* Does the ApplicationURI match the local certificates? */
  398. #ifdef UA_ENABLE_ENCRYPTION
  399. verifyServerApplicationURI(server);
  400. #endif
  401. /* Sample the start time and set it to the Server object */
  402. server->startTime = UA_DateTime_now();
  403. UA_Variant var;
  404. UA_Variant_init(&var);
  405. UA_Variant_setScalar(&var, &server->startTime, &UA_TYPES[UA_TYPES_DATETIME]);
  406. UA_Server_writeValue(server,
  407. UA_NODEID_NUMERIC(0, UA_NS0ID_SERVER_SERVERSTATUS_STARTTIME),
  408. var);
  409. /* Start the networklayers */
  410. UA_StatusCode result = UA_STATUSCODE_GOOD;
  411. for(size_t i = 0; i < server->config.networkLayersSize; ++i) {
  412. UA_ServerNetworkLayer *nl = &server->config.networkLayers[i];
  413. result |= nl->start(nl, &server->config.customHostname);
  414. }
  415. /* Update the application description to match the previously added discovery urls.
  416. * We can only do this after the network layer is started since it inits the discovery url */
  417. if (server->config.applicationDescription.discoveryUrlsSize != 0) {
  418. UA_Array_delete(server->config.applicationDescription.discoveryUrls, server->config.applicationDescription.discoveryUrlsSize, &UA_TYPES[UA_TYPES_STRING]);
  419. server->config.applicationDescription.discoveryUrlsSize = 0;
  420. }
  421. server->config.applicationDescription.discoveryUrls = (UA_String *) UA_Array_new(server->config.networkLayersSize, &UA_TYPES[UA_TYPES_STRING]);
  422. if (!server->config.applicationDescription.discoveryUrls) {
  423. return UA_STATUSCODE_BADOUTOFMEMORY;
  424. }
  425. server->config.applicationDescription.discoveryUrlsSize = server->config.networkLayersSize;
  426. for (size_t i=0; i< server->config.applicationDescription.discoveryUrlsSize; i++) {
  427. UA_ServerNetworkLayer *nl = &server->config.networkLayers[i];
  428. UA_String_copy(&nl->discoveryUrl, &server->config.applicationDescription.discoveryUrls[i]);
  429. }
  430. /* Spin up the worker threads */
  431. #ifdef UA_ENABLE_MULTITHREADING
  432. UA_LOG_INFO(&server->config.logger, UA_LOGCATEGORY_SERVER,
  433. "Spinning up %u worker thread(s)", server->config.nThreads);
  434. UA_WorkQueue_start(&server->workQueue, server->config.nThreads);
  435. #endif
  436. /* Start the multicast discovery server */
  437. #ifdef UA_ENABLE_DISCOVERY_MULTICAST
  438. if(server->config.discovery.mdnsEnable)
  439. startMulticastDiscoveryServer(server);
  440. #endif
  441. server->state = UA_SERVERLIFECYCLE_FRESH;
  442. return result;
  443. }
  444. static void
  445. serverExecuteRepeatedCallback(UA_Server *server, UA_ApplicationCallback cb,
  446. void *callbackApplication, void *data) {
  447. #ifndef UA_ENABLE_MULTITHREADING
  448. cb(callbackApplication, data);
  449. #else
  450. UA_WorkQueue_enqueue(&server->workQueue, cb, callbackApplication, data);
  451. #endif
  452. }
  453. UA_UInt16
  454. UA_Server_run_iterate(UA_Server *server, UA_Boolean waitInternal) {
  455. /* Process repeated work */
  456. UA_DateTime now = UA_DateTime_nowMonotonic();
  457. UA_DateTime nextRepeated = UA_Timer_process(&server->timer, now,
  458. (UA_TimerExecutionCallback)serverExecuteRepeatedCallback, server);
  459. UA_DateTime latest = now + (UA_MAXTIMEOUT * UA_DATETIME_MSEC);
  460. if(nextRepeated > latest)
  461. nextRepeated = latest;
  462. UA_UInt16 timeout = 0;
  463. /* round always to upper value to avoid timeout to be set to 0
  464. * if(nextRepeated - now) < (UA_DATETIME_MSEC/2) */
  465. if(waitInternal)
  466. timeout = (UA_UInt16)(((nextRepeated - now) + (UA_DATETIME_MSEC - 1)) / UA_DATETIME_MSEC);
  467. /* Listen on the networklayer */
  468. for(size_t i = 0; i < server->config.networkLayersSize; ++i) {
  469. UA_ServerNetworkLayer *nl = &server->config.networkLayers[i];
  470. nl->listen(nl, server, timeout);
  471. }
  472. #if defined(UA_ENABLE_DISCOVERY_MULTICAST) && !defined(UA_ENABLE_MULTITHREADING)
  473. if(server->config.discovery.mdnsEnable) {
  474. // TODO multicastNextRepeat does not consider new input data (requests)
  475. // on the socket. It will be handled on the next call. if needed, we
  476. // need to use select with timeout on the multicast socket
  477. // server->mdnsSocket (see example in mdnsd library) on higher level.
  478. UA_DateTime multicastNextRepeat = 0;
  479. UA_StatusCode hasNext =
  480. iterateMulticastDiscoveryServer(server, &multicastNextRepeat, true);
  481. if(hasNext == UA_STATUSCODE_GOOD && multicastNextRepeat < nextRepeated)
  482. nextRepeated = multicastNextRepeat;
  483. }
  484. #endif
  485. #ifndef UA_ENABLE_MULTITHREADING
  486. UA_WorkQueue_manuallyProcessDelayed(&server->workQueue);
  487. #endif
  488. now = UA_DateTime_nowMonotonic();
  489. timeout = 0;
  490. if(nextRepeated > now)
  491. timeout = (UA_UInt16)((nextRepeated - now) / UA_DATETIME_MSEC);
  492. return timeout;
  493. }
  494. UA_StatusCode
  495. UA_Server_run_shutdown(UA_Server *server) {
  496. /* Stop the netowrk layer */
  497. for(size_t i = 0; i < server->config.networkLayersSize; ++i) {
  498. UA_ServerNetworkLayer *nl = &server->config.networkLayers[i];
  499. nl->stop(nl, server);
  500. }
  501. #ifdef UA_ENABLE_MULTITHREADING
  502. /* Shut down the workers */
  503. UA_LOG_INFO(&server->config.logger, UA_LOGCATEGORY_SERVER,
  504. "Shutting down %u worker thread(s)",
  505. (UA_UInt32)server->workQueue.workersSize);
  506. UA_WorkQueue_stop(&server->workQueue);
  507. #endif
  508. #ifdef UA_ENABLE_DISCOVERY_MULTICAST
  509. /* Stop multicast discovery */
  510. if(server->config.discovery.mdnsEnable)
  511. stopMulticastDiscoveryServer(server);
  512. #endif
  513. /* Execute all delayed callbacks */
  514. UA_WorkQueue_cleanup(&server->workQueue);
  515. return UA_STATUSCODE_GOOD;
  516. }
  517. static UA_Boolean
  518. testShutdownCondition(UA_Server *server) {
  519. if(server->endTime == 0)
  520. return false;
  521. return (UA_DateTime_now() > server->endTime);
  522. }
  523. UA_StatusCode
  524. UA_Server_run(UA_Server *server, const volatile UA_Boolean *running) {
  525. UA_StatusCode retval = UA_Server_run_startup(server);
  526. if(retval != UA_STATUSCODE_GOOD)
  527. return retval;
  528. #ifdef UA_ENABLE_VALGRIND_INTERACTIVE
  529. size_t loopCount = 0;
  530. #endif
  531. while(!testShutdownCondition(server)) {
  532. #ifdef UA_ENABLE_VALGRIND_INTERACTIVE
  533. if(loopCount == 0) {
  534. VALGRIND_DO_LEAK_CHECK;
  535. }
  536. ++loopCount;
  537. loopCount %= UA_VALGRIND_INTERACTIVE_INTERVAL;
  538. #endif
  539. UA_Server_run_iterate(server, true);
  540. if(!*running) {
  541. if(setServerShutdown(server))
  542. break;
  543. }
  544. }
  545. return UA_Server_run_shutdown(server);
  546. }
  547. #ifdef UA_ENABLE_HISTORIZING
  548. /* Allow insert of historical data */
  549. UA_Boolean
  550. UA_Server_AccessControl_allowHistoryUpdateUpdateData(UA_Server *server,
  551. const UA_NodeId *sessionId, void *sessionContext,
  552. const UA_NodeId *nodeId,
  553. UA_PerformUpdateType performInsertReplace,
  554. const UA_DataValue *value) {
  555. if(server->config.accessControl.allowHistoryUpdateUpdateData &&
  556. !server->config.accessControl.allowHistoryUpdateUpdateData(server, &server->config.accessControl,
  557. sessionId, sessionContext, nodeId,
  558. performInsertReplace, value)) {
  559. return false;
  560. }
  561. return true;
  562. }
  563. /* Allow delete of historical data */
  564. UA_Boolean
  565. UA_Server_AccessControl_allowHistoryUpdateDeleteRawModified(UA_Server *server,
  566. const UA_NodeId *sessionId, void *sessionContext,
  567. const UA_NodeId *nodeId,
  568. UA_DateTime startTimestamp,
  569. UA_DateTime endTimestamp,
  570. bool isDeleteModified) {
  571. if(server->config.accessControl.allowHistoryUpdateDeleteRawModified &&
  572. !server->config.accessControl.allowHistoryUpdateDeleteRawModified(server, &server->config.accessControl,
  573. sessionId, sessionContext, nodeId,
  574. startTimestamp, endTimestamp,
  575. isDeleteModified)) {
  576. return false;
  577. }
  578. return true;
  579. }
  580. #endif /* UA_ENABLE_HISTORIZING */