ua_mdns.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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_mdns_internal.h"
  10. #include "ua_util.h"
  11. #ifdef UA_ENABLE_DISCOVERY_MULTICAST
  12. # ifdef UA_NO_AMALGAMATION
  13. # include "mdnsd/libmdnsd/xht.h"
  14. # include "mdnsd/libmdnsd/sdtxt.h"
  15. # endif
  16. # ifdef _WIN32
  17. # define _WINSOCK_DEPRECATED_NO_WARNINGS /* inet_ntoa is deprecated on MSVC but used for compatibility */
  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. #ifndef UA_STRDUP
  29. # if defined(__MINGW32__)
  30. static char *ua_strdup(const char *s) {
  31. char *p = (char*)UA_malloc(strlen(s) + 1);
  32. if(p) { strcpy(p, s); }
  33. return p;
  34. }
  35. # define UA_STRDUP ua_strdup
  36. # elif defined(_WIN32)
  37. # define UA_STRDUP _strdup
  38. # else
  39. # define UA_STRDUP strdup
  40. # endif
  41. #endif
  42. // FIXME: Is this a required algorithm? Otherwise, reuse hashing for nodeids
  43. /* Generates a hash code for a string.
  44. * This function uses the ELF hashing algorithm as reprinted in
  45. * Andrew Binstock, "Hashing Rehashed," Dr. Dobb's Journal, April 1996.
  46. */
  47. static int mdns_hash_record(const char *s) {
  48. /* ELF hash uses unsigned chars and unsigned arithmetic for portability */
  49. const unsigned char *name = (const unsigned char *) s;
  50. unsigned long h = 0;
  51. while(*name) {
  52. h = (h << 4) + (unsigned long) (*name++);
  53. unsigned long g;
  54. if((g = (h & 0xF0000000UL)) != 0)
  55. h ^= (g >> 24);
  56. h &= ~g;
  57. }
  58. return (int) h;
  59. }
  60. static struct serverOnNetwork_list_entry *
  61. mdns_record_add_or_get(UA_Server *server, const char *record, const char *serverName,
  62. size_t serverNameLen, UA_Boolean createNew) {
  63. int hashIdx = mdns_hash_record(record) % SERVER_ON_NETWORK_HASH_PRIME;
  64. struct serverOnNetwork_hash_entry *hash_entry = server->serverOnNetworkHash[hashIdx];
  65. while(hash_entry) {
  66. size_t maxLen;
  67. if(serverNameLen > hash_entry->entry->serverOnNetwork.serverName.length)
  68. maxLen = hash_entry->entry->serverOnNetwork.serverName.length;
  69. else
  70. maxLen = serverNameLen;
  71. if(strncmp((char *) hash_entry->entry->serverOnNetwork.serverName.data, serverName, maxLen) == 0)
  72. return hash_entry->entry;
  73. hash_entry = hash_entry->next;
  74. }
  75. if(!createNew)
  76. return NULL;
  77. // not yet in list, create new one
  78. // todo: malloc may fail: return a statuscode
  79. struct serverOnNetwork_list_entry *listEntry =
  80. (serverOnNetwork_list_entry*)UA_malloc(sizeof(struct serverOnNetwork_list_entry));
  81. listEntry->created = UA_DateTime_now();
  82. listEntry->pathTmp = NULL;
  83. listEntry->txtSet = UA_FALSE;
  84. listEntry->srvSet = UA_FALSE;
  85. UA_ServerOnNetwork_init(&listEntry->serverOnNetwork);
  86. listEntry->serverOnNetwork.recordId = server->serverOnNetworkRecordIdCounter;
  87. listEntry->serverOnNetwork.serverName.length = serverNameLen;
  88. // todo: malloc may fail: return a statuscode
  89. listEntry->serverOnNetwork.serverName.data = (UA_Byte*)UA_malloc(serverNameLen);
  90. memcpy(listEntry->serverOnNetwork.serverName.data, serverName, serverNameLen);
  91. UA_atomic_addUInt32(&server->serverOnNetworkRecordIdCounter, 1);
  92. if(server->serverOnNetworkRecordIdCounter == 0)
  93. server->serverOnNetworkRecordIdLastReset = UA_DateTime_now();
  94. // add to hash
  95. // todo: malloc may fail: return a statuscode
  96. struct serverOnNetwork_hash_entry *newHashEntry =
  97. (struct serverOnNetwork_hash_entry*)UA_malloc(sizeof(struct serverOnNetwork_hash_entry));
  98. newHashEntry->next = server->serverOnNetworkHash[hashIdx];
  99. server->serverOnNetworkHash[hashIdx] = newHashEntry;
  100. newHashEntry->entry = listEntry;
  101. LIST_INSERT_HEAD(&server->serverOnNetwork, listEntry, pointers);
  102. return listEntry;
  103. }
  104. #ifdef UA_ENABLE_MULTITHREADING
  105. static void
  106. delayedFree(UA_Server *server, void *data) {
  107. UA_free(data);
  108. }
  109. #endif
  110. static void
  111. mdns_record_remove(UA_Server *server, const char *record,
  112. struct serverOnNetwork_list_entry *entry) {
  113. // remove from hash
  114. int hashIdx = mdns_hash_record(record) % SERVER_ON_NETWORK_HASH_PRIME;
  115. struct serverOnNetwork_hash_entry *hash_entry = server->serverOnNetworkHash[hashIdx];
  116. struct serverOnNetwork_hash_entry *prevEntry = hash_entry;
  117. while(hash_entry) {
  118. if(hash_entry->entry == entry) {
  119. if(server->serverOnNetworkHash[hashIdx] == hash_entry)
  120. server->serverOnNetworkHash[hashIdx] = hash_entry->next;
  121. else if(prevEntry)
  122. prevEntry->next = hash_entry->next;
  123. break;
  124. }
  125. prevEntry = hash_entry;
  126. hash_entry = hash_entry->next;
  127. }
  128. UA_free(hash_entry);
  129. if(server->serverOnNetworkCallback)
  130. server->serverOnNetworkCallback(&entry->serverOnNetwork, UA_FALSE,
  131. entry->txtSet, server->serverOnNetworkCallbackData);
  132. // remove from list
  133. LIST_REMOVE(entry, pointers);
  134. UA_ServerOnNetwork_deleteMembers(&entry->serverOnNetwork);
  135. if(entry->pathTmp)
  136. UA_free(entry->pathTmp);
  137. #ifndef UA_ENABLE_MULTITHREADING
  138. server->serverOnNetworkSize--;
  139. UA_free(entry);
  140. #else
  141. UA_atomic_subSize(&server->serverOnNetworkSize, 1);
  142. UA_Server_delayedCallback(server, delayedFree, entry);
  143. #endif
  144. }
  145. static void
  146. mdns_append_path_to_url(UA_String *url, const char *path) {
  147. size_t pathLen = strlen(path);
  148. // todo: malloc may fail: return a statuscode
  149. char *newUrl = (char *)UA_malloc(url->length + pathLen);
  150. memcpy(newUrl, url->data, url->length);
  151. memcpy(newUrl + url->length, path, pathLen);
  152. url->length = url->length + pathLen;
  153. url->data = (UA_Byte *) newUrl;
  154. }
  155. static void
  156. setTxt(const struct resource *r,
  157. struct serverOnNetwork_list_entry *entry) {
  158. entry->txtSet = UA_TRUE;
  159. xht_t *x = txt2sd(r->rdata, r->rdlength);
  160. char *path = (char *) xht_get(x, "path");
  161. char *caps = (char *) xht_get(x, "caps");
  162. if(path && strlen(path) > 1) {
  163. if(!entry->srvSet) {
  164. /* txt arrived before SRV, thus cache path entry */
  165. // todo: malloc in strdup may fail: return a statuscode
  166. entry->pathTmp = UA_STRDUP(path);
  167. } else {
  168. /* SRV already there and discovery URL set. Add path to discovery URL */
  169. mdns_append_path_to_url(&entry->serverOnNetwork.discoveryUrl, path);
  170. }
  171. }
  172. if(caps && strlen(caps) > 0) {
  173. /* count comma in caps */
  174. size_t capsCount = 1;
  175. for(size_t i = 0; caps[i]; i++) {
  176. if(caps[i] == ',')
  177. capsCount++;
  178. }
  179. /* set capabilities */
  180. entry->serverOnNetwork.serverCapabilitiesSize = capsCount;
  181. entry->serverOnNetwork.serverCapabilities =
  182. (UA_String *) UA_Array_new(capsCount, &UA_TYPES[UA_TYPES_STRING]);
  183. for(size_t i = 0; i < capsCount; i++) {
  184. char *nextStr = strchr(caps, ',');
  185. size_t len = nextStr ? (size_t) (nextStr - caps) : strlen(caps);
  186. entry->serverOnNetwork.serverCapabilities[i].length = len;
  187. // todo: malloc may fail: return a statuscode
  188. entry->serverOnNetwork.serverCapabilities[i].data = (UA_Byte*)UA_malloc(len);
  189. memcpy(entry->serverOnNetwork.serverCapabilities[i].data, caps, len);
  190. if(nextStr)
  191. caps = nextStr + 1;
  192. else
  193. break;
  194. }
  195. }
  196. xht_free(x);
  197. }
  198. // [servername]-[hostname]._opcua-tcp._tcp.local. 86400 IN SRV 0 5 port [hostname].
  199. static void
  200. setSrv(UA_Server *server, const struct resource *r,
  201. struct serverOnNetwork_list_entry *entry) {
  202. entry->srvSet = UA_TRUE;
  203. // opc.tcp://[servername]:[port][path]
  204. size_t srvNameLen = strlen(r->known.srv.name);
  205. if(srvNameLen > 0 && r->known.srv.name[srvNameLen - 1] == '.')
  206. srvNameLen--;
  207. // todo: malloc may fail: return a statuscode
  208. char *newUrl = (char*)UA_malloc(10 + srvNameLen + 8);
  209. UA_snprintf(newUrl, 10 + srvNameLen + 8, "opc.tcp://%.*s:%d/", (int) srvNameLen,
  210. r->known.srv.name, r->known.srv.port);
  211. UA_LOG_INFO(server->config.logger, UA_LOGCATEGORY_SERVER,
  212. "Multicast DNS: found server: %s", newUrl);
  213. entry->serverOnNetwork.discoveryUrl = UA_String_fromChars(newUrl);
  214. UA_free(newUrl);
  215. if(entry->pathTmp) {
  216. mdns_append_path_to_url(&entry->serverOnNetwork.discoveryUrl, entry->pathTmp);
  217. UA_free(entry->pathTmp);
  218. }
  219. }
  220. /* This will be called by the mDNS library on every record which is received */
  221. void mdns_record_received(const struct resource *r, void *data) {
  222. UA_Server *server = (UA_Server *) data;
  223. /* we only need SRV and TXT records */
  224. // TODO: remove magic number
  225. if((r->clazz != QCLASS_IN && r->clazz != QCLASS_IN + 32768) ||
  226. (r->type != QTYPE_SRV && r->type != QTYPE_TXT))
  227. return;
  228. /* we only handle '_opcua-tcp._tcp.' records */
  229. char *opcStr = strstr(r->name, "_opcua-tcp._tcp.");
  230. if(!opcStr)
  231. return;
  232. /* Compute the length of the servername */
  233. size_t servernameLen = (size_t) (opcStr - r->name);
  234. if(servernameLen == 0)
  235. return;
  236. servernameLen--; // remove point
  237. /* Get entry */
  238. struct serverOnNetwork_list_entry *entry =
  239. mdns_record_add_or_get(server, r->name, r->name, servernameLen, r->ttl > 0);
  240. if(!entry)
  241. return;
  242. /* Check that the ttl is positive */
  243. if(r->ttl == 0) {
  244. UA_LOG_INFO(server->config.logger, UA_LOGCATEGORY_SERVER,
  245. "Multicast DNS: remove server (TTL=0): %.*s",
  246. (int)entry->serverOnNetwork.discoveryUrl.length,
  247. entry->serverOnNetwork.discoveryUrl.data);
  248. mdns_record_remove(server, r->name, entry);
  249. return;
  250. }
  251. /* Update lastSeen */
  252. entry->lastSeen = UA_DateTime_nowMonotonic();
  253. /* TXT and SRV are already set */
  254. if(entry->txtSet && entry->srvSet)
  255. return;
  256. /* Add the resources */
  257. if(r->type == QTYPE_TXT && !entry->txtSet)
  258. setTxt(r, entry);
  259. else if (r->type == QTYPE_SRV && !entry->srvSet)
  260. setSrv(server, r, entry);
  261. /* Call callback to announce a new server */
  262. if(entry->srvSet && server->serverOnNetworkCallback)
  263. server->serverOnNetworkCallback(&entry->serverOnNetwork, UA_TRUE,
  264. entry->txtSet, server->serverOnNetworkCallbackData);
  265. }
  266. void mdns_create_txt(UA_Server *server, const char *fullServiceDomain, const char *path,
  267. const UA_String *capabilites, const size_t *capabilitiesSize,
  268. void (*conflict)(char *host, int type, void *arg)) {
  269. mdns_record_t *r = mdnsd_unique(server->mdnsDaemon, fullServiceDomain, QTYPE_TXT,
  270. 600, conflict, server);
  271. xht_t *h = xht_new(11);
  272. char *allocPath = NULL;
  273. if(!path || strlen(path) == 0) {
  274. xht_set(h, "path", "/");
  275. } else {
  276. // path does not contain slash, so add it here
  277. if(path[0] == '/')
  278. // todo: malloc in strdup may fail: return a statuscode
  279. allocPath = UA_STRDUP(path);
  280. else {
  281. // todo: malloc may fail: return a statuscode
  282. allocPath = (char*)UA_malloc(strlen(path) + 2);
  283. allocPath[0] = '/';
  284. memcpy(allocPath + 1, path, strlen(path));
  285. allocPath[strlen(path) + 1] = '\0';
  286. }
  287. xht_set(h, "path", allocPath);
  288. }
  289. // calculate max string length:
  290. size_t capsLen = 0;
  291. for(size_t i = 0; i < *capabilitiesSize; i++) {
  292. // add comma or last \0
  293. capsLen += capabilites[i].length + 1;
  294. }
  295. char *caps = NULL;
  296. if(capsLen) {
  297. // freed when xht_free is called
  298. // todo: malloc may fail: return a statuscode
  299. caps = (char*)UA_malloc(sizeof(char) * capsLen);
  300. size_t idx = 0;
  301. for(size_t i = 0; i < *capabilitiesSize; i++) {
  302. memcpy(caps + idx, (const char *) capabilites[i].data, capabilites[i].length);
  303. idx += capabilites[i].length + 1;
  304. caps[idx - 1] = ',';
  305. }
  306. caps[idx - 1] = '\0';
  307. xht_set(h, "caps", caps);
  308. } else {
  309. xht_set(h, "caps", "NA");
  310. }
  311. int txtRecordLength;
  312. unsigned char *packet = sd2txt(h, &txtRecordLength);
  313. if(allocPath)
  314. UA_free(allocPath);
  315. if(caps)
  316. UA_free(caps);
  317. xht_free(h);
  318. mdnsd_set_raw(server->mdnsDaemon, r, (char *) packet, (unsigned short) txtRecordLength);
  319. UA_free(packet);
  320. }
  321. mdns_record_t *
  322. mdns_find_record(mdns_daemon_t *mdnsDaemon, unsigned short type,
  323. const char *host, const char *rdname) {
  324. mdns_record_t *r = mdnsd_get_published(mdnsDaemon, host);
  325. if(!r)
  326. return NULL;
  327. // search for the record with the correct ptr hostname
  328. while(r) {
  329. const mdns_answer_t *data = mdnsd_record_data(r);
  330. if(data->type == type && strcmp(data->rdname, rdname) == 0)
  331. return r;
  332. r = mdnsd_record_next(r);
  333. }
  334. return NULL;
  335. }
  336. /* set record in the given interface */
  337. static void
  338. mdns_set_address_record_if(UA_Server *server, const char *fullServiceDomain,
  339. const char *localDomain, char *addr, UA_UInt16 addr_len) {
  340. // [servername]-[hostname]._opcua-tcp._tcp.local. A [ip].
  341. mdns_record_t *r = mdnsd_shared(server->mdnsDaemon, fullServiceDomain, QTYPE_A, 600);
  342. mdnsd_set_raw(server->mdnsDaemon, r, addr, addr_len);
  343. // [hostname]. A [ip].
  344. r = mdnsd_shared(server->mdnsDaemon, localDomain, QTYPE_A, 600);
  345. mdnsd_set_raw(server->mdnsDaemon, r, addr, addr_len);
  346. }
  347. /* Loop over network interfaces and run set_address_record on each */
  348. #ifdef _WIN32
  349. // see http://stackoverflow.com/a/10838854/869402
  350. static IP_ADAPTER_ADDRESSES *
  351. getInterfaces(UA_Server *server) {
  352. IP_ADAPTER_ADDRESSES* adapter_addresses = NULL;
  353. // Start with a 16 KB buffer and resize if needed - multiple attempts in
  354. // case interfaces change while we are in the middle of querying them.
  355. DWORD adapter_addresses_buffer_size = 16 * 1024;
  356. for(size_t attempts = 0; attempts != 3; ++attempts) {
  357. // todo: malloc may fail: return a statuscode
  358. adapter_addresses = (IP_ADAPTER_ADDRESSES*)UA_malloc(adapter_addresses_buffer_size);
  359. if(!adapter_addresses) {
  360. UA_LOG_ERROR(server->config.logger, UA_LOGCATEGORY_SERVER,
  361. "GetAdaptersAddresses out of memory");
  362. adapter_addresses = NULL;
  363. break;
  364. }
  365. DWORD error = GetAdaptersAddresses(AF_UNSPEC,
  366. GAA_FLAG_SKIP_ANYCAST |
  367. GAA_FLAG_SKIP_DNS_SERVER |
  368. GAA_FLAG_SKIP_FRIENDLY_NAME,
  369. NULL, adapter_addresses,
  370. &adapter_addresses_buffer_size);
  371. if(ERROR_SUCCESS == error) {
  372. break;
  373. } else if (ERROR_BUFFER_OVERFLOW == error) {
  374. // Try again with the new size
  375. UA_free(adapter_addresses);
  376. adapter_addresses = NULL;
  377. continue;
  378. }
  379. /* Unexpected error */
  380. UA_LOG_ERROR(server->config.logger, UA_LOGCATEGORY_SERVER,
  381. "GetAdaptersAddresses returned an unexpected error. "
  382. "Not setting mDNS A records.");
  383. UA_free(adapter_addresses);
  384. adapter_addresses = NULL;
  385. break;
  386. }
  387. return adapter_addresses;
  388. }
  389. void mdns_set_address_record(UA_Server *server, const char *fullServiceDomain,
  390. const char *localDomain) {
  391. IP_ADAPTER_ADDRESSES* adapter_addresses = getInterfaces(server);
  392. if(!adapter_addresses)
  393. return;
  394. /* Iterate through all of the adapters */
  395. IP_ADAPTER_ADDRESSES* adapter = adapter_addresses->Next;
  396. for(; adapter != NULL; adapter = adapter->Next) {
  397. /* Skip loopback adapters */
  398. if(IF_TYPE_SOFTWARE_LOOPBACK == adapter->IfType)
  399. continue;
  400. // Parse all IPv4 and IPv6 addresses
  401. IP_ADAPTER_UNICAST_ADDRESS* address = adapter->FirstUnicastAddress;
  402. for(; NULL != address; address = address->Next) {
  403. int family = address->Address.lpSockaddr->sa_family;
  404. if(AF_INET == family) {
  405. SOCKADDR_IN* ipv4 = (SOCKADDR_IN*)(address->Address.lpSockaddr); // IPv4
  406. mdns_set_address_record_if(server, fullServiceDomain, localDomain,
  407. (char *)&ipv4->sin_addr, 4);
  408. }
  409. /*else if(AF_INET6 == family) {
  410. // IPv6
  411. SOCKADDR_IN6* ipv6 = (SOCKADDR_IN6*)(address->Address.lpSockaddr);
  412. char str_buffer[INET6_ADDRSTRLEN] = {0};
  413. inet_ntop(AF_INET6, &(ipv6->sin6_addr), str_buffer, INET6_ADDRSTRLEN);
  414. std::string ipv6_str(str_buffer);
  415. // Detect and skip non-external addresses
  416. bool is_link_local(false);
  417. bool is_special_use(false);
  418. if(0 == ipv6_str.find("fe")) {
  419. char c = ipv6_str[2];
  420. if(c == '8' || c == '9' || c == 'a' || c == 'b')
  421. is_link_local = true;
  422. } else if (0 == ipv6_str.find("2001:0:")) {
  423. is_special_use = true;
  424. }
  425. if(!(is_link_local || is_special_use))
  426. ipAddrs.mIpv6.push_back(ipv6_str);
  427. }*/
  428. }
  429. }
  430. /* Cleanup */
  431. UA_free(adapter_addresses);
  432. adapter_addresses = NULL;
  433. }
  434. #else //_WIN32
  435. void mdns_set_address_record(UA_Server *server, const char *fullServiceDomain,
  436. const char *localDomain) {
  437. struct ifaddrs *ifaddr, *ifa;
  438. if(getifaddrs(&ifaddr) == -1) {
  439. UA_LOG_ERROR(server->config.logger, UA_LOGCATEGORY_SERVER,
  440. "getifaddrs returned an unexpected error. Not setting mDNS A records.");
  441. return;
  442. }
  443. /* Walk through linked list, maintaining head pointer so we can free list later */
  444. int n;
  445. for(ifa = ifaddr, n = 0; ifa != NULL; ifa = ifa->ifa_next, n++) {
  446. if(!ifa->ifa_addr)
  447. continue;
  448. if((strcmp("lo", ifa->ifa_name) == 0) ||
  449. !(ifa->ifa_flags & (IFF_RUNNING))||
  450. !(ifa->ifa_flags & (IFF_MULTICAST)))
  451. continue;
  452. /* IPv4 */
  453. if(ifa->ifa_addr->sa_family == AF_INET) {
  454. struct sockaddr_in* sa = (struct sockaddr_in*) ifa->ifa_addr;
  455. mdns_set_address_record_if(server, fullServiceDomain, localDomain,
  456. (char*)&sa->sin_addr.s_addr, 4);
  457. }
  458. /* IPv6 not implemented yet */
  459. }
  460. /* Clean up */
  461. freeifaddrs(ifaddr);
  462. }
  463. #endif //_WIN32
  464. #endif // UA_ENABLE_DISCOVERY_MULTICAST