ua_services_discovery.c 31 KB

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