ua_server_discovery_mdns.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  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 2017 (c) Stefan Profanter, fortiss GmbH
  6. * Copyright 2017 (c) Fraunhofer IOSB (Author: Julius Pfrommer)
  7. */
  8. #include "ua_server_internal.h"
  9. #include "ua_util.h"
  10. #ifdef UA_ENABLE_DISCOVERY_MULTICAST
  11. #ifndef UA_ENABLE_AMALGAMATION
  12. #include "mdnsd/libmdnsd/xht.h"
  13. #include "mdnsd/libmdnsd/sdtxt.h"
  14. #endif
  15. #ifdef _WIN32
  16. /* inet_ntoa is deprecated on MSVC but used for compatibility */
  17. # define _WINSOCK_DEPRECATED_NO_WARNINGS
  18. # include <winsock2.h>
  19. # include <iphlpapi.h>
  20. # include <ws2tcpip.h>
  21. #else
  22. # include <sys/time.h> // for struct timeval
  23. # include <netinet/in.h> // for struct ip_mreq
  24. # include <ifaddrs.h>
  25. # include <net/if.h> /* for IFF_RUNNING */
  26. # include <netdb.h> // for recvfrom in cygwin
  27. #endif
  28. /* FIXME: Is this a required algorithm? Otherwise, reuse hashing for nodeids */
  29. /* Generates a hash code for a string.
  30. * This function uses the ELF hashing algorithm as reprinted in
  31. * Andrew Binstock, "Hashing Rehashed," Dr. Dobb's Journal, April 1996.
  32. */
  33. static int
  34. mdns_hash_record(const char *s) {
  35. /* ELF hash uses unsigned chars and unsigned arithmetic for portability */
  36. const unsigned char *name = (const unsigned char *) s;
  37. unsigned long h = 0;
  38. while(*name) {
  39. h = (h << 4) + (unsigned long) (*name++);
  40. unsigned long g;
  41. if((g = (h & 0xF0000000UL)) != 0)
  42. h ^= (g >> 24);
  43. h &= ~g;
  44. }
  45. return (int) h;
  46. }
  47. static struct serverOnNetwork_list_entry *
  48. mdns_record_add_or_get(UA_DiscoveryManager *dm, const char *record, const char *serverName,
  49. size_t serverNameLen, UA_Boolean createNew) {
  50. int hashIdx = mdns_hash_record(record) % SERVER_ON_NETWORK_HASH_PRIME;
  51. struct serverOnNetwork_hash_entry *hash_entry = dm->serverOnNetworkHash[hashIdx];
  52. while(hash_entry) {
  53. size_t maxLen;
  54. if(serverNameLen > hash_entry->entry->serverOnNetwork.serverName.length)
  55. maxLen = hash_entry->entry->serverOnNetwork.serverName.length;
  56. else
  57. maxLen = serverNameLen;
  58. if(strncmp((char *) hash_entry->entry->serverOnNetwork.serverName.data,
  59. serverName, maxLen) == 0)
  60. return hash_entry->entry;
  61. hash_entry = hash_entry->next;
  62. }
  63. if(!createNew)
  64. return NULL;
  65. /* not yet in list, create new one */
  66. /* todo: malloc may fail: return a statuscode */
  67. struct serverOnNetwork_list_entry *listEntry = (serverOnNetwork_list_entry*)
  68. UA_malloc(sizeof(struct serverOnNetwork_list_entry));
  69. listEntry->created = UA_DateTime_now();
  70. listEntry->pathTmp = NULL;
  71. listEntry->txtSet = false;
  72. listEntry->srvSet = false;
  73. UA_ServerOnNetwork_init(&listEntry->serverOnNetwork);
  74. listEntry->serverOnNetwork.recordId = dm->serverOnNetworkRecordIdCounter;
  75. listEntry->serverOnNetwork.serverName.length = serverNameLen;
  76. /* todo: malloc may fail: return a statuscode */
  77. listEntry->serverOnNetwork.serverName.data = (UA_Byte*)UA_malloc(serverNameLen);
  78. memcpy(listEntry->serverOnNetwork.serverName.data, serverName, serverNameLen);
  79. UA_atomic_addUInt32(&dm->serverOnNetworkRecordIdCounter, 1);
  80. if(dm->serverOnNetworkRecordIdCounter == 0)
  81. dm->serverOnNetworkRecordIdLastReset = UA_DateTime_now();
  82. /* add to hash */
  83. /* todo: malloc may fail: return a statuscode */
  84. struct serverOnNetwork_hash_entry *newHashEntry = (struct serverOnNetwork_hash_entry*)
  85. UA_malloc(sizeof(struct serverOnNetwork_hash_entry));
  86. newHashEntry->next = dm->serverOnNetworkHash[hashIdx];
  87. dm->serverOnNetworkHash[hashIdx] = newHashEntry;
  88. newHashEntry->entry = listEntry;
  89. LIST_INSERT_HEAD(&dm->serverOnNetwork, listEntry, pointers);
  90. return listEntry;
  91. }
  92. #ifdef _WIN32
  93. /* see http://stackoverflow.com/a/10838854/869402 */
  94. static IP_ADAPTER_ADDRESSES *
  95. getInterfaces(UA_Server *server) {
  96. IP_ADAPTER_ADDRESSES* adapter_addresses = NULL;
  97. /* Start with a 16 KB buffer and resize if needed - multiple attempts in
  98. * case interfaces change while we are in the middle of querying them. */
  99. DWORD adapter_addresses_buffer_size = 16 * 1024;
  100. for(size_t attempts = 0; attempts != 3; ++attempts) {
  101. /* todo: malloc may fail: return a statuscode */
  102. adapter_addresses = (IP_ADAPTER_ADDRESSES*)UA_malloc(adapter_addresses_buffer_size);
  103. if(!adapter_addresses) {
  104. UA_LOG_ERROR(&server->config.logger, UA_LOGCATEGORY_SERVER,
  105. "GetAdaptersAddresses out of memory");
  106. adapter_addresses = NULL;
  107. break;
  108. }
  109. DWORD error = GetAdaptersAddresses(AF_UNSPEC,
  110. GAA_FLAG_SKIP_ANYCAST |
  111. GAA_FLAG_SKIP_DNS_SERVER |
  112. GAA_FLAG_SKIP_FRIENDLY_NAME,
  113. NULL, adapter_addresses,
  114. &adapter_addresses_buffer_size);
  115. if(ERROR_SUCCESS == error) {
  116. break;
  117. } else if (ERROR_BUFFER_OVERFLOW == error) {
  118. /* Try again with the new size */
  119. UA_free(adapter_addresses);
  120. adapter_addresses = NULL;
  121. continue;
  122. }
  123. /* Unexpected error */
  124. UA_LOG_ERROR(&server->config.logger, UA_LOGCATEGORY_SERVER,
  125. "GetAdaptersAddresses returned an unexpected error. "
  126. "Not setting mDNS A records.");
  127. UA_free(adapter_addresses);
  128. adapter_addresses = NULL;
  129. break;
  130. }
  131. return adapter_addresses;
  132. }
  133. #endif /* _WIN32 */
  134. static UA_Boolean
  135. mdns_is_self_announce(UA_Server *server, struct serverOnNetwork_list_entry *entry) {
  136. for (size_t i=0; i<server->config.networkLayersSize; i++) {
  137. UA_ServerNetworkLayer *nl = &server->config.networkLayers[i];
  138. if(UA_String_equal(&entry->serverOnNetwork.discoveryUrl,
  139. &nl->discoveryUrl))
  140. return true;
  141. }
  142. /* The discovery URL may also just contain the IP address, but in our
  143. * discovery URL we are using hostname thus previous check may not detect
  144. * the same URL. Therefore we also check if the name matches: */
  145. UA_String hostnameRemote = UA_STRING_NULL;
  146. UA_UInt16 portRemote = 4840;
  147. UA_String pathRemote = UA_STRING_NULL;
  148. UA_StatusCode retval =
  149. UA_parseEndpointUrl(&entry->serverOnNetwork.discoveryUrl,
  150. &hostnameRemote, &portRemote, &pathRemote);
  151. if(retval != UA_STATUSCODE_GOOD) {
  152. /* skip invalid url */
  153. return false;
  154. }
  155. #ifdef _WIN32
  156. IP_ADAPTER_ADDRESSES* adapter_addresses = getInterfaces(server);
  157. if(!adapter_addresses) {
  158. UA_LOG_ERROR(&server->config.logger, UA_LOGCATEGORY_SERVER,
  159. "getifaddrs returned an unexpected error. Not setting mDNS A records.");
  160. return false;
  161. }
  162. #else
  163. struct ifaddrs *ifaddr, *ifa;
  164. if(getifaddrs(&ifaddr) == -1) {
  165. UA_LOG_ERROR(&server->config.logger, UA_LOGCATEGORY_SERVER,
  166. "getifaddrs returned an unexpected error. Not setting mDNS A records.");
  167. return false;
  168. }
  169. #endif
  170. UA_Boolean isSelf = false;
  171. for (size_t i=0; i<server->config.networkLayersSize; i++) {
  172. UA_ServerNetworkLayer *nl = &server->config.networkLayers[i];
  173. UA_String hostnameSelf = UA_STRING_NULL;
  174. UA_UInt16 portSelf = 4840;
  175. UA_String pathSelf = UA_STRING_NULL;
  176. retval = UA_parseEndpointUrl(&nl->discoveryUrl, &hostnameSelf,
  177. &portSelf, &pathSelf);
  178. if(retval != UA_STATUSCODE_GOOD) {
  179. /* skip invalid url */
  180. continue;
  181. }
  182. if (portRemote != portSelf)
  183. continue;
  184. #ifdef _WIN32
  185. /* Iterate through all of the adapters */
  186. IP_ADAPTER_ADDRESSES* adapter = adapter_addresses;
  187. for(; adapter != NULL; adapter = adapter->Next) {
  188. /* Skip loopback adapters */
  189. if(IF_TYPE_SOFTWARE_LOOPBACK == adapter->IfType)
  190. continue;
  191. /* Parse all IPv4 and IPv6 addresses */
  192. IP_ADAPTER_UNICAST_ADDRESS* address = adapter->FirstUnicastAddress;
  193. for(; NULL != address; address = address->Next) {
  194. int family = address->Address.lpSockaddr->sa_family;
  195. if(AF_INET == family) {
  196. SOCKADDR_IN* ipv4 = (SOCKADDR_IN*)(address->Address.lpSockaddr); /* IPv4 */
  197. char *ipStr = inet_ntoa(ipv4->sin_addr);
  198. if(strncmp((const char*)hostnameRemote.data, ipStr,
  199. hostnameRemote.length) == 0) {
  200. isSelf = true;
  201. break;
  202. }
  203. } else if(AF_INET6 == family) {
  204. /* IPv6 not implemented yet */
  205. }
  206. }
  207. if (isSelf)
  208. break;
  209. }
  210. #else
  211. /* Walk through linked list, maintaining head pointer so we can free
  212. * list later */
  213. int n;
  214. for(ifa = ifaddr, n = 0; ifa != NULL; ifa = ifa->ifa_next, n++) {
  215. if(!ifa->ifa_addr)
  216. continue;
  217. if((strcmp("lo", ifa->ifa_name) == 0) ||
  218. !(ifa->ifa_flags & (IFF_RUNNING))||
  219. !(ifa->ifa_flags & (IFF_MULTICAST)))
  220. continue;
  221. /* IPv4 */
  222. if(ifa->ifa_addr->sa_family == AF_INET) {
  223. struct sockaddr_in* sa = (struct sockaddr_in*) ifa->ifa_addr;
  224. char *ipStr = inet_ntoa(sa->sin_addr);
  225. if(strncmp((const char*)hostnameRemote.data, ipStr,
  226. hostnameRemote.length) == 0) {
  227. isSelf = true;
  228. break;
  229. }
  230. }
  231. /* IPv6 not implemented yet */
  232. }
  233. #endif
  234. if (isSelf)
  235. break;
  236. }
  237. #ifdef _WIN32
  238. /* Cleanup */
  239. UA_free(adapter_addresses);
  240. adapter_addresses = NULL;
  241. #else
  242. /* Clean up */
  243. freeifaddrs(ifaddr);
  244. #endif
  245. return isSelf;
  246. }
  247. static void
  248. mdns_record_remove(UA_Server *server, const char *record,
  249. struct serverOnNetwork_list_entry *entry) {
  250. UA_DiscoveryManager *dm = &server->discoveryManager;
  251. /* remove from hash */
  252. int hashIdx = mdns_hash_record(record) % SERVER_ON_NETWORK_HASH_PRIME;
  253. struct serverOnNetwork_hash_entry *hash_entry = dm->serverOnNetworkHash[hashIdx];
  254. struct serverOnNetwork_hash_entry *prevEntry = hash_entry;
  255. while(hash_entry) {
  256. if(hash_entry->entry == entry) {
  257. if(dm->serverOnNetworkHash[hashIdx] == hash_entry)
  258. dm->serverOnNetworkHash[hashIdx] = hash_entry->next;
  259. else if(prevEntry)
  260. prevEntry->next = hash_entry->next;
  261. break;
  262. }
  263. prevEntry = hash_entry;
  264. hash_entry = hash_entry->next;
  265. }
  266. UA_free(hash_entry);
  267. if(dm->serverOnNetworkCallback && !mdns_is_self_announce(server, entry))
  268. dm->serverOnNetworkCallback(&entry->serverOnNetwork, false,
  269. entry->txtSet, dm->serverOnNetworkCallbackData);
  270. /* remove from list */
  271. LIST_REMOVE(entry, pointers);
  272. UA_ServerOnNetwork_deleteMembers(&entry->serverOnNetwork);
  273. if(entry->pathTmp)
  274. UA_free(entry->pathTmp);
  275. #ifndef UA_ENABLE_MULTITHREADING
  276. dm->serverOnNetworkSize--;
  277. UA_free(entry);
  278. #else
  279. UA_atomic_subSize(&dm->serverOnNetworkSize, 1);
  280. entry->delayedCleanup.callback = NULL; /* Only free the structure */
  281. UA_WorkQueue_enqueueDelayed(&server->workQueue, &entry->delayedCleanup);
  282. #endif
  283. }
  284. static void
  285. mdns_append_path_to_url(UA_String *url, const char *path) {
  286. size_t pathLen = strlen(path);
  287. /* todo: malloc may fail: return a statuscode */
  288. char *newUrl = (char *)UA_malloc(url->length + pathLen);
  289. memcpy(newUrl, url->data, url->length);
  290. memcpy(newUrl + url->length, path, pathLen);
  291. url->length = url->length + pathLen;
  292. url->data = (UA_Byte *) newUrl;
  293. }
  294. static void
  295. setTxt(UA_Server *server, const struct resource *r,
  296. struct serverOnNetwork_list_entry *entry) {
  297. entry->txtSet = true;
  298. xht_t *x = txt2sd(r->rdata, r->rdlength);
  299. char *path = (char *) xht_get(x, "path");
  300. char *caps = (char *) xht_get(x, "caps");
  301. size_t pathLen = strlen(path);
  302. if(path && pathLen > 1) {
  303. if(!entry->srvSet) {
  304. /* txt arrived before SRV, thus cache path entry */
  305. if (!entry->pathTmp) {
  306. entry->pathTmp = (char*)UA_malloc(pathLen+1);
  307. if (!entry->pathTmp) {
  308. UA_LOG_ERROR(&server->config.logger, UA_LOGCATEGORY_SERVER, "Cannot alloc memory for mDNS srv path");
  309. return;
  310. }
  311. memcpy(&(entry->pathTmp), &path, pathLen);
  312. entry->pathTmp[pathLen] = '\0';
  313. }
  314. } else {
  315. /* SRV already there and discovery URL set. Add path to discovery URL */
  316. mdns_append_path_to_url(&entry->serverOnNetwork.discoveryUrl, path);
  317. }
  318. }
  319. if(caps && strlen(caps) > 0) {
  320. /* count comma in caps */
  321. size_t capsCount = 1;
  322. for(size_t i = 0; caps[i]; i++) {
  323. if(caps[i] == ',')
  324. capsCount++;
  325. }
  326. /* set capabilities */
  327. entry->serverOnNetwork.serverCapabilitiesSize = capsCount;
  328. entry->serverOnNetwork.serverCapabilities =
  329. (UA_String *) UA_Array_new(capsCount, &UA_TYPES[UA_TYPES_STRING]);
  330. for(size_t i = 0; i < capsCount; i++) {
  331. char *nextStr = strchr(caps, ',');
  332. size_t len = nextStr ? (size_t) (nextStr - caps) : strlen(caps);
  333. entry->serverOnNetwork.serverCapabilities[i].length = len;
  334. /* todo: malloc may fail: return a statuscode */
  335. entry->serverOnNetwork.serverCapabilities[i].data = (UA_Byte*)UA_malloc(len);
  336. memcpy(entry->serverOnNetwork.serverCapabilities[i].data, caps, len);
  337. if(nextStr)
  338. caps = nextStr + 1;
  339. else
  340. break;
  341. }
  342. }
  343. xht_free(x);
  344. }
  345. /* [servername]-[hostname]._opcua-tcp._tcp.local. 86400 IN SRV 0 5 port [hostname]. */
  346. static void
  347. setSrv(UA_Server *server, const struct resource *r,
  348. struct serverOnNetwork_list_entry *entry) {
  349. entry->srvSet = true;
  350. /* The specification Part 12 says: The hostname maps onto the SRV record
  351. * target field. If the hostname is an IPAddress then it must be converted
  352. * to a domain name. If this cannot be done then LDS shall report an
  353. * error. */
  354. size_t srvNameLen = strlen(r->known.srv.name);
  355. if(srvNameLen > 0 && r->known.srv.name[srvNameLen - 1] == '.')
  356. /* cut off last dot */
  357. srvNameLen--;
  358. /* opc.tcp://[servername]:[port][path] */
  359. char *newUrl = (char*)UA_malloc(10 + srvNameLen + 8);
  360. if (!newUrl) {
  361. UA_LOG_ERROR(&server->config.logger, UA_LOGCATEGORY_SERVER, "Cannot allocate char for discovery url. Out of memory.");
  362. return;
  363. }
  364. UA_snprintf(newUrl, 10 + srvNameLen + 8, "opc.tcp://%.*s:%d", (int) srvNameLen,
  365. r->known.srv.name, r->known.srv.port);
  366. UA_LOG_INFO(&server->config.logger, UA_LOGCATEGORY_SERVER,
  367. "Multicast DNS: found server: %s", newUrl);
  368. entry->serverOnNetwork.discoveryUrl = UA_String_fromChars(newUrl);
  369. UA_free(newUrl);
  370. if(entry->pathTmp) {
  371. mdns_append_path_to_url(&entry->serverOnNetwork.discoveryUrl, entry->pathTmp);
  372. UA_free(entry->pathTmp);
  373. }
  374. }
  375. /* This will be called by the mDNS library on every record which is received */
  376. void
  377. mdns_record_received(const struct resource *r, void *data) {
  378. UA_Server *server = (UA_Server *) data;
  379. /* we only need SRV and TXT records */
  380. /* TODO: remove magic number */
  381. if((r->clazz != QCLASS_IN && r->clazz != QCLASS_IN + 32768) ||
  382. (r->type != QTYPE_SRV && r->type != QTYPE_TXT))
  383. return;
  384. /* we only handle '_opcua-tcp._tcp.' records */
  385. char *opcStr = strstr(r->name, "_opcua-tcp._tcp.");
  386. if(!opcStr)
  387. return;
  388. /* Compute the length of the servername */
  389. size_t servernameLen = (size_t) (opcStr - r->name);
  390. if(servernameLen == 0)
  391. return;
  392. servernameLen--; /* remove point */
  393. /* Get entry */
  394. struct serverOnNetwork_list_entry *entry =
  395. mdns_record_add_or_get(&server->discoveryManager, r->name, r->name,
  396. servernameLen, r->ttl > 0);
  397. if(!entry)
  398. return;
  399. /* Check that the ttl is positive */
  400. if(r->ttl == 0) {
  401. UA_LOG_INFO(&server->config.logger, UA_LOGCATEGORY_SERVER,
  402. "Multicast DNS: remove server (TTL=0): %.*s",
  403. (int)entry->serverOnNetwork.discoveryUrl.length,
  404. entry->serverOnNetwork.discoveryUrl.data);
  405. mdns_record_remove(server, r->name, entry);
  406. return;
  407. }
  408. /* Update lastSeen */
  409. entry->lastSeen = UA_DateTime_nowMonotonic();
  410. /* TXT and SRV are already set */
  411. if(entry->txtSet && entry->srvSet)
  412. return;
  413. /* Add the resources */
  414. if(r->type == QTYPE_TXT && !entry->txtSet)
  415. setTxt(server, r, entry);
  416. else if (r->type == QTYPE_SRV && !entry->srvSet)
  417. setSrv(server, r, entry);
  418. /* Call callback to announce a new server */
  419. if(entry->srvSet && server->discoveryManager.serverOnNetworkCallback &&
  420. !mdns_is_self_announce(server, entry))
  421. server->discoveryManager.
  422. serverOnNetworkCallback(&entry->serverOnNetwork, true, entry->txtSet,
  423. server->discoveryManager.serverOnNetworkCallbackData);
  424. }
  425. void
  426. mdns_create_txt(UA_Server *server, const char *fullServiceDomain, const char *path,
  427. const UA_String *capabilites, const size_t *capabilitiesSize,
  428. void (*conflict)(char *host, int type, void *arg)) {
  429. mdns_record_t *r = mdnsd_unique(server->discoveryManager.mdnsDaemon, fullServiceDomain,
  430. QTYPE_TXT, 600, conflict, server);
  431. xht_t *h = xht_new(11);
  432. char *allocPath = NULL;
  433. if(!path || strlen(path) == 0) {
  434. xht_set(h, "path", "/");
  435. } else {
  436. /* path does not contain slash, so add it here */
  437. size_t pathLen = strlen(path);
  438. if(path[0] == '/') {
  439. allocPath = (char*)UA_malloc(pathLen+1);
  440. if (!allocPath) {
  441. UA_LOG_ERROR(&server->config.logger, UA_LOGCATEGORY_SERVER, "Cannot alloc memory for txt path");
  442. return;
  443. }
  444. memcpy(&allocPath, &path, pathLen);
  445. allocPath[pathLen] = '\0';
  446. } else {
  447. /* todo: malloc may fail: return a statuscode */
  448. allocPath = (char*)UA_malloc(pathLen + 2);
  449. allocPath[0] = '/';
  450. memcpy(allocPath + 1, path, pathLen);
  451. allocPath[pathLen + 1] = '\0';
  452. }
  453. xht_set(h, "path", allocPath);
  454. }
  455. /* calculate max string length: */
  456. size_t capsLen = 0;
  457. for(size_t i = 0; i < *capabilitiesSize; i++) {
  458. /* add comma or last \0 */
  459. capsLen += capabilites[i].length + 1;
  460. }
  461. char *caps = NULL;
  462. if(capsLen) {
  463. /* freed when xht_free is called */
  464. /* todo: malloc may fail: return a statuscode */
  465. caps = (char*)UA_malloc(sizeof(char) * capsLen);
  466. size_t idx = 0;
  467. for(size_t i = 0; i < *capabilitiesSize; i++) {
  468. memcpy(caps + idx, (const char *) capabilites[i].data, capabilites[i].length);
  469. idx += capabilites[i].length + 1;
  470. caps[idx - 1] = ',';
  471. }
  472. caps[idx - 1] = '\0';
  473. xht_set(h, "caps", caps);
  474. } else {
  475. xht_set(h, "caps", "NA");
  476. }
  477. int txtRecordLength;
  478. unsigned char *packet = sd2txt(h, &txtRecordLength);
  479. if(allocPath)
  480. UA_free(allocPath);
  481. if(caps)
  482. UA_free(caps);
  483. xht_free(h);
  484. mdnsd_set_raw(server->discoveryManager.mdnsDaemon, r, (char *) packet,
  485. (unsigned short) txtRecordLength);
  486. UA_free(packet);
  487. }
  488. mdns_record_t *
  489. mdns_find_record(mdns_daemon_t *mdnsDaemon, unsigned short type,
  490. const char *host, const char *rdname) {
  491. mdns_record_t *r = mdnsd_get_published(mdnsDaemon, host);
  492. if(!r)
  493. return NULL;
  494. /* search for the record with the correct ptr hostname */
  495. while(r) {
  496. const mdns_answer_t *data = mdnsd_record_data(r);
  497. if(data->type == type && strcmp(data->rdname, rdname) == 0)
  498. return r;
  499. r = mdnsd_record_next(r);
  500. }
  501. return NULL;
  502. }
  503. /* set record in the given interface */
  504. static void
  505. mdns_set_address_record_if(UA_DiscoveryManager *dm, const char *fullServiceDomain,
  506. const char *localDomain, char *addr, UA_UInt16 addr_len) {
  507. /* [servername]-[hostname]._opcua-tcp._tcp.local. A [ip]. */
  508. mdns_record_t *r = mdnsd_shared(dm->mdnsDaemon, fullServiceDomain, QTYPE_A, 600);
  509. mdnsd_set_raw(dm->mdnsDaemon, r, addr, addr_len);
  510. /* [hostname]. A [ip]. */
  511. r = mdnsd_shared(dm->mdnsDaemon, localDomain, QTYPE_A, 600);
  512. mdnsd_set_raw(dm->mdnsDaemon, r, addr, addr_len);
  513. }
  514. /* Loop over network interfaces and run set_address_record on each */
  515. #ifdef _WIN32
  516. void mdns_set_address_record(UA_Server *server, const char *fullServiceDomain,
  517. const char *localDomain) {
  518. IP_ADAPTER_ADDRESSES* adapter_addresses = getInterfaces(server);
  519. if(!adapter_addresses)
  520. return;
  521. /* Iterate through all of the adapters */
  522. IP_ADAPTER_ADDRESSES* adapter = adapter_addresses;
  523. for(; adapter != NULL; adapter = adapter->Next) {
  524. /* Skip loopback adapters */
  525. if(IF_TYPE_SOFTWARE_LOOPBACK == adapter->IfType)
  526. continue;
  527. /* Parse all IPv4 and IPv6 addresses */
  528. IP_ADAPTER_UNICAST_ADDRESS* address = adapter->FirstUnicastAddress;
  529. for(; NULL != address; address = address->Next) {
  530. int family = address->Address.lpSockaddr->sa_family;
  531. if(AF_INET == family) {
  532. SOCKADDR_IN* ipv4 = (SOCKADDR_IN*)(address->Address.lpSockaddr); /* IPv4 */
  533. mdns_set_address_record_if(&server->discoveryManager, fullServiceDomain,
  534. localDomain, (char *)&ipv4->sin_addr, 4);
  535. } else if(AF_INET6 == family) {
  536. /* IPv6 */
  537. #if 0
  538. SOCKADDR_IN6* ipv6 = (SOCKADDR_IN6*)(address->Address.lpSockaddr);
  539. char str_buffer[INET6_ADDRSTRLEN] = {0};
  540. inet_ntop(AF_INET6, &(ipv6->sin6_addr), str_buffer, INET6_ADDRSTRLEN);
  541. std::string ipv6_str(str_buffer);
  542. /* Detect and skip non-external addresses */
  543. UA_Boolean is_link_local(false);
  544. UA_Boolean is_special_use(false);
  545. if(0 == ipv6_str.find("fe")) {
  546. char c = ipv6_str[2];
  547. if(c == '8' || c == '9' || c == 'a' || c == 'b')
  548. is_link_local = true;
  549. } else if (0 == ipv6_str.find("2001:0:")) {
  550. is_special_use = true;
  551. }
  552. if(!(is_link_local || is_special_use))
  553. ipAddrs.mIpv6.push_back(ipv6_str);
  554. #endif
  555. }
  556. }
  557. }
  558. /* Cleanup */
  559. UA_free(adapter_addresses);
  560. adapter_addresses = NULL;
  561. }
  562. #else /* _WIN32 */
  563. void
  564. mdns_set_address_record(UA_Server *server, const char *fullServiceDomain,
  565. const char *localDomain) {
  566. struct ifaddrs *ifaddr, *ifa;
  567. if(getifaddrs(&ifaddr) == -1) {
  568. UA_LOG_ERROR(&server->config.logger, UA_LOGCATEGORY_SERVER,
  569. "getifaddrs returned an unexpected error. Not setting mDNS A records.");
  570. return;
  571. }
  572. /* Walk through linked list, maintaining head pointer so we can free list later */
  573. int n;
  574. for(ifa = ifaddr, n = 0; ifa != NULL; ifa = ifa->ifa_next, n++) {
  575. if(!ifa->ifa_addr)
  576. continue;
  577. if((strcmp("lo", ifa->ifa_name) == 0) ||
  578. !(ifa->ifa_flags & (IFF_RUNNING))||
  579. !(ifa->ifa_flags & (IFF_MULTICAST)))
  580. continue;
  581. /* IPv4 */
  582. if(ifa->ifa_addr->sa_family == AF_INET) {
  583. struct sockaddr_in* sa = (struct sockaddr_in*) ifa->ifa_addr;
  584. mdns_set_address_record_if(&server->discoveryManager, fullServiceDomain,
  585. localDomain, (char*)&sa->sin_addr.s_addr, 4);
  586. }
  587. /* IPv6 not implemented yet */
  588. }
  589. /* Clean up */
  590. freeifaddrs(ifaddr);
  591. }
  592. #endif /* _WIN32 */
  593. #endif /* UA_ENABLE_DISCOVERY_MULTICAST */