ua_server_discovery_mdns.c 25 KB

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