discover.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. /*
  2. * Copyright (C) 2001-2005 by egnite Software GmbH. All rights reserved.
  3. *
  4. * Redistribution and use in source and binary forms, with or without
  5. * modification, are permitted provided that the following conditions
  6. * are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright
  9. * notice, this list of conditions and the following disclaimer.
  10. * 2. Redistributions in binary form must reproduce the above copyright
  11. * notice, this list of conditions and the following disclaimer in the
  12. * documentation and/or other materials provided with the distribution.
  13. * 3. Neither the name of the copyright holders nor the names of
  14. * contributors may be used to endorse or promote products derived
  15. * from this software without specific prior written permission.
  16. *
  17. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  18. * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  19. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  20. * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  21. * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  22. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  23. * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
  24. * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
  25. * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  26. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  27. * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  28. * SUCH DAMAGE.
  29. *
  30. * For additional information see http://www.ethernut.de/
  31. *
  32. */
  33. /*
  34. * $Log$
  35. * Revision 1.6 2009/02/13 14:52:05 haraldkipp
  36. * Include memdebug.h for heap management debugging support.
  37. *
  38. * Revision 1.5 2009/02/06 15:37:40 haraldkipp
  39. * Added stack space multiplier and addend. Adjusted stack space.
  40. *
  41. * Revision 1.4 2009/01/17 11:26:52 haraldkipp
  42. * Getting rid of two remaining BSD types in favor of stdint.
  43. * Replaced 'u_int' by 'unsinged int' and 'uptr_t' by 'uintptr_t'.
  44. *
  45. * Revision 1.3 2009/01/16 17:03:50 haraldkipp
  46. * Configurable discovery protocol version and port plus
  47. * configurable service thread stack size. The new version 1.1
  48. * allows host names up to 98 characters. Added some code
  49. * to make sure, that nothing is overwritten with version 1.0
  50. * protocol and too long host names. Protocol version 1.0
  51. * is still the default.
  52. *
  53. * Revision 1.2 2008/08/11 07:00:35 haraldkipp
  54. * BSD types replaced by stdint types (feature request #1282721).
  55. *
  56. * Revision 1.1 2006/09/07 09:06:17 haraldkipp
  57. * Discovery service added.
  58. *
  59. */
  60. #include <sys/confnet.h>
  61. #include <sys/confos.h>
  62. #include <sys/thread.h>
  63. #include <sys/timer.h>
  64. #include <sys/socket.h>
  65. #include <netinet/in.h>
  66. #include <net/if_var.h>
  67. #include <stdlib.h>
  68. #include <string.h>
  69. #include <memdebug.h>
  70. #include <pro/discover.h>
  71. /*!
  72. * \addtogroup xgDiscover
  73. */
  74. /*@{*/
  75. #ifndef NUT_THREAD_DISTSTACK
  76. #if defined(__AVR__)
  77. #if defined(__GNUC__)
  78. /* avr-gcc size optimized code uses 124 bytes. */
  79. #define NUT_THREAD_DISTSTACK 224
  80. #else
  81. /* icc-avr v7.19 uses 244 bytes. */
  82. #define NUT_THREAD_DISTSTACK 384
  83. #endif
  84. #elif defined(__AVR32__)
  85. #define NUT_THREAD_DISTSTACK 512
  86. #else
  87. /* arm-elf-gcc used 232 bytes with size optimized, 476 bytes with debug code. */
  88. #define NUT_THREAD_DISTSTACK 320
  89. #endif
  90. #endif
  91. #ifndef DISCOVERY_PORT
  92. #define DISCOVERY_PORT 9806
  93. #endif
  94. typedef struct {
  95. uint32_t disopt_ipmask;
  96. uint16_t disopt_port;
  97. unsigned int disopt_flags;
  98. } DISCOVERY_OPTIONS;
  99. static DISCOVERY_OPTIONS disopt;
  100. static uint32_t xid;
  101. static int NutDiscoveryHandler(uint32_t ip, uint16_t port, DISCOVERY_TELE * dist, int len);
  102. static NutDiscoveryCallback discovery_callback = NutDiscoveryHandler;
  103. /*!
  104. * \brief Create an announcement datagram.
  105. *
  106. * \param dist Pointer to the datagram buffer that will be filled.
  107. *
  108. * \return Number of bytes filled into the datagram buffer.
  109. */
  110. int NutDiscoveryAnnTele(DISCOVERY_TELE * dist)
  111. {
  112. memset(dist, 0, sizeof(DISCOVERY_TELE));
  113. dist->dist_xid = xid;
  114. dist->dist_type = DIST_ANNOUNCE;
  115. dist->dist_ver = DISCOVERY_VERSION;
  116. memcpy(dist->dist_mac, confnet.cdn_mac, sizeof(dist->dist_mac));
  117. dist->dist_ip_addr = confnet.cdn_ip_addr;
  118. dist->dist_ip_mask = confnet.cdn_ip_mask;
  119. dist->dist_gateway = confnet.cdn_gateway;
  120. dist->dist_cip_addr = confnet.cdn_cip_addr;
  121. #if DISCOVERY_VERSION <= 0x10
  122. memcpy(dist->dist_hostname, confos.hostname, sizeof(dist->dist_hostname));
  123. return sizeof(DISCOVERY_TELE) - sizeof(dist->dist_custom);
  124. #else
  125. dist->dist_appendix[0] = (uint8_t)strlen(confos.hostname);
  126. memcpy(&dist->dist_appendix[1], confos.hostname, dist->dist_appendix[0]);
  127. return sizeof(DISCOVERY_TELE) - sizeof(dist->dist_appendix) + dist->dist_appendix[0] + 1;
  128. #endif
  129. }
  130. /*!
  131. * \brief Apply new configuration.
  132. *
  133. * \param dist Pointer to the discovery datagram. It is assumed, that
  134. * the validity of the datagram contents had been checked
  135. * by the caller.
  136. */
  137. int NutDiscoveryAppConf(DISCOVERY_TELE * dist)
  138. {
  139. memset(confos.hostname, 0, sizeof(confos.hostname));
  140. #if DISCOVERY_VERSION <= 0x10
  141. strncpy(confos.hostname, (char *)dist->dist_hostname, sizeof(confos.hostname) - 1);
  142. #else
  143. memcpy(confos.hostname, &dist->dist_appendix[1], dist->dist_appendix[0]);
  144. #endif
  145. NutSaveConfig();
  146. memcpy(confnet.cdn_mac, dist->dist_mac, sizeof(confnet.cdn_mac));
  147. confnet.cdn_ip_addr = dist->dist_ip_addr;
  148. confnet.cdn_ip_mask = dist->dist_ip_mask;
  149. confnet.cdn_gateway = dist->dist_gateway;
  150. confnet.cdn_cip_addr = dist->dist_cip_addr;
  151. return NutNetSaveConfig();
  152. }
  153. /*
  154. * \brief Default discovery datagram handler.
  155. *
  156. * \param ip Sender's IP address.
  157. * \param port Sender's UDP port.
  158. * \param dtel Pointer to the UDP telegram buffer.
  159. * \param len UDP telegram size.
  160. */
  161. static int NutDiscoveryHandler(uint32_t ip, uint16_t port, DISCOVERY_TELE * dist, int len)
  162. {
  163. int rc = -1;
  164. #if DISCOVERY_VERSION <= 0x10
  165. size_t minlen = sizeof(DISCOVERY_TELE) - sizeof(dist->dist_custom);
  166. #else
  167. size_t minlen = sizeof(DISCOVERY_TELE) - sizeof(dist->dist_appendix) + 1;
  168. #endif
  169. /* Check minimum datagram length. */
  170. if (len >= minlen) {
  171. /*
  172. * Request telegram.
  173. */
  174. if (dist->dist_type == DIST_REQUEST) {
  175. /* Respond to requests. */
  176. rc = NutDiscoveryAnnTele(dist);
  177. }
  178. /*
  179. * Apply telegram.
  180. */
  181. else if (dist->dist_type == DIST_APPLY
  182. /* Check exchange ID. */
  183. && dist->dist_xid == xid
  184. /* Required protocol version. */
  185. && dist->dist_ver == DISCOVERY_VERSION) {
  186. xid += NutGetTickCount();
  187. /* Store configuration. */
  188. rc = NutDiscoveryAppConf(dist);
  189. }
  190. }
  191. return rc;
  192. }
  193. THREAD(DiscoveryResponder, arg)
  194. {
  195. UDPSOCKET *sock;
  196. DISCOVERY_TELE *dist;
  197. uint32_t raddr;
  198. uint16_t rport;
  199. int len;
  200. /* Insist on allocating a datagram buffer. */
  201. while ((dist = malloc(sizeof(DISCOVERY_TELE))) == NULL) {
  202. NutSleep(1000);
  203. }
  204. /* Insist on creating a socket. */
  205. while ((sock = NutUdpCreateSocket(disopt.disopt_port)) == NULL) {
  206. NutSleep(1000);
  207. }
  208. /* Nut/Net doesn't provide UDP datagram buffering by default. */
  209. {
  210. uint16_t max_ms = sizeof(DISCOVERY_TELE) * 3;
  211. NutUdpSetSockOpt(sock, SO_RCVBUF, &max_ms, sizeof(max_ms));
  212. }
  213. /* Create a pseudo random telegram identifier. */
  214. memcpy(&xid, &confnet.cdn_mac[2], sizeof(xid));
  215. xid += NutGetTickCount();
  216. /* Optionally send initial announce datagram. */
  217. if (disopt.disopt_flags & DISF_INITAL_ANN) {
  218. /* Variable sleep avoids broadcast storms in large installations. */
  219. NutSleep(500 + (xid & 0x7FF));
  220. if ((len = NutDiscoveryAnnTele(dist)) > 0) {
  221. NutUdpSendTo(sock, INADDR_BROADCAST, disopt.disopt_port, dist, len);
  222. }
  223. }
  224. /* Handle discovery telegrams in an endless loop. */
  225. for (;;) {
  226. len = NutUdpReceiveFrom(sock, &raddr, &rport, dist, sizeof(DISCOVERY_TELE), 0);
  227. /* Updates may be filtered by an IP mask. */
  228. if ((raddr & disopt.disopt_ipmask) == raddr && len > 0 && discovery_callback) {
  229. if ((len = discovery_callback(raddr, rport, dist, len)) > 0) {
  230. /* Broadcast response if destination is unreachable. */
  231. if ((raddr & confnet.cdn_ip_mask) != (confnet.cdn_ip_addr & confnet.cdn_ip_mask)) {
  232. raddr = INADDR_BROADCAST;
  233. }
  234. NutUdpSendTo(sock, raddr, disopt.disopt_port, dist, len);
  235. }
  236. }
  237. /* Avoid system blocking by datagram storms. */
  238. NutSleep(100);
  239. }
  240. }
  241. /*!
  242. * \brief Register a custom discovery callback handler.
  243. *
  244. * When a callback had been registered, all datagrams matching the IP mask
  245. * are passed to this function, which should inspect the datagram contents
  246. * and take any required action like calling NutDiscoveryAnnTele() etc.
  247. * If the callback returns a positive value, a response will be sent
  248. * back, using that return value as its length.
  249. *
  250. * \param func Pointer to the callback function or NULL to disable
  251. * responses.
  252. *
  253. * \return Previously used callback function pointer.
  254. */
  255. NutDiscoveryCallback NutRegisterDiscoveryCallback(NutDiscoveryCallback func)
  256. {
  257. NutDiscoveryCallback rc = discovery_callback;
  258. discovery_callback = func;
  259. return rc;
  260. }
  261. /*!
  262. * \brief Register discovery telegram responder.
  263. *
  264. * The first call will activate the responder thread. Any subsequent
  265. * calls will return a failure.
  266. *
  267. * \note Enabling a discovery responder is a potential security hole.
  268. *
  269. * \param ipmask Update datagrams from remote hosts, which do not fit to
  270. * this mask are ignored. Set to INADDR_BROADCAST to allow
  271. * any. If zero, no updates are allowed.
  272. * \param port The responder will listen to this UDP port. If zero,
  273. * the default port \ref DISCOVERY_PORT is used.
  274. * \param flags Option value, may contain any combination of DISF_ flags.
  275. *
  276. * \return 0 if a handler thread had been started, -1 otherwise.
  277. */
  278. int NutRegisterDiscovery(uint32_t ipmask, uint16_t port, unsigned int flags)
  279. {
  280. static HANDLE tid = NULL;
  281. if (tid == NULL) {
  282. disopt.disopt_ipmask = ipmask;
  283. disopt.disopt_port = port ? port : DISCOVERY_PORT;
  284. disopt.disopt_flags = flags;
  285. tid = NutThreadCreate("udisc", DiscoveryResponder, NULL,
  286. (NUT_THREAD_DISTSTACK * NUT_THREAD_STACK_MULT) + NUT_THREAD_STACK_ADD);
  287. if (tid) {
  288. return 0;
  289. }
  290. }
  291. return -1;
  292. }
  293. /*@}*/