ua_mdns.c 19 KB

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