ua_server.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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. #include "ua_types.h"
  5. #include "ua_server_internal.h"
  6. #include "ua_securechannel_manager.h"
  7. #include "ua_session_manager.h"
  8. #include "ua_util.h"
  9. #include "ua_services.h"
  10. #include "ua_nodeids.h"
  11. #ifdef UA_ENABLE_GENERATE_NAMESPACE0
  12. #include "ua_namespaceinit_generated.h"
  13. #endif
  14. #if defined(UA_ENABLE_MULTITHREADING) && !defined(NDEBUG)
  15. UA_THREAD_LOCAL bool rcu_locked = false;
  16. #endif
  17. /**********************/
  18. /* Namespace Handling */
  19. /**********************/
  20. UA_UInt16 addNamespace(UA_Server *server, const UA_String name) {
  21. /* Check if the namespace already exists in the server's namespace array */
  22. for(UA_UInt16 i = 0; i < server->namespacesSize; ++i) {
  23. if(UA_String_equal(&name, &server->namespaces[i]))
  24. return i;
  25. }
  26. /* Make the array bigger */
  27. UA_String *newNS = (UA_String*)UA_realloc(server->namespaces,
  28. sizeof(UA_String) * (server->namespacesSize + 1));
  29. if(!newNS)
  30. return 0;
  31. server->namespaces = newNS;
  32. /* Copy the namespace string */
  33. UA_StatusCode retval = UA_String_copy(&name, &server->namespaces[server->namespacesSize]);
  34. if(retval != UA_STATUSCODE_GOOD)
  35. return 0;
  36. /* Announce the change (otherwise, the array appears unchanged) */
  37. ++server->namespacesSize;
  38. return (UA_UInt16)(server->namespacesSize - 1);
  39. }
  40. UA_UInt16 UA_Server_addNamespace(UA_Server *server, const char* name) {
  41. /* Override const attribute to get string (dirty hack) */
  42. UA_String nameString;
  43. nameString.length = strlen(name);
  44. nameString.data = (UA_Byte*)(uintptr_t)name;
  45. return addNamespace(server, nameString);
  46. }
  47. UA_StatusCode
  48. UA_Server_forEachChildNodeCall(UA_Server *server, UA_NodeId parentNodeId,
  49. UA_NodeIteratorCallback callback, void *handle) {
  50. UA_RCU_LOCK();
  51. const UA_Node *parent = UA_NodeStore_get(server->nodestore, &parentNodeId);
  52. if(!parent) {
  53. UA_RCU_UNLOCK();
  54. return UA_STATUSCODE_BADNODEIDINVALID;
  55. }
  56. /* TODO: We need to do an ugly copy of the references array since users may
  57. * delete references from within the callback. In single-threaded mode this
  58. * changes the same node we point at here. In multi-threaded mode, this
  59. * creates a new copy as nodes are truly immutable. */
  60. UA_ReferenceNode *refs = NULL;
  61. size_t refssize = parent->referencesSize;
  62. UA_StatusCode retval = UA_Array_copy(parent->references, parent->referencesSize,
  63. (void**)&refs, &UA_TYPES[UA_TYPES_REFERENCENODE]);
  64. if(retval != UA_STATUSCODE_GOOD) {
  65. UA_RCU_UNLOCK();
  66. return retval;
  67. }
  68. for(size_t i = parent->referencesSize; i > 0; --i) {
  69. UA_ReferenceNode *ref = &refs[i-1];
  70. retval |= callback(ref->targetId.nodeId, ref->isInverse,
  71. ref->referenceTypeId, handle);
  72. }
  73. UA_RCU_UNLOCK();
  74. UA_Array_delete(refs, refssize, &UA_TYPES[UA_TYPES_REFERENCENODE]);
  75. return retval;
  76. }
  77. /********************/
  78. /* Server Lifecycle */
  79. /********************/
  80. /* The server needs to be stopped before it can be deleted */
  81. void UA_Server_delete(UA_Server *server) {
  82. /* Delete all internal data */
  83. UA_SecureChannelManager_deleteMembers(&server->secureChannelManager);
  84. UA_SessionManager_deleteMembers(&server->sessionManager);
  85. UA_RCU_LOCK();
  86. UA_NodeStore_delete(server->nodestore);
  87. UA_RCU_UNLOCK();
  88. UA_Array_delete(server->namespaces, server->namespacesSize, &UA_TYPES[UA_TYPES_STRING]);
  89. UA_Array_delete(server->endpointDescriptions, server->endpointDescriptionsSize,
  90. &UA_TYPES[UA_TYPES_ENDPOINTDESCRIPTION]);
  91. #ifdef UA_ENABLE_DISCOVERY
  92. registeredServer_list_entry *rs, *rs_tmp;
  93. LIST_FOREACH_SAFE(rs, &server->registeredServers, pointers, rs_tmp) {
  94. LIST_REMOVE(rs, pointers);
  95. UA_RegisteredServer_deleteMembers(&rs->registeredServer);
  96. UA_free(rs);
  97. }
  98. if(server->periodicServerRegisterCallback)
  99. UA_free(server->periodicServerRegisterCallback);
  100. # ifdef UA_ENABLE_DISCOVERY_MULTICAST
  101. if(server->config.applicationDescription.applicationType == UA_APPLICATIONTYPE_DISCOVERYSERVER)
  102. destroyMulticastDiscoveryServer(server);
  103. serverOnNetwork_list_entry *son, *son_tmp;
  104. LIST_FOREACH_SAFE(son, &server->serverOnNetwork, pointers, son_tmp) {
  105. LIST_REMOVE(son, pointers);
  106. UA_ServerOnNetwork_deleteMembers(&son->serverOnNetwork);
  107. if(son->pathTmp)
  108. UA_free(son->pathTmp);
  109. UA_free(son);
  110. }
  111. for(size_t i = 0; i < SERVER_ON_NETWORK_HASH_PRIME; i++) {
  112. serverOnNetwork_hash_entry* currHash = server->serverOnNetworkHash[i];
  113. while(currHash) {
  114. serverOnNetwork_hash_entry* nextHash = currHash->next;
  115. UA_free(currHash);
  116. currHash = nextHash;
  117. }
  118. }
  119. # endif
  120. #endif
  121. #ifdef UA_ENABLE_MULTITHREADING
  122. pthread_cond_destroy(&server->dispatchQueue_condition);
  123. pthread_mutex_destroy(&server->dispatchQueue_mutex);
  124. #endif
  125. /* Delete the timed work */
  126. UA_Timer_deleteMembers(&server->timer);
  127. /* Delete the server itself */
  128. UA_free(server);
  129. }
  130. /* Recurring cleanup. Removing unused and timed-out channels and sessions */
  131. static void
  132. UA_Server_cleanup(UA_Server *server, void *_) {
  133. UA_DateTime nowMonotonic = UA_DateTime_nowMonotonic();
  134. UA_SessionManager_cleanupTimedOut(&server->sessionManager, nowMonotonic);
  135. UA_SecureChannelManager_cleanupTimedOut(&server->secureChannelManager, nowMonotonic);
  136. #ifdef UA_ENABLE_DISCOVERY
  137. UA_Discovery_cleanupTimedOut(server, nowMonotonic);
  138. #endif
  139. }
  140. /* Create endpoints w/o endpointurl. It is added from the networklayers at startup */
  141. static void
  142. addEndpointDefinitions(UA_Server *server) {
  143. server->endpointDescriptions =
  144. (UA_EndpointDescription*)UA_Array_new(server->config.networkLayersSize,
  145. &UA_TYPES[UA_TYPES_ENDPOINTDESCRIPTION]);
  146. server->endpointDescriptionsSize = server->config.networkLayersSize;
  147. for(size_t i = 0; i < server->config.networkLayersSize; ++i) {
  148. UA_EndpointDescription *endpoint = &server->endpointDescriptions[i];
  149. endpoint->securityMode = UA_MESSAGESECURITYMODE_NONE;
  150. endpoint->securityPolicyUri =
  151. UA_STRING_ALLOC("http://opcfoundation.org/UA/SecurityPolicy#None");
  152. endpoint->transportProfileUri =
  153. UA_STRING_ALLOC("http://opcfoundation.org/UA-Profile/Transport/uatcp-uasc-uabinary");
  154. size_t policies = 0;
  155. if(server->config.accessControl.enableAnonymousLogin)
  156. ++policies;
  157. if(server->config.accessControl.enableUsernamePasswordLogin)
  158. ++policies;
  159. endpoint->userIdentityTokensSize = policies;
  160. endpoint->userIdentityTokens =
  161. (UA_UserTokenPolicy*)UA_Array_new(policies, &UA_TYPES[UA_TYPES_USERTOKENPOLICY]);
  162. size_t currentIndex = 0;
  163. if(server->config.accessControl.enableAnonymousLogin) {
  164. UA_UserTokenPolicy_init(&endpoint->userIdentityTokens[currentIndex]);
  165. endpoint->userIdentityTokens[currentIndex].tokenType = UA_USERTOKENTYPE_ANONYMOUS;
  166. endpoint->userIdentityTokens[currentIndex].policyId = UA_STRING_ALLOC(ANONYMOUS_POLICY);
  167. ++currentIndex;
  168. }
  169. if(server->config.accessControl.enableUsernamePasswordLogin) {
  170. UA_UserTokenPolicy_init(&endpoint->userIdentityTokens[currentIndex]);
  171. endpoint->userIdentityTokens[currentIndex].tokenType = UA_USERTOKENTYPE_USERNAME;
  172. endpoint->userIdentityTokens[currentIndex].policyId = UA_STRING_ALLOC(USERNAME_POLICY);
  173. }
  174. /* The standard says "the HostName specified in the Server Certificate is the
  175. same as the HostName contained in the endpointUrl provided in the
  176. EndpointDescription */
  177. UA_String_copy(&server->config.serverCertificate, &endpoint->serverCertificate);
  178. UA_ApplicationDescription_copy(&server->config.applicationDescription, &endpoint->server);
  179. /* copy the discovery url only once the networlayer has been started */
  180. // UA_String_copy(&server->config.networkLayers[i].discoveryUrl, &endpoint->endpointUrl);
  181. }
  182. }
  183. UA_Server *
  184. UA_Server_new(const UA_ServerConfig config) {
  185. UA_Server *server = (UA_Server *)UA_calloc(1, sizeof(UA_Server));
  186. if(!server)
  187. return NULL;
  188. server->config = config;
  189. server->startTime = UA_DateTime_now();
  190. server->nodestore = UA_NodeStore_new();
  191. /* Set a seed for non-cyptographic randomness */
  192. #ifndef UA_ENABLE_DETERMINISTIC_RNG
  193. UA_random_seed((UA_UInt64)UA_DateTime_now());
  194. #endif
  195. /* Initialize the handling of repeated callbacks */
  196. UA_Timer_init(&server->timer);
  197. /* Initialized the linked list for delayed callbacks */
  198. #ifndef UA_ENABLE_MULTITHREADING
  199. SLIST_INIT(&server->delayedCallbacks);
  200. #endif
  201. /* Initialized the dispatch queue for worker threads */
  202. #ifdef UA_ENABLE_MULTITHREADING
  203. rcu_init();
  204. cds_wfcq_init(&server->dispatchQueue_head, &server->dispatchQueue_tail);
  205. #endif
  206. /* Create Namespaces 0 and 1 */
  207. server->namespaces = (UA_String *)UA_Array_new(2, &UA_TYPES[UA_TYPES_STRING]);
  208. server->namespaces[0] = UA_STRING_ALLOC("http://opcfoundation.org/UA/");
  209. UA_String_copy(&server->config.applicationDescription.applicationUri, &server->namespaces[1]);
  210. server->namespacesSize = 2;
  211. /* Create Endpoint Definitions */
  212. addEndpointDefinitions(server);
  213. /* Initialized SecureChannel and Session managers */
  214. UA_SecureChannelManager_init(&server->secureChannelManager, server);
  215. UA_SessionManager_init(&server->sessionManager, server);
  216. /* Add a regular callback for cleanup and maintenance */
  217. UA_Server_addRepeatedCallback(server, (UA_ServerCallback)UA_Server_cleanup, NULL,
  218. 10000, NULL);
  219. /* Initialized discovery database */
  220. #ifdef UA_ENABLE_DISCOVERY
  221. LIST_INIT(&server->registeredServers);
  222. server->registeredServersSize = 0;
  223. server->periodicServerRegisterCallback = NULL;
  224. server->registerServerCallback = NULL;
  225. server->registerServerCallbackData = NULL;
  226. #endif
  227. /* Initialize multicast discovery */
  228. #if defined(UA_ENABLE_DISCOVERY) && defined(UA_ENABLE_DISCOVERY_MULTICAST)
  229. server->mdnsDaemon = NULL;
  230. server->mdnsSocket = 0;
  231. server->mdnsMainSrvAdded = UA_FALSE;
  232. if(server->config.applicationDescription.applicationType == UA_APPLICATIONTYPE_DISCOVERYSERVER)
  233. initMulticastDiscoveryServer(server);
  234. LIST_INIT(&server->serverOnNetwork);
  235. server->serverOnNetworkSize = 0;
  236. server->serverOnNetworkRecordIdCounter = 0;
  237. server->serverOnNetworkRecordIdLastReset = UA_DateTime_now();
  238. memset(server->serverOnNetworkHash, 0,
  239. sizeof(struct serverOnNetwork_hash_entry*) * SERVER_ON_NETWORK_HASH_PRIME);
  240. server->serverOnNetworkCallback = NULL;
  241. server->serverOnNetworkCallbackData = NULL;
  242. #endif
  243. /* Initialize Namespace 0 */
  244. #ifndef UA_ENABLE_GENERATE_NAMESPACE0
  245. UA_Server_createNS0(server);
  246. #else
  247. ua_namespaceinit_generated(server);
  248. #endif
  249. return server;
  250. }
  251. /*****************/
  252. /* Repeated Jobs */
  253. /*****************/
  254. UA_StatusCode
  255. UA_Server_addRepeatedCallback(UA_Server *server, UA_ServerCallback callback,
  256. void *data, UA_UInt32 interval,
  257. UA_UInt64 *callbackId) {
  258. return UA_Timer_addRepeatedCallback(&server->timer, (UA_TimerCallback)callback,
  259. data, interval, callbackId);
  260. }
  261. UA_StatusCode
  262. UA_Server_changeRepeatedCallbackInterval(UA_Server *server, UA_UInt64 callbackId,
  263. UA_UInt32 interval) {
  264. return UA_Timer_changeRepeatedCallbackInterval(&server->timer, callbackId, interval);
  265. }
  266. UA_StatusCode
  267. UA_Server_removeRepeatedCallback(UA_Server *server, UA_UInt64 callbackId) {
  268. return UA_Timer_removeRepeatedCallback(&server->timer, callbackId);
  269. }