ua_server.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  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. #ifdef UA_ENABLE_GENERATE_NAMESPACE0
  7. #include "ua_namespaceinit_generated.h"
  8. #endif
  9. /**********************/
  10. /* Namespace Handling */
  11. /**********************/
  12. UA_UInt16 addNamespace(UA_Server *server, const UA_String name) {
  13. /* Check if the namespace already exists in the server's namespace array */
  14. for(UA_UInt16 i = 0; i < server->namespacesSize; ++i) {
  15. if(UA_String_equal(&name, &server->namespaces[i]))
  16. return i;
  17. }
  18. /* Make the array bigger */
  19. UA_String *newNS = (UA_String*)UA_realloc(server->namespaces,
  20. sizeof(UA_String) * (server->namespacesSize + 1));
  21. if(!newNS)
  22. return 0;
  23. server->namespaces = newNS;
  24. /* Copy the namespace string */
  25. UA_StatusCode retval = UA_String_copy(&name, &server->namespaces[server->namespacesSize]);
  26. if(retval != UA_STATUSCODE_GOOD)
  27. return 0;
  28. /* Announce the change (otherwise, the array appears unchanged) */
  29. ++server->namespacesSize;
  30. return (UA_UInt16)(server->namespacesSize - 1);
  31. }
  32. UA_UInt16 UA_Server_addNamespace(UA_Server *server, const char* name) {
  33. /* Override const attribute to get string (dirty hack) */
  34. UA_String nameString;
  35. nameString.length = strlen(name);
  36. nameString.data = (UA_Byte*)(uintptr_t)name;
  37. return addNamespace(server, nameString);
  38. }
  39. UA_StatusCode
  40. UA_Server_forEachChildNodeCall(UA_Server *server, UA_NodeId parentNodeId,
  41. UA_NodeIteratorCallback callback, void *handle) {
  42. const UA_Node *parent =
  43. server->config.nodestore.getNode(server->config.nodestore.context,
  44. &parentNodeId);
  45. if(!parent)
  46. return UA_STATUSCODE_BADNODEIDINVALID;
  47. /* TODO: We need to do an ugly copy of the references array since users may
  48. * delete references from within the callback. In single-threaded mode this
  49. * changes the same node we point at here. In multi-threaded mode, this
  50. * creates a new copy as nodes are truly immutable. */
  51. UA_ReferenceNode *refs = NULL;
  52. size_t refssize = parent->referencesSize;
  53. UA_StatusCode retval = UA_Array_copy(parent->references, parent->referencesSize,
  54. (void**)&refs, &UA_TYPES[UA_TYPES_REFERENCENODE]);
  55. if(retval != UA_STATUSCODE_GOOD) {
  56. server->config.nodestore.releaseNode(server->config.nodestore.context, parent);
  57. return retval;
  58. }
  59. for(size_t i = parent->referencesSize; i > 0; --i) {
  60. UA_ReferenceNode *ref = &refs[i - 1];
  61. retval |= callback(ref->targetId.nodeId, ref->isInverse,
  62. ref->referenceTypeId, handle);
  63. }
  64. server->config.nodestore.releaseNode(server->config.nodestore.context, parent);
  65. UA_Array_delete(refs, refssize, &UA_TYPES[UA_TYPES_REFERENCENODE]);
  66. return retval;
  67. }
  68. /********************/
  69. /* Server Lifecycle */
  70. /********************/
  71. /* The server needs to be stopped before it can be deleted */
  72. void UA_Server_delete(UA_Server *server) {
  73. /* Delete all internal data */
  74. UA_SecureChannelManager_deleteMembers(&server->secureChannelManager);
  75. UA_SessionManager_deleteMembers(&server->sessionManager);
  76. UA_Array_delete(server->namespaces, server->namespacesSize, &UA_TYPES[UA_TYPES_STRING]);
  77. #ifdef UA_ENABLE_DISCOVERY
  78. registeredServer_list_entry *rs, *rs_tmp;
  79. LIST_FOREACH_SAFE(rs, &server->registeredServers, pointers, rs_tmp) {
  80. LIST_REMOVE(rs, pointers);
  81. UA_RegisteredServer_deleteMembers(&rs->registeredServer);
  82. UA_free(rs);
  83. }
  84. periodicServerRegisterCallback_entry *ps, *ps_tmp;
  85. LIST_FOREACH_SAFE(ps, &server->periodicServerRegisterCallbacks, pointers, ps_tmp) {
  86. LIST_REMOVE(ps, pointers);
  87. UA_free(ps->callback);
  88. UA_free(ps);
  89. }
  90. # ifdef UA_ENABLE_DISCOVERY_MULTICAST
  91. if(server->config.applicationDescription.applicationType == UA_APPLICATIONTYPE_DISCOVERYSERVER)
  92. destroyMulticastDiscoveryServer(server);
  93. serverOnNetwork_list_entry *son, *son_tmp;
  94. LIST_FOREACH_SAFE(son, &server->serverOnNetwork, pointers, son_tmp) {
  95. LIST_REMOVE(son, pointers);
  96. UA_ServerOnNetwork_deleteMembers(&son->serverOnNetwork);
  97. if(son->pathTmp)
  98. UA_free(son->pathTmp);
  99. UA_free(son);
  100. }
  101. for(size_t i = 0; i < SERVER_ON_NETWORK_HASH_PRIME; i++) {
  102. serverOnNetwork_hash_entry* currHash = server->serverOnNetworkHash[i];
  103. while(currHash) {
  104. serverOnNetwork_hash_entry* nextHash = currHash->next;
  105. UA_free(currHash);
  106. currHash = nextHash;
  107. }
  108. }
  109. # endif
  110. #endif
  111. #ifdef UA_ENABLE_MULTITHREADING
  112. pthread_cond_destroy(&server->dispatchQueue_condition);
  113. pthread_mutex_destroy(&server->dispatchQueue_mutex);
  114. #endif
  115. /* Delete the timed work */
  116. UA_Timer_deleteMembers(&server->timer);
  117. /* Delete the server itself */
  118. UA_free(server);
  119. }
  120. /* Recurring cleanup. Removing unused and timed-out channels and sessions */
  121. static void
  122. UA_Server_cleanup(UA_Server *server, void *_) {
  123. UA_DateTime nowMonotonic = UA_DateTime_nowMonotonic();
  124. UA_SessionManager_cleanupTimedOut(&server->sessionManager, nowMonotonic);
  125. UA_SecureChannelManager_cleanupTimedOut(&server->secureChannelManager, nowMonotonic);
  126. #ifdef UA_ENABLE_DISCOVERY
  127. UA_Discovery_cleanupTimedOut(server, nowMonotonic);
  128. #endif
  129. }
  130. static void initNamespace0(UA_Server *server) {
  131. /* Load nodes and references generated from the XML ns0 definition */
  132. server->bootstrapNS0 = true;
  133. ua_namespace0(server);
  134. server->bootstrapNS0 = false;
  135. /* NamespaceArray */
  136. UA_DataSource namespaceDataSource = {.handle = server, .read = readNamespaces, .write = NULL};
  137. UA_Server_setVariableNode_dataSource(server,
  138. UA_NODEID_NUMERIC(0, UA_NS0ID_SERVER_NAMESPACEARRAY), namespaceDataSource);
  139. /* ServerArray */
  140. writeNs0VariableArray(server, UA_NS0ID_SERVER_SERVERARRAY,
  141. &server->config.applicationDescription.applicationUri,
  142. 1, &UA_TYPES[UA_TYPES_STRING]);
  143. /* LocaleIdArray */
  144. UA_String locale_en = UA_STRING("en");
  145. writeNs0VariableArray(server, UA_NS0ID_SERVER_SERVERCAPABILITIES_LOCALEIDARRAY,
  146. &locale_en, 1, &UA_TYPES[UA_TYPES_STRING]);
  147. /* MaxBrowseContinuationPoints */
  148. UA_UInt16 maxBrowseContinuationPoints = MAXCONTINUATIONPOINTS;
  149. writeNs0Variable(server, UA_NS0ID_SERVER_SERVERCAPABILITIES_MAXBROWSECONTINUATIONPOINTS,
  150. &maxBrowseContinuationPoints, &UA_TYPES[UA_TYPES_UINT16]);
  151. /* ServerProfileArray */
  152. UA_String profileArray[4];
  153. UA_UInt16 profileArraySize = 0;
  154. #define ADDPROFILEARRAY(x) profileArray[profileArraySize++] = UA_STRING_ALLOC(x)
  155. ADDPROFILEARRAY("http://opcfoundation.org/UA-Profile/Server/NanoEmbeddedDevice");
  156. #ifdef UA_ENABLE_NODEMANAGEMENT
  157. ADDPROFILEARRAY("http://opcfoundation.org/UA-Profile/Server/NodeManagement");
  158. #endif
  159. #ifdef UA_ENABLE_METHODCALLS
  160. ADDPROFILEARRAY("http://opcfoundation.org/UA-Profile/Server/Methods");
  161. #endif
  162. #ifdef UA_ENABLE_SUBSCRIPTIONS
  163. ADDPROFILEARRAY("http://opcfoundation.org/UA-Profile/Server/EmbeddedDataChangeSubscription");
  164. #endif
  165. writeNs0VariableArray(server, UA_NS0ID_SERVER_SERVERCAPABILITIES_SERVERPROFILEARRAY,
  166. profileArray, profileArraySize, &UA_TYPES[UA_TYPES_STRING]);
  167. /* MaxQueryContinuationPoints */
  168. UA_UInt16 maxQueryContinuationPoints = 0;
  169. writeNs0Variable(server, UA_NS0ID_SERVER_SERVERCAPABILITIES_MAXQUERYCONTINUATIONPOINTS,
  170. &maxQueryContinuationPoints, &UA_TYPES[UA_TYPES_UINT16]);
  171. /* MaxHistoryContinuationPoints */
  172. UA_UInt16 maxHistoryContinuationPoints = 0;
  173. writeNs0Variable(server, UA_NS0ID_SERVER_SERVERCAPABILITIES_MAXHISTORYCONTINUATIONPOINTS,
  174. &maxHistoryContinuationPoints, &UA_TYPES[UA_TYPES_UINT16]);
  175. /* MinSupportedSampleRate */
  176. writeNs0Variable(server, UA_NS0ID_SERVER_SERVERCAPABILITIES_MINSUPPORTEDSAMPLERATE,
  177. &server->config.samplingIntervalLimits.min, &UA_TYPES[UA_TYPES_UINT16]);
  178. /* ServerDiagnostics - ServerDiagnosticsSummary */
  179. UA_ServerDiagnosticsSummaryDataType serverDiagnosticsSummary;
  180. UA_ServerDiagnosticsSummaryDataType_init(&serverDiagnosticsSummary);
  181. writeNs0Variable(server, UA_NS0ID_SERVER_SERVERDIAGNOSTICS_SERVERDIAGNOSTICSSUMMARY,
  182. &serverDiagnosticsSummary, &UA_TYPES[UA_TYPES_SERVERDIAGNOSTICSSUMMARYDATATYPE]);
  183. /* ServerDiagnostics - EnabledFlag */
  184. UA_Boolean enabledFlag = false;
  185. writeNs0Variable(server, UA_NS0ID_SERVER_SERVERDIAGNOSTICS_ENABLEDFLAG,
  186. &enabledFlag, &UA_TYPES[UA_TYPES_BOOLEAN]);
  187. /* ServerStatus */
  188. UA_DataSource serverStatus = {.handle = server, .read = readStatus, .write = NULL};
  189. UA_Server_setVariableNode_dataSource(server,
  190. UA_NODEID_NUMERIC(0, UA_NS0ID_SERVER_SERVERSTATUS), serverStatus);
  191. /* StartTime */
  192. writeNs0Variable(server, UA_NS0ID_SERVER_SERVERSTATUS_STARTTIME,
  193. &server->startTime, &UA_TYPES[UA_TYPES_DATETIME]);
  194. /* CurrentTime */
  195. UA_DataSource currentTime = {.handle = server, .read = readCurrentTime, .write = NULL};
  196. UA_Server_setVariableNode_dataSource(server,
  197. UA_NODEID_NUMERIC(0, UA_NS0ID_SERVER_SERVERSTATUS), currentTime);
  198. /* State */
  199. UA_ServerState state = UA_SERVERSTATE_RUNNING;
  200. writeNs0Variable(server, UA_NS0ID_SERVER_SERVERSTATUS_STATE,
  201. &state, &UA_TYPES[UA_TYPES_SERVERSTATE]);
  202. /* BuildInfo */
  203. writeNs0Variable(server, UA_NS0ID_SERVER_SERVERSTATUS_BUILDINFO,
  204. &server->config.buildInfo, &UA_TYPES[UA_TYPES_BUILDINFO]);
  205. /* BuildInfo - ProductUri */
  206. writeNs0Variable(server, UA_NS0ID_SERVER_SERVERSTATUS_BUILDINFO_PRODUCTURI,
  207. &server->config.buildInfo.productUri, &UA_TYPES[UA_TYPES_STRING]);
  208. /* BuildInfo - ManufacturerName */
  209. writeNs0Variable(server, UA_NS0ID_SERVER_SERVERSTATUS_BUILDINFO_MANUFACTURERNAME,
  210. &server->config.buildInfo.manufacturerName, &UA_TYPES[UA_TYPES_STRING]);
  211. /* BuildInfo - ProductName */
  212. writeNs0Variable(server, UA_NS0ID_SERVER_SERVERSTATUS_BUILDINFO_PRODUCTNAME,
  213. &server->config.buildInfo.productName, &UA_TYPES[UA_TYPES_STRING]);
  214. /* BuildInfo - SoftwareVersion */
  215. writeNs0Variable(server, UA_NS0ID_SERVER_SERVERSTATUS_BUILDINFO_SOFTWAREVERSION,
  216. &server->config.buildInfo.softwareVersion, &UA_TYPES[UA_TYPES_STRING]);
  217. /* BuildInfo - BuildNumber */
  218. writeNs0Variable(server, UA_NS0ID_SERVER_SERVERSTATUS_BUILDINFO_BUILDNUMBER,
  219. &server->config.buildInfo.buildNumber, &UA_TYPES[UA_TYPES_STRING]);
  220. /* BuildInfo - BuildDate */
  221. writeNs0Variable(server, UA_NS0ID_SERVER_SERVERSTATUS_BUILDINFO_BUILDDATE,
  222. &server->config.buildInfo.buildDate, &UA_TYPES[UA_TYPES_DATETIME]);
  223. /* SecondsTillShutdown */
  224. UA_UInt32 secondsTillShutdown = 0;
  225. writeNs0Variable(server, UA_NS0ID_SERVER_SERVERSTATUS_SECONDSTILLSHUTDOWN,
  226. &secondsTillShutdown, &UA_TYPES[UA_TYPES_UINT32]);
  227. /* ShutDownReason */
  228. UA_LocalizedText shutdownReason;
  229. UA_LocalizedText_init(&shutdownReason);
  230. writeNs0Variable(server, UA_NS0ID_SERVER_SERVERSTATUS_SHUTDOWNREASON,
  231. &shutdownReason, &UA_TYPES[UA_TYPES_LOCALIZEDTEXT]);
  232. /* ServiceLevel */
  233. UA_DataSource serviceLevel = {.handle = server, .read = readServiceLevel, .write = NULL};
  234. UA_Server_setVariableNode_dataSource(server,
  235. UA_NODEID_NUMERIC(0, UA_NS0ID_SERVER_SERVICELEVEL), serviceLevel);
  236. /* Auditing */
  237. UA_DataSource auditing = {.handle = server, .read = readAuditing, .write = NULL};
  238. UA_Server_setVariableNode_dataSource(server,
  239. UA_NODEID_NUMERIC(0, UA_NS0ID_SERVER_AUDITING), auditing);
  240. /* Redundancy Support */
  241. /* TODO: Use enum */
  242. UA_Int32 redundancySupport = 0;
  243. writeNs0Variable(server, UA_NS0ID_SERVER_SERVERREDUNDANCY_REDUNDANCYSUPPORT,
  244. &redundancySupport, &UA_TYPES[UA_TYPES_INT32]);
  245. #if defined(UA_ENABLE_METHODCALLS) && defined(UA_ENABLE_SUBSCRIPTIONS)
  246. UA_Argument inputArguments;
  247. UA_Argument_init(&inputArguments);
  248. inputArguments.dataType = UA_TYPES[UA_TYPES_UINT32].typeId;
  249. inputArguments.name = UA_STRING("SubscriptionId");
  250. inputArguments.valueRank = -1; /* scalar argument */
  251. UA_Argument outputArguments[2];
  252. UA_Argument_init(&outputArguments[0]);
  253. outputArguments[0].dataType = UA_TYPES[UA_TYPES_UINT32].typeId;
  254. outputArguments[0].name = UA_STRING("ServerHandles");
  255. outputArguments[0].valueRank = 1;
  256. UA_Argument_init(&outputArguments[1]);
  257. outputArguments[1].dataType = UA_TYPES[UA_TYPES_UINT32].typeId;
  258. outputArguments[1].name = UA_STRING("ClientHandles");
  259. outputArguments[1].valueRank = 1;
  260. UA_MethodAttributes addmethodattributes;
  261. UA_MethodAttributes_init(&addmethodattributes);
  262. addmethodattributes.displayName = UA_LOCALIZEDTEXT("", "GetMonitoredItems");
  263. addmethodattributes.executable = true;
  264. addmethodattributes.userExecutable = true;
  265. UA_Server_addMethodNode(server, UA_NODEID_NUMERIC(0, UA_NS0ID_SERVER_GETMONITOREDITEMS),
  266. UA_NODEID_NUMERIC(0, UA_NS0ID_SERVER),
  267. UA_NODEID_NUMERIC(0, UA_NS0ID_HASCOMPONENT),
  268. UA_QUALIFIEDNAME(0, "GetMonitoredItems"), addmethodattributes, readMonitoredItems
  269. , /* callback of the method node */
  270. NULL, /* handle passed with the callback */
  271. 1, &inputArguments,
  272. 2, outputArguments,
  273. NULL);
  274. #endif
  275. }
  276. /********************/
  277. /* Server Lifecycle */
  278. /********************/
  279. UA_Server *
  280. UA_Server_new(const UA_ServerConfig *config) {
  281. UA_Server *server = (UA_Server *)UA_calloc(1, sizeof(UA_Server));
  282. if(!server)
  283. return NULL;
  284. if(config->endpointsSize == 0) {
  285. UA_LOG_FATAL(config->logger,
  286. UA_LOGCATEGORY_SERVER,
  287. "There has to be at least one endpoint.");
  288. UA_free(server);
  289. return NULL;
  290. }
  291. server->config = *config;
  292. server->startTime = UA_DateTime_now();
  293. /* Set a seed for non-cyptographic randomness */
  294. #ifndef UA_ENABLE_DETERMINISTIC_RNG
  295. UA_random_seed((UA_UInt64)UA_DateTime_now());
  296. #endif
  297. /* Initialize the handling of repeated callbacks */
  298. UA_Timer_init(&server->timer);
  299. /* Initialized the linked list for delayed callbacks */
  300. #ifndef UA_ENABLE_MULTITHREADING
  301. SLIST_INIT(&server->delayedCallbacks);
  302. #endif
  303. /* Initialized the dispatch queue for worker threads */
  304. #ifdef UA_ENABLE_MULTITHREADING
  305. cds_wfcq_init(&server->dispatchQueue_head, &server->dispatchQueue_tail);
  306. #endif
  307. /* Create Namespaces 0 and 1 */
  308. server->namespaces = (UA_String *)UA_Array_new(2, &UA_TYPES[UA_TYPES_STRING]);
  309. server->namespaces[0] = UA_STRING_ALLOC("http://opcfoundation.org/UA/");
  310. UA_String_copy(&server->config.applicationDescription.applicationUri, &server->namespaces[1]);
  311. server->namespacesSize = 2;
  312. /* Initialized SecureChannel and Session managers */
  313. UA_SecureChannelManager_init(&server->secureChannelManager, server);
  314. UA_SessionManager_init(&server->sessionManager, server);
  315. #ifdef UA_ENABLE_MULTITHREADING
  316. rcu_init();
  317. cds_wfcq_init(&server->dispatchQueue_head, &server->dispatchQueue_tail);
  318. cds_lfs_init(&server->mainLoopJobs);
  319. #endif
  320. /* Add a regular callback for cleanup and maintenance */
  321. UA_Server_addRepeatedCallback(server, (UA_ServerCallback)UA_Server_cleanup, NULL,
  322. 10000, NULL);
  323. /* Initialized discovery database */
  324. #ifdef UA_ENABLE_DISCOVERY
  325. LIST_INIT(&server->registeredServers);
  326. server->registeredServersSize = 0;
  327. LIST_INIT(&server->periodicServerRegisterCallbacks);
  328. server->registerServerCallback = NULL;
  329. server->registerServerCallbackData = NULL;
  330. #endif
  331. /* Initialize multicast discovery */
  332. #if defined(UA_ENABLE_DISCOVERY) && defined(UA_ENABLE_DISCOVERY_MULTICAST)
  333. server->mdnsDaemon = NULL;
  334. server->mdnsSocket = 0;
  335. server->mdnsMainSrvAdded = UA_FALSE;
  336. if(server->config.applicationDescription.applicationType == UA_APPLICATIONTYPE_DISCOVERYSERVER)
  337. initMulticastDiscoveryServer(server);
  338. LIST_INIT(&server->serverOnNetwork);
  339. server->serverOnNetworkSize = 0;
  340. server->serverOnNetworkRecordIdCounter = 0;
  341. server->serverOnNetworkRecordIdLastReset = UA_DateTime_now();
  342. memset(server->serverOnNetworkHash, 0,
  343. sizeof(struct serverOnNetwork_hash_entry*) * SERVER_ON_NETWORK_HASH_PRIME);
  344. server->serverOnNetworkCallback = NULL;
  345. server->serverOnNetworkCallbackData = NULL;
  346. #endif
  347. /* Initialize namespace 0*/
  348. initNamespace0(server);
  349. return server;
  350. }
  351. /*****************/
  352. /* Repeated Jobs */
  353. /*****************/
  354. UA_StatusCode
  355. UA_Server_addRepeatedCallback(UA_Server *server, UA_ServerCallback callback,
  356. void *data, UA_UInt32 interval,
  357. UA_UInt64 *callbackId) {
  358. return UA_Timer_addRepeatedCallback(&server->timer, (UA_TimerCallback)callback,
  359. data, interval, callbackId);
  360. }
  361. UA_StatusCode
  362. UA_Server_changeRepeatedCallbackInterval(UA_Server *server, UA_UInt64 callbackId,
  363. UA_UInt32 interval) {
  364. return UA_Timer_changeRepeatedCallbackInterval(&server->timer, callbackId, interval);
  365. }
  366. UA_StatusCode
  367. UA_Server_removeRepeatedCallback(UA_Server *server, UA_UInt64 callbackId) {
  368. return UA_Timer_removeRepeatedCallback(&server->timer, callbackId);
  369. }