ua_mdns.c 19 KB

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