ua_mdns.c 19 KB

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