ua_services_discovery.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  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-2017 (c) Fraunhofer IOSB (Author: Julius Pfrommer)
  6. * Copyright 2014-2016 (c) Sten Grüner
  7. * Copyright 2014, 2017 (c) Florian Palm
  8. * Copyright 2016 (c) Oleksiy Vasylyev
  9. * Copyright 2016-2017 (c) Stefan Profanter, fortiss GmbH
  10. * Copyright 2017 (c) frax2222
  11. * Copyright 2017 (c) Mark Giraud, Fraunhofer IOSB
  12. */
  13. #include "ua_server_internal.h"
  14. #include "ua_services.h"
  15. #ifdef UA_ENABLE_DISCOVERY
  16. #include "ua_client_internal.h"
  17. static UA_StatusCode
  18. setApplicationDescriptionFromRegisteredServer(const UA_FindServersRequest *request,
  19. UA_ApplicationDescription *target,
  20. const UA_RegisteredServer *registeredServer) {
  21. UA_ApplicationDescription_init(target);
  22. UA_StatusCode retval = UA_String_copy(&registeredServer->serverUri, &target->applicationUri);
  23. if(retval != UA_STATUSCODE_GOOD)
  24. return retval;
  25. retval = UA_String_copy(&registeredServer->productUri, &target->productUri);
  26. if(retval != UA_STATUSCODE_GOOD)
  27. return retval;
  28. // if the client requests a specific locale, select the corresponding server name
  29. if(request->localeIdsSize) {
  30. UA_Boolean appNameFound = false;
  31. for(size_t i =0; i<request->localeIdsSize && !appNameFound; i++) {
  32. for(size_t j =0; j<registeredServer->serverNamesSize; j++) {
  33. if(UA_String_equal(&request->localeIds[i], &registeredServer->serverNames[j].locale)) {
  34. retval = UA_LocalizedText_copy(&registeredServer->serverNames[j],
  35. &target->applicationName);
  36. if(retval != UA_STATUSCODE_GOOD)
  37. return retval;
  38. appNameFound = true;
  39. break;
  40. }
  41. }
  42. }
  43. // server does not have the requested local, therefore we can select the
  44. // most suitable one
  45. if(!appNameFound && registeredServer->serverNamesSize) {
  46. retval = UA_LocalizedText_copy(&registeredServer->serverNames[0],
  47. &target->applicationName);
  48. if(retval != UA_STATUSCODE_GOOD)
  49. return retval;
  50. }
  51. } else if(registeredServer->serverNamesSize) {
  52. // just take the first name
  53. retval = UA_LocalizedText_copy(&registeredServer->serverNames[0], &target->applicationName);
  54. if(retval != UA_STATUSCODE_GOOD)
  55. return retval;
  56. }
  57. target->applicationType = registeredServer->serverType;
  58. retval = UA_String_copy(&registeredServer->gatewayServerUri, &target->gatewayServerUri);
  59. if(retval != UA_STATUSCODE_GOOD)
  60. return retval;
  61. // TODO where do we get the discoveryProfileUri for application data?
  62. target->discoveryUrlsSize = registeredServer->discoveryUrlsSize;
  63. if(registeredServer->discoveryUrlsSize) {
  64. size_t duSize = sizeof(UA_String) * registeredServer->discoveryUrlsSize;
  65. target->discoveryUrls = (UA_String *)UA_malloc(duSize);
  66. if(!target->discoveryUrls)
  67. return UA_STATUSCODE_BADOUTOFMEMORY;
  68. for(size_t i = 0; i < registeredServer->discoveryUrlsSize; i++) {
  69. retval = UA_String_copy(&registeredServer->discoveryUrls[i], &target->discoveryUrls[i]);
  70. if(retval != UA_STATUSCODE_GOOD)
  71. return retval;
  72. }
  73. }
  74. return retval;
  75. }
  76. #endif
  77. static UA_StatusCode
  78. setApplicationDescriptionFromServer(UA_ApplicationDescription *target, const UA_Server *server) {
  79. /* Copy ApplicationDescription from the config */
  80. UA_StatusCode result = UA_ApplicationDescription_copy(&server->config.applicationDescription, target);
  81. if(result != UA_STATUSCODE_GOOD)
  82. return result;
  83. /* add the discoveryUrls from the networklayers */
  84. size_t discSize = sizeof(UA_String) * (target->discoveryUrlsSize + server->config.networkLayersSize);
  85. UA_String* disc = (UA_String *)UA_realloc(target->discoveryUrls, discSize);
  86. if(!disc)
  87. return UA_STATUSCODE_BADOUTOFMEMORY;
  88. size_t existing = target->discoveryUrlsSize;
  89. target->discoveryUrls = disc;
  90. target->discoveryUrlsSize += server->config.networkLayersSize;
  91. // TODO: Add nl only if discoveryUrl not already present
  92. for(size_t i = 0; i < server->config.networkLayersSize; i++) {
  93. UA_ServerNetworkLayer* nl = &server->config.networkLayers[i];
  94. UA_String_copy(&nl->discoveryUrl, &target->discoveryUrls[existing + i]);
  95. }
  96. return UA_STATUSCODE_GOOD;
  97. }
  98. void Service_FindServers(UA_Server *server, UA_Session *session,
  99. const UA_FindServersRequest *request,
  100. UA_FindServersResponse *response) {
  101. UA_LOG_DEBUG_SESSION(&server->config.logger, session, "Processing FindServersRequest");
  102. /* Return the server itself? */
  103. UA_Boolean foundSelf = false;
  104. if(request->serverUrisSize) {
  105. for(size_t i = 0; i < request->serverUrisSize; i++) {
  106. if(UA_String_equal(&request->serverUris[i],
  107. &server->config.applicationDescription.applicationUri)) {
  108. foundSelf = true;
  109. break;
  110. }
  111. }
  112. } else {
  113. foundSelf = true;
  114. }
  115. #ifndef UA_ENABLE_DISCOVERY
  116. if(!foundSelf)
  117. return;
  118. UA_ApplicationDescription *ad = UA_ApplicationDescription_new();
  119. if(!ad) {
  120. response->responseHeader.serviceResult = UA_STATUSCODE_BADOUTOFMEMORY;
  121. return;
  122. }
  123. UA_StatusCode retval = setApplicationDescriptionFromServer(ad, server);
  124. if(retval != UA_STATUSCODE_GOOD) {
  125. UA_ApplicationDescription_delete(ad);
  126. response->responseHeader.serviceResult = UA_STATUSCODE_BADOUTOFMEMORY;
  127. return;
  128. }
  129. response->servers = ad;
  130. response->serversSize = 1;
  131. return;
  132. #else
  133. /* Temporarily store all the pointers which we found to avoid reiterating
  134. * through the list */
  135. size_t foundServersSize = 0;
  136. UA_STACKARRAY(UA_RegisteredServer*, foundServers, server->discoveryManager.registeredServersSize+1);
  137. registeredServer_list_entry* current;
  138. LIST_FOREACH(current, &server->discoveryManager.registeredServers, pointers) {
  139. if(request->serverUrisSize) {
  140. /* If client only requested a specific set of servers */
  141. for(size_t i = 0; i < request->serverUrisSize; i++) {
  142. if(UA_String_equal(&current->registeredServer.serverUri, &request->serverUris[i])) {
  143. foundServers[foundServersSize] = &current->registeredServer;
  144. foundServersSize++;
  145. break;
  146. }
  147. }
  148. } else {
  149. /* Return all registered servers */
  150. foundServers[foundServersSize] = &current->registeredServer;
  151. foundServersSize++;
  152. }
  153. }
  154. size_t allocSize = foundServersSize;
  155. if(foundSelf)
  156. allocSize++;
  157. /* Nothing to do? */
  158. if(allocSize == 0)
  159. return;
  160. /* Allocate memory */
  161. response->servers = (UA_ApplicationDescription*)UA_Array_new(allocSize, &UA_TYPES[UA_TYPES_APPLICATIONDESCRIPTION]);
  162. if(!response->servers) {
  163. response->responseHeader.serviceResult = UA_STATUSCODE_BADOUTOFMEMORY;
  164. return;
  165. }
  166. response->serversSize = allocSize;
  167. /* Copy into the response. TODO: Evaluate return codes */
  168. size_t pos = 0;
  169. if(foundSelf) {
  170. setApplicationDescriptionFromServer(&response->servers[pos++], server);
  171. }
  172. for(size_t i = 0; i < foundServersSize; i++) {
  173. setApplicationDescriptionFromRegisteredServer(request, &response->servers[pos++], foundServers[i]);
  174. }
  175. #endif
  176. }
  177. void
  178. Service_GetEndpoints(UA_Server *server, UA_Session *session,
  179. const UA_GetEndpointsRequest *request,
  180. UA_GetEndpointsResponse *response) {
  181. /* If the client expects to see a specific endpointurl, mirror it back. If
  182. not, clone the endpoints with the discovery url of all networklayers. */
  183. const UA_String *endpointUrl = &request->endpointUrl;
  184. if(endpointUrl->length > 0) {
  185. UA_LOG_DEBUG_SESSION(&server->config.logger, session,
  186. "Processing GetEndpointsRequest with endpointUrl "
  187. UA_PRINTF_STRING_FORMAT, UA_PRINTF_STRING_DATA(*endpointUrl));
  188. } else {
  189. UA_LOG_DEBUG_SESSION(&server->config.logger, session,
  190. "Processing GetEndpointsRequest with an empty endpointUrl");
  191. }
  192. /* test if the supported binary profile shall be returned */
  193. size_t reSize = sizeof(UA_Boolean) * server->config.endpointsSize;
  194. UA_STACKARRAY(UA_Boolean, relevant_endpoints, reSize);
  195. memset(relevant_endpoints, 0, reSize);
  196. size_t relevant_count = 0;
  197. if(request->profileUrisSize == 0) {
  198. for(size_t j = 0; j < server->config.endpointsSize; ++j)
  199. relevant_endpoints[j] = true;
  200. relevant_count = server->config.endpointsSize;
  201. } else {
  202. for(size_t j = 0; j < server->config.endpointsSize; ++j) {
  203. for(size_t i = 0; i < request->profileUrisSize; ++i) {
  204. if(!UA_String_equal(&request->profileUris[i],
  205. &server->config.endpoints[j].transportProfileUri))
  206. continue;
  207. relevant_endpoints[j] = true;
  208. ++relevant_count;
  209. break;
  210. }
  211. }
  212. }
  213. if(relevant_count == 0) {
  214. response->endpointsSize = 0;
  215. return;
  216. }
  217. /* Clone the endpoint for each networklayer? */
  218. size_t clone_times = 1;
  219. UA_Boolean nl_endpointurl = false;
  220. if(endpointUrl->length == 0) {
  221. clone_times = server->config.networkLayersSize;
  222. nl_endpointurl = true;
  223. }
  224. response->endpoints =
  225. (UA_EndpointDescription*)UA_Array_new(relevant_count * clone_times,
  226. &UA_TYPES[UA_TYPES_ENDPOINTDESCRIPTION]);
  227. if(!response->endpoints) {
  228. response->responseHeader.serviceResult = UA_STATUSCODE_BADOUTOFMEMORY;
  229. return;
  230. }
  231. response->endpointsSize = relevant_count * clone_times;
  232. size_t k = 0;
  233. UA_StatusCode retval;
  234. for(size_t i = 0; i < clone_times; ++i) {
  235. if(nl_endpointurl)
  236. endpointUrl = &server->config.networkLayers[i].discoveryUrl;
  237. for(size_t j = 0; j < server->config.endpointsSize; ++j) {
  238. if(!relevant_endpoints[j])
  239. continue;
  240. retval = UA_EndpointDescription_copy(&server->config.endpoints[j],
  241. &response->endpoints[k]);
  242. if(retval != UA_STATUSCODE_GOOD)
  243. goto error;
  244. retval = UA_String_copy(endpointUrl, &response->endpoints[k].endpointUrl);
  245. if(retval != UA_STATUSCODE_GOOD)
  246. goto error;
  247. ++k;
  248. }
  249. }
  250. return;
  251. error:
  252. response->responseHeader.serviceResult = retval;
  253. UA_Array_delete(response->endpoints, response->endpointsSize,
  254. &UA_TYPES[UA_TYPES_ENDPOINTDESCRIPTION]);
  255. response->endpoints = NULL;
  256. response->endpointsSize = 0;
  257. }
  258. #ifdef UA_ENABLE_DISCOVERY
  259. static void
  260. process_RegisterServer(UA_Server *server, UA_Session *session,
  261. const UA_RequestHeader* requestHeader,
  262. const UA_RegisteredServer *requestServer,
  263. const size_t requestDiscoveryConfigurationSize,
  264. const UA_ExtensionObject *requestDiscoveryConfiguration,
  265. UA_ResponseHeader* responseHeader,
  266. size_t *responseConfigurationResultsSize,
  267. UA_StatusCode **responseConfigurationResults,
  268. size_t *responseDiagnosticInfosSize,
  269. UA_DiagnosticInfo *responseDiagnosticInfos) {
  270. /* Find the server from the request in the registered list */
  271. registeredServer_list_entry* current;
  272. registeredServer_list_entry *registeredServer_entry = NULL;
  273. LIST_FOREACH(current, &server->discoveryManager.registeredServers, pointers) {
  274. if(UA_String_equal(&current->registeredServer.serverUri, &requestServer->serverUri)) {
  275. registeredServer_entry = current;
  276. break;
  277. }
  278. }
  279. UA_MdnsDiscoveryConfiguration *mdnsConfig = NULL;
  280. const UA_String* mdnsServerName = NULL;
  281. if(requestDiscoveryConfigurationSize) {
  282. *responseConfigurationResults =
  283. (UA_StatusCode *)UA_Array_new(requestDiscoveryConfigurationSize,
  284. &UA_TYPES[UA_TYPES_STATUSCODE]);
  285. if(!(*responseConfigurationResults)) {
  286. responseHeader->serviceResult = UA_STATUSCODE_BADOUTOFMEMORY;
  287. return;
  288. }
  289. *responseConfigurationResultsSize = requestDiscoveryConfigurationSize;
  290. for(size_t i = 0; i < requestDiscoveryConfigurationSize; i++) {
  291. const UA_ExtensionObject *object = &requestDiscoveryConfiguration[i];
  292. if(!mdnsConfig && (object->encoding == UA_EXTENSIONOBJECT_DECODED ||
  293. object->encoding == UA_EXTENSIONOBJECT_DECODED_NODELETE) &&
  294. (object->content.decoded.type == &UA_TYPES[UA_TYPES_MDNSDISCOVERYCONFIGURATION])) {
  295. mdnsConfig = (UA_MdnsDiscoveryConfiguration *)object->content.decoded.data;
  296. mdnsServerName = &mdnsConfig->mdnsServerName;
  297. (*responseConfigurationResults)[i] = UA_STATUSCODE_GOOD;
  298. } else {
  299. (*responseConfigurationResults)[i] = UA_STATUSCODE_BADNOTSUPPORTED;
  300. }
  301. }
  302. }
  303. if(!mdnsServerName && requestServer->serverNamesSize)
  304. mdnsServerName = &requestServer->serverNames[0].text;
  305. if(!mdnsServerName) {
  306. responseHeader->serviceResult = UA_STATUSCODE_BADSERVERNAMEMISSING;
  307. return;
  308. }
  309. if(requestServer->discoveryUrlsSize == 0) {
  310. responseHeader->serviceResult = UA_STATUSCODE_BADDISCOVERYURLMISSING;
  311. return;
  312. }
  313. if(requestServer->semaphoreFilePath.length) {
  314. #ifdef UA_ENABLE_DISCOVERY_SEMAPHORE
  315. char* filePath = (char*)
  316. UA_malloc(sizeof(char)*requestServer->semaphoreFilePath.length+1);
  317. if(!filePath) {
  318. UA_LOG_ERROR_SESSION(&server->config.logger, session,
  319. "Cannot allocate memory for semaphore path. Out of memory.");
  320. responseHeader->serviceResult = UA_STATUSCODE_BADOUTOFMEMORY;
  321. return;
  322. }
  323. memcpy(filePath, requestServer->semaphoreFilePath.data, requestServer->semaphoreFilePath.length );
  324. filePath[requestServer->semaphoreFilePath.length] = '\0';
  325. if(!UA_fileExists( filePath )) {
  326. responseHeader->serviceResult = UA_STATUSCODE_BADSEMPAHOREFILEMISSING;
  327. UA_free(filePath);
  328. return;
  329. }
  330. UA_free(filePath);
  331. #else
  332. UA_LOG_WARNING(&server->config.logger, UA_LOGCATEGORY_CLIENT,
  333. "Ignoring semaphore file path. open62541 not compiled "
  334. "with UA_ENABLE_DISCOVERY_SEMAPHORE=ON");
  335. #endif
  336. }
  337. #ifdef UA_ENABLE_DISCOVERY_MULTICAST
  338. if(server->config.discovery.mdnsEnable) {
  339. for(size_t i = 0; i < requestServer->discoveryUrlsSize; i++) {
  340. /* create TXT if is online and first index, delete TXT if is offline and last index */
  341. UA_Boolean updateTxt = (requestServer->isOnline && i==0) ||
  342. (!requestServer->isOnline && i==requestServer->discoveryUrlsSize);
  343. UA_Server_updateMdnsForDiscoveryUrl(server, mdnsServerName, mdnsConfig,
  344. &requestServer->discoveryUrls[i],
  345. requestServer->isOnline, updateTxt);
  346. }
  347. }
  348. #endif
  349. if(!requestServer->isOnline) {
  350. // server is shutting down. Remove it from the registered servers list
  351. if(!registeredServer_entry) {
  352. // server not found, show warning
  353. UA_LOG_WARNING_SESSION(&server->config.logger, session,
  354. "Could not unregister server %.*s. Not registered.",
  355. (int)requestServer->serverUri.length, requestServer->serverUri.data);
  356. responseHeader->serviceResult = UA_STATUSCODE_BADNOTHINGTODO;
  357. return;
  358. }
  359. if(server->discoveryManager.registerServerCallback)
  360. server->discoveryManager.
  361. registerServerCallback(requestServer,
  362. server->discoveryManager.registerServerCallbackData);
  363. // server found, remove from list
  364. LIST_REMOVE(registeredServer_entry, pointers);
  365. UA_RegisteredServer_deleteMembers(&registeredServer_entry->registeredServer);
  366. #ifndef UA_ENABLE_MULTITHREADING
  367. UA_free(registeredServer_entry);
  368. server->discoveryManager.registeredServersSize--;
  369. #else
  370. UA_atomic_subSize(&server->discoveryManager.registeredServersSize, 1);
  371. registeredServer_entry->delayedCleanup.callback = NULL; /* only free the structure */
  372. UA_WorkQueue_enqueueDelayed(&server->workQueue, &registeredServer_entry->delayedCleanup);
  373. #endif
  374. responseHeader->serviceResult = UA_STATUSCODE_GOOD;
  375. return;
  376. }
  377. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  378. if(!registeredServer_entry) {
  379. // server not yet registered, register it by adding it to the list
  380. UA_LOG_DEBUG_SESSION(&server->config.logger, session, "Registering new server: %.*s",
  381. (int)requestServer->serverUri.length, requestServer->serverUri.data);
  382. registeredServer_entry =
  383. (registeredServer_list_entry *)UA_malloc(sizeof(registeredServer_list_entry));
  384. if(!registeredServer_entry) {
  385. responseHeader->serviceResult = UA_STATUSCODE_BADOUTOFMEMORY;
  386. return;
  387. }
  388. LIST_INSERT_HEAD(&server->discoveryManager.registeredServers, registeredServer_entry, pointers);
  389. #ifndef UA_ENABLE_MULTITHREADING
  390. server->discoveryManager.registeredServersSize++;
  391. #else
  392. UA_atomic_addSize(&server->discoveryManager.registeredServersSize, 1);
  393. #endif
  394. if(server->discoveryManager.registerServerCallback)
  395. server->discoveryManager.
  396. registerServerCallback(requestServer,
  397. server->discoveryManager.registerServerCallbackData);
  398. } else {
  399. UA_RegisteredServer_deleteMembers(&registeredServer_entry->registeredServer);
  400. }
  401. // copy the data from the request into the list
  402. UA_RegisteredServer_copy(requestServer, &registeredServer_entry->registeredServer);
  403. registeredServer_entry->lastSeen = UA_DateTime_nowMonotonic();
  404. responseHeader->serviceResult = retval;
  405. }
  406. void Service_RegisterServer(UA_Server *server, UA_Session *session,
  407. const UA_RegisterServerRequest *request,
  408. UA_RegisterServerResponse *response) {
  409. UA_LOG_DEBUG_SESSION(&server->config.logger, session,
  410. "Processing RegisterServerRequest");
  411. process_RegisterServer(server, session, &request->requestHeader, &request->server, 0,
  412. NULL, &response->responseHeader, 0, NULL, 0, NULL);
  413. }
  414. void Service_RegisterServer2(UA_Server *server, UA_Session *session,
  415. const UA_RegisterServer2Request *request,
  416. UA_RegisterServer2Response *response) {
  417. UA_LOG_DEBUG_SESSION(&server->config.logger, session,
  418. "Processing RegisterServer2Request");
  419. process_RegisterServer(server, session, &request->requestHeader, &request->server,
  420. request->discoveryConfigurationSize, request->discoveryConfiguration,
  421. &response->responseHeader, &response->configurationResultsSize,
  422. &response->configurationResults, &response->diagnosticInfosSize,
  423. response->diagnosticInfos);
  424. }
  425. /* Cleanup server registration: If the semaphore file path is set, then it just
  426. * checks the existence of the file. When it is deleted, the registration is
  427. * removed. If there is no semaphore file, then the registration will be removed
  428. * if it is older than 60 minutes. */
  429. void UA_Discovery_cleanupTimedOut(UA_Server *server, UA_DateTime nowMonotonic) {
  430. UA_DateTime timedOut = nowMonotonic;
  431. // registration is timed out if lastSeen is older than 60 minutes (default
  432. // value, can be modified by user).
  433. if(server->config.discovery.cleanupTimeout)
  434. timedOut -= server->config.discovery.cleanupTimeout*UA_DATETIME_SEC;
  435. registeredServer_list_entry* current, *temp;
  436. LIST_FOREACH_SAFE(current, &server->discoveryManager.registeredServers, pointers, temp) {
  437. UA_Boolean semaphoreDeleted = false;
  438. #ifdef UA_ENABLE_DISCOVERY_SEMAPHORE
  439. if(current->registeredServer.semaphoreFilePath.length) {
  440. size_t fpSize = sizeof(char)*current->registeredServer.semaphoreFilePath.length+1;
  441. // todo: malloc may fail: return a statuscode
  442. char* filePath = (char *)UA_malloc(fpSize);
  443. if(filePath) {
  444. memcpy(filePath, current->registeredServer.semaphoreFilePath.data,
  445. current->registeredServer.semaphoreFilePath.length );
  446. filePath[current->registeredServer.semaphoreFilePath.length] = '\0';
  447. semaphoreDeleted = UA_fileExists(filePath) == false;
  448. UA_free(filePath);
  449. } else {
  450. UA_LOG_ERROR(&server->config.logger, UA_LOGCATEGORY_SERVER,
  451. "Cannot check registration semaphore. Out of memory");
  452. }
  453. }
  454. #endif
  455. if(semaphoreDeleted || (server->config.discovery.cleanupTimeout &&
  456. current->lastSeen < timedOut)) {
  457. if(semaphoreDeleted) {
  458. UA_LOG_INFO(&server->config.logger, UA_LOGCATEGORY_SERVER,
  459. "Registration of server with URI %.*s is removed because "
  460. "the semaphore file '%.*s' was deleted.",
  461. (int)current->registeredServer.serverUri.length,
  462. current->registeredServer.serverUri.data,
  463. (int)current->registeredServer.semaphoreFilePath.length,
  464. current->registeredServer.semaphoreFilePath.data);
  465. } else {
  466. // cppcheck-suppress unreadVariable
  467. UA_LOG_INFO(&server->config.logger, UA_LOGCATEGORY_SERVER,
  468. "Registration of server with URI %.*s has timed out and is removed.",
  469. (int)current->registeredServer.serverUri.length,
  470. current->registeredServer.serverUri.data);
  471. }
  472. LIST_REMOVE(current, pointers);
  473. UA_RegisteredServer_deleteMembers(&current->registeredServer);
  474. #ifndef UA_ENABLE_MULTITHREADING
  475. UA_free(current);
  476. server->discoveryManager.registeredServersSize--;
  477. #else
  478. UA_atomic_subSize(&server->discoveryManager.registeredServersSize, 1);
  479. current->delayedCleanup.callback = NULL; /* Only free the structure */
  480. UA_WorkQueue_enqueueDelayed(&server->workQueue, &current->delayedCleanup);
  481. #endif
  482. }
  483. }
  484. }
  485. struct PeriodicServerRegisterCallback {
  486. UA_UInt64 id;
  487. UA_Double this_interval;
  488. UA_Double default_interval;
  489. UA_Boolean registered;
  490. UA_Client* client;
  491. const char* discovery_server_url;
  492. };
  493. /* Called by the UA_Server callback. The OPC UA specification says:
  494. *
  495. * > If an error occurs during registration (e.g. the Discovery Server is not running) then the Server
  496. * > must periodically re-attempt registration. The frequency of these attempts should start at 1 second
  497. * > but gradually increase until the registration frequency is the same as what it would be if not
  498. * > errors occurred. The recommended approach would double the period each attempt until reaching the maximum.
  499. *
  500. * We will do so by using the additional data parameter which holds information
  501. * if the next interval is default or if it is a repeated call. */
  502. static void
  503. periodicServerRegister(UA_Server *server, void *data) {
  504. UA_assert(data != NULL);
  505. struct PeriodicServerRegisterCallback *cb = (struct PeriodicServerRegisterCallback *)data;
  506. /* Which URL to register on */
  507. // fixme: remove magic url
  508. const char * server_url;
  509. if(cb->discovery_server_url != NULL)
  510. server_url = cb->discovery_server_url;
  511. else
  512. server_url = "opc.tcp://localhost:4840";
  513. UA_StatusCode retval = UA_Client_connect_noSession(cb->client, server_url);
  514. if (retval == UA_STATUSCODE_GOOD) {
  515. /* Register
  516. You can also use a semaphore file. That file must exist. When the file is
  517. deleted, the server is automatically unregistered. The semaphore file has
  518. to be accessible by the discovery server
  519. UA_StatusCode retval = UA_Server_register_discovery(server,
  520. "opc.tcp://localhost:4840", "/path/to/some/file");
  521. */
  522. retval = UA_Server_register_discovery(server, cb->client, NULL);
  523. }
  524. if (cb->client->state == UA_CLIENTSTATE_CONNECTED) {
  525. UA_StatusCode retval1 = UA_Client_disconnect(cb->client);
  526. if(retval1 != UA_STATUSCODE_GOOD) {
  527. UA_LOG_WARNING(&server->config.logger, UA_LOGCATEGORY_SERVER,
  528. "Could not disconnect client from register server. StatusCode %s",
  529. UA_StatusCode_name(retval));
  530. }
  531. }
  532. /* Registering failed */
  533. if(retval != UA_STATUSCODE_GOOD) {
  534. UA_LOG_ERROR(&server->config.logger, UA_LOGCATEGORY_SERVER,
  535. "Could not register server with discovery server. "
  536. "Is the discovery server started? StatusCode %s",
  537. UA_StatusCode_name(retval));
  538. /* If the server was previously registered, retry in one second,
  539. * else, double the previous interval */
  540. UA_Double nextInterval = 1000.0;
  541. if(!cb->registered)
  542. nextInterval = cb->this_interval * 2;
  543. /* The interval should be smaller than the default interval */
  544. if(nextInterval > cb->default_interval)
  545. nextInterval = cb->default_interval;
  546. cb->this_interval = nextInterval;
  547. UA_Server_changeRepeatedCallbackInterval(server, cb->id, nextInterval);
  548. return;
  549. }
  550. /* Registering succeeded */
  551. UA_LOG_DEBUG(&server->config.logger, UA_LOGCATEGORY_SERVER,
  552. "Server successfully registered. Next periodical register will be in %d seconds",
  553. (int)(cb->default_interval/1000));
  554. if(!cb->registered) {
  555. retval = UA_Server_changeRepeatedCallbackInterval(server, cb->id, cb->default_interval);
  556. /* If changing the interval fails, try again after the next registering */
  557. if(retval == UA_STATUSCODE_GOOD)
  558. cb->registered = true;
  559. }
  560. }
  561. UA_StatusCode
  562. UA_Server_addPeriodicServerRegisterCallback(UA_Server *server,
  563. struct UA_Client *client,
  564. const char* discoveryServerUrl,
  565. UA_Double intervalMs,
  566. UA_Double delayFirstRegisterMs,
  567. UA_UInt64 *periodicCallbackId) {
  568. /* No valid server URL */
  569. if(!discoveryServerUrl) {
  570. UA_LOG_ERROR(&server->config.logger, UA_LOGCATEGORY_SERVER,
  571. "No discovery server URL provided");
  572. return UA_STATUSCODE_BADINTERNALERROR;
  573. }
  574. if (client->connection.state != UA_CONNECTION_CLOSED)
  575. return UA_STATUSCODE_BADINVALIDSTATE;
  576. /* check if we are already registering with the given discovery url and remove the old periodic call */
  577. {
  578. periodicServerRegisterCallback_entry *rs, *rs_tmp;
  579. LIST_FOREACH_SAFE(rs, &server->discoveryManager.
  580. periodicServerRegisterCallbacks, pointers, rs_tmp) {
  581. if(strcmp(rs->callback->discovery_server_url, discoveryServerUrl) == 0) {
  582. UA_LOG_INFO(&server->config.logger, UA_LOGCATEGORY_SERVER,
  583. "There is already a register callback for '%s' in place. Removing the older one.", discoveryServerUrl);
  584. UA_Server_removeRepeatedCallback(server, rs->callback->id);
  585. LIST_REMOVE(rs, pointers);
  586. UA_free(rs->callback);
  587. UA_free(rs);
  588. break;
  589. }
  590. }
  591. }
  592. /* Allocate and initialize */
  593. struct PeriodicServerRegisterCallback* cb =
  594. (struct PeriodicServerRegisterCallback*)
  595. UA_malloc(sizeof(struct PeriodicServerRegisterCallback));
  596. if(!cb)
  597. return UA_STATUSCODE_BADOUTOFMEMORY;
  598. /* Start repeating a failed register after 1s, then increase the delay. Set
  599. * to 500ms, as the delay is doubled before changing the callback
  600. * interval.*/
  601. cb->this_interval = 500.0;
  602. cb->default_interval = intervalMs;
  603. cb->registered = false;
  604. cb->client = client;
  605. cb->discovery_server_url = discoveryServerUrl;
  606. /* Add the callback */
  607. UA_StatusCode retval =
  608. UA_Server_addRepeatedCallback(server, periodicServerRegister,
  609. cb, delayFirstRegisterMs, &cb->id);
  610. if(retval != UA_STATUSCODE_GOOD) {
  611. UA_LOG_ERROR(&server->config.logger, UA_LOGCATEGORY_SERVER,
  612. "Could not create periodic job for server register. "
  613. "StatusCode %s", UA_StatusCode_name(retval));
  614. UA_free(cb);
  615. return retval;
  616. }
  617. #ifndef __clang_analyzer__
  618. // the analyzer reports on LIST_INSERT_HEAD a use after free false positive
  619. periodicServerRegisterCallback_entry *newEntry =
  620. (periodicServerRegisterCallback_entry *)UA_malloc(sizeof(periodicServerRegisterCallback_entry));
  621. if(!newEntry) {
  622. UA_Server_removeRepeatedCallback(server, cb->id);
  623. UA_free(cb);
  624. return UA_STATUSCODE_BADOUTOFMEMORY;
  625. }
  626. newEntry->callback = cb;
  627. LIST_INSERT_HEAD(&server->discoveryManager.periodicServerRegisterCallbacks, newEntry, pointers);
  628. #endif
  629. if(periodicCallbackId)
  630. *periodicCallbackId = cb->id;
  631. return UA_STATUSCODE_GOOD;
  632. }
  633. void
  634. UA_Server_setRegisterServerCallback(UA_Server *server,
  635. UA_Server_registerServerCallback cb,
  636. void* data) {
  637. server->discoveryManager.registerServerCallback = cb;
  638. server->discoveryManager.registerServerCallbackData = data;
  639. }
  640. #endif /* UA_ENABLE_DISCOVERY */