UDPAddrIface.c 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. /* vim: set expandtab ts=4 sw=4: */
  2. /*
  3. * You may redistribute this program and/or modify it under the terms of
  4. * the GNU General Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. */
  15. #include "util/events/libuv/UvWrapper.h"
  16. #include "exception/Except.h"
  17. #include "interface/Iface.h"
  18. #include "util/events/UDPAddrIface.h"
  19. #include "memory/Allocator.h"
  20. #include "util/events/libuv/EventBase_pvt.h"
  21. #include "util/platform/Sockaddr.h"
  22. #include "util/Assert.h"
  23. #include "util/Identity.h"
  24. #include "wire/Message.h"
  25. #include "wire/Error.h"
  26. #include "util/Hex.h"
  27. struct UDPAddrIface_pvt
  28. {
  29. struct UDPAddrIface pub;
  30. struct Allocator* userAlloc;
  31. struct Allocator* alloc;
  32. struct Log* logger;
  33. Iface_t iface;
  34. uv_udp_t uvHandle;
  35. int queueLen;
  36. /** true if we are inside of the callback, used by blockFreeInsideCallback */
  37. int inCallback;
  38. Identity
  39. };
  40. struct UDPAddrIface_WriteRequest_pvt {
  41. uv_udp_send_t uvReq;
  42. int32_t length;
  43. struct UDPAddrIface_pvt* udp;
  44. struct Message* msg;
  45. struct Allocator* alloc;
  46. Identity
  47. };
  48. static struct UDPAddrIface_pvt* ifaceForHandle(uv_udp_t* handle)
  49. {
  50. char* hp = ((char*)handle) - offsetof(struct UDPAddrIface_pvt, uvHandle);
  51. return Identity_check((struct UDPAddrIface_pvt*) hp);
  52. }
  53. static void sendComplete(uv_udp_send_t* uvReq, int error)
  54. {
  55. struct UDPAddrIface_WriteRequest_pvt* req =
  56. Identity_check((struct UDPAddrIface_WriteRequest_pvt*) uvReq);
  57. if (error) {
  58. Log_debug(req->udp->logger, "DROP Failed to write to UDPAddrIface [%s]",
  59. uv_strerror(error) );
  60. }
  61. Assert_true(Message_getLength(req->msg) == req->length);
  62. req->udp->queueLen -= Message_getLength(req->msg);
  63. Assert_true(req->udp->queueLen >= 0);
  64. Allocator_free(req->alloc);
  65. }
  66. static Iface_DEFUN incomingFromIface(struct Message* m, struct Iface* iface)
  67. {
  68. struct UDPAddrIface_pvt* context =
  69. Identity_containerOf(iface, struct UDPAddrIface_pvt, iface);
  70. Assert_true(Message_getLength(m) >= Sockaddr_OVERHEAD);
  71. if (((struct Sockaddr*)m->msgbytes)->flags & Sockaddr_flags_BCAST) {
  72. Log_debug(context->logger, "Attempted bcast, bcast unsupported");
  73. // bcast not supported.
  74. return Error(m, "UNHANDLED");
  75. }
  76. if (context->queueLen > UDPAddrIface_MAX_QUEUE) {
  77. Log_warn(context->logger, "DROP msg length [%d] to [%s] maximum queue length reached",
  78. Message_getLength(m), Sockaddr_print(context->pub.generic.addr, Message_getAlloc(m)));
  79. return Error(m, "OVERFLOW");
  80. }
  81. // This allocator will hold the message allocator in existance after it is freed.
  82. struct Allocator* reqAlloc = Allocator_child(context->alloc);
  83. Allocator_adopt(reqAlloc, Message_getAlloc(m));
  84. struct UDPAddrIface_WriteRequest_pvt* req =
  85. Allocator_clone(reqAlloc, (&(struct UDPAddrIface_WriteRequest_pvt) {
  86. .udp = context,
  87. .msg = m,
  88. .alloc = reqAlloc
  89. }));
  90. Identity_set(req);
  91. struct Sockaddr_storage ss;
  92. Er_assert(Message_epop(m, &ss, context->pub.generic.addr->addrLen));
  93. Assert_true(ss.addr.addrLen == context->pub.generic.addr->addrLen);
  94. req->length = Message_getLength(m);
  95. uv_buf_t buffers[] = {
  96. { .base = (char*)m->msgbytes, .len = Message_getLength(m) }
  97. };
  98. int ret = uv_udp_send(&req->uvReq, &context->uvHandle, buffers, 1,
  99. (const struct sockaddr*)ss.nativeAddr, (uv_udp_send_cb)&sendComplete);
  100. if (ret) {
  101. Log_info(context->logger, "DROP Failed writing to UDPAddrIface [%s]",
  102. uv_strerror(ret));
  103. Allocator_free(req->alloc);
  104. return Error(m, "UNHANDLED");
  105. }
  106. context->queueLen += Message_getLength(m);
  107. return NULL;
  108. }
  109. static void onClosed(uv_handle_t* wasClosed)
  110. {
  111. struct UDPAddrIface_pvt* context =
  112. Identity_check((struct UDPAddrIface_pvt*) wasClosed->data);
  113. Allocator_free(context->alloc);
  114. }
  115. #if UDPAddrIface_PADDING_AMOUNT < 8
  116. #error
  117. #endif
  118. #define ALLOC(buff) (((struct Message**) &(buff[-(8 + (((uintptr_t)buff) % 8))]))[0])
  119. static void incoming(uv_udp_t* handle,
  120. ssize_t nread,
  121. const uv_buf_t* buf,
  122. const struct sockaddr* addr,
  123. unsigned flags)
  124. {
  125. struct UDPAddrIface_pvt* context = ifaceForHandle(handle);
  126. context->inCallback = 1;
  127. // Grab out the allocator which was placed there by allocate()
  128. struct Message* msg = buf->base ? ALLOC(buf->base) : NULL;
  129. // if nread < 0, we used to log uv_last_error, which doesn't exist anymore.
  130. if (nread == 0) {
  131. // Happens constantly
  132. //Log_debug(context->logger, "0 length read");
  133. } else {
  134. Er_assert(Message_truncate(msg, nread));
  135. Er_assert(Message_epush(msg, addr, context->pub.generic.addr->addrLen - Sockaddr_OVERHEAD));
  136. // make sure the sockaddr doesn't have crap in it which will
  137. // prevent it from being used as a lookup key
  138. Sockaddr_normalizeNative((struct sockaddr*) msg->msgbytes);
  139. Er_assert(Message_epush(msg, context->pub.generic.addr, Sockaddr_OVERHEAD));
  140. /*uint8_t buff[256] = {0};
  141. Assert_true(Hex_encode(buff, 255, m->bytes, context->pub.generic.addr->addrLen));
  142. Log_debug(context->logger, "Message from [%s]", buff);*/
  143. Iface_send(context->pub.generic.iface, msg);
  144. }
  145. if (msg) {
  146. Allocator_free(Message_getAlloc(msg));
  147. }
  148. context->inCallback = 0;
  149. if (context->userAlloc == NULL) {
  150. uv_close((uv_handle_t*)&context->uvHandle, onClosed);
  151. }
  152. }
  153. static void allocate(uv_handle_t* handle, size_t size, uv_buf_t* buf)
  154. {
  155. struct UDPAddrIface_pvt* context = ifaceForHandle((uv_udp_t*)handle);
  156. size = UDPAddrIface_BUFFER_CAP;
  157. struct Allocator* child = Allocator_child(context->alloc);
  158. struct Message* msg = Message_new(
  159. UDPAddrIface_BUFFER_CAP,
  160. UDPAddrIface_PADDING_AMOUNT + context->pub.generic.addr->addrLen,
  161. child
  162. );
  163. ALLOC(msg->msgbytes) = msg;
  164. buf->base = msg->msgbytes;
  165. buf->len = size;
  166. }
  167. static int onFree(struct Allocator_OnFreeJob* job)
  168. {
  169. struct UDPAddrIface_pvt* context =
  170. Identity_check((struct UDPAddrIface_pvt*) job->userData);
  171. context->userAlloc = NULL;
  172. if (!context->inCallback) {
  173. uv_close((uv_handle_t*)&context->uvHandle, onClosed);
  174. }
  175. return 0;
  176. }
  177. int UDPAddrIface_setDSCP(struct UDPAddrIface* iface, uint8_t dscp)
  178. {
  179. int res = 0;
  180. /* For win32 setsockopt is unable to mark the TOS field in IP header, do not support it now */
  181. #ifndef win32
  182. struct UDPAddrIface_pvt* context = Identity_check((struct UDPAddrIface_pvt*) iface);
  183. /* 6-bit DSCP, 2-bit ENC(useless for UDP) */
  184. int tos = dscp << 2;
  185. if (Sockaddr_getFamily(context->pub.generic.addr) == Sockaddr_AF_INET) {
  186. res = setsockopt(context->uvHandle.io_watcher.fd, IPPROTO_IP, IP_TOS,
  187. &tos, sizeof(tos));
  188. } else if (Sockaddr_getFamily(context->pub.generic.addr) == Sockaddr_AF_INET6) {
  189. res = setsockopt(context->uvHandle.io_watcher.fd, IPPROTO_IPV6, IPV6_TCLASS,
  190. &tos, sizeof(tos));
  191. }
  192. #endif
  193. return res;
  194. }
  195. int UDPAddrIface_getFd(struct UDPAddrIface* iface)
  196. {
  197. int out = -1;
  198. #ifndef win32
  199. struct UDPAddrIface_pvt* context = Identity_check((struct UDPAddrIface_pvt*) iface);
  200. out = context->uvHandle.io_watcher.fd;
  201. #endif
  202. return out;
  203. }
  204. int UDPAddrIface_setBroadcast(struct UDPAddrIface* iface, bool enable)
  205. {
  206. struct UDPAddrIface_pvt* context = Identity_check((struct UDPAddrIface_pvt*) iface);
  207. return uv_udp_set_broadcast(&context->uvHandle, enable ? 1 : 0);
  208. }
  209. Er_DEFUN(struct UDPAddrIface* UDPAddrIface_new(struct EventBase* eventBase,
  210. struct Sockaddr* addr,
  211. struct Allocator* userAlloc,
  212. struct Log* logger))
  213. {
  214. struct EventBase_pvt* base = EventBase_privatize(eventBase);
  215. struct Allocator* alloc = Allocator_child(base->alloc);
  216. struct UDPAddrIface_pvt* context =
  217. Allocator_clone(alloc, (&(struct UDPAddrIface_pvt) {
  218. .logger = logger,
  219. .userAlloc = userAlloc,
  220. .alloc = alloc,
  221. }));
  222. context->pub.generic.alloc = alloc;
  223. context->pub.generic.iface = &context->iface;
  224. context->iface.send = incomingFromIface;
  225. Identity_set(context);
  226. if (addr) {
  227. Log_debug(logger, "Binding to address [%s]", Sockaddr_print(addr, alloc));
  228. }
  229. struct Sockaddr_storage ss;
  230. if (!addr) {
  231. Sockaddr_parse("0.0.0.0:0", &ss);
  232. addr = &ss.addr;
  233. }
  234. uv_udp_init(base->loop, &context->uvHandle);
  235. context->uvHandle.data = context;
  236. int ret;
  237. void* native = Sockaddr_asNative(addr);
  238. ret = uv_udp_bind(&context->uvHandle, (const struct sockaddr*)native, 0);
  239. if (ret) {
  240. Er_raise(alloc, "call to uv_udp_bind() failed [%s]", uv_strerror(ret));
  241. }
  242. ret = uv_udp_recv_start(&context->uvHandle, allocate, incoming);
  243. if (ret) {
  244. const char* err = uv_strerror(ret);
  245. uv_close((uv_handle_t*) &context->uvHandle, NULL);
  246. Er_raise(alloc, "uv_udp_recv_start() failed [%s]", err);
  247. }
  248. int nameLen = sizeof(struct Sockaddr_storage);
  249. Bits_memset(&ss, 0, sizeof(struct Sockaddr_storage));
  250. ret = uv_udp_getsockname(&context->uvHandle, (void*)ss.nativeAddr, &nameLen);
  251. if (ret) {
  252. const char* err = uv_strerror(ret);
  253. uv_close((uv_handle_t*) &context->uvHandle, NULL);
  254. Er_raise(alloc, "uv_udp_getsockname() failed [%s]", err);
  255. }
  256. ss.addr.addrLen = nameLen + 8;
  257. context->pub.generic.addr = Sockaddr_clone(&ss.addr, alloc);
  258. Log_debug(logger, "Bound to address [%s]", Sockaddr_print(context->pub.generic.addr, alloc));
  259. Allocator_onFree(userAlloc, onFree, context);
  260. Er_ret(&context->pub);
  261. }