1
0

UDPAddrIface.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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* allocator;
  31. struct Log* logger;
  32. /** Job to close the handle when the allocator is freed */
  33. struct Allocator_OnFreeJob* closeHandleOnFree;
  34. /** Job which blocks the freeing until the callback completes */
  35. struct Allocator_OnFreeJob* blockFreeInsideCallback;
  36. uv_udp_t uvHandle;
  37. int queueLen;
  38. /** true if we are inside of the callback, used by blockFreeInsideCallback */
  39. int inCallback;
  40. Identity
  41. };
  42. struct UDPAddrIface_WriteRequest_pvt {
  43. uv_udp_send_t uvReq;
  44. int32_t length;
  45. struct UDPAddrIface_pvt* udp;
  46. struct Message* msg;
  47. struct Allocator* alloc;
  48. Identity
  49. };
  50. static struct UDPAddrIface_pvt* ifaceForHandle(uv_udp_t* handle)
  51. {
  52. char* hp = ((char*)handle) - offsetof(struct UDPAddrIface_pvt, uvHandle);
  53. return Identity_check((struct UDPAddrIface_pvt*) hp);
  54. }
  55. static void sendComplete(uv_udp_send_t* uvReq, int error)
  56. {
  57. struct UDPAddrIface_WriteRequest_pvt* req =
  58. Identity_check((struct UDPAddrIface_WriteRequest_pvt*) uvReq);
  59. if (error) {
  60. Log_debug(req->udp->logger, "DROP Failed to write to UDPAddrIface [%s]",
  61. uv_strerror(error) );
  62. }
  63. Assert_true(Message_getLength(req->msg) == req->length);
  64. req->udp->queueLen -= Message_getLength(req->msg);
  65. Assert_true(req->udp->queueLen >= 0);
  66. Allocator_free(req->alloc);
  67. }
  68. static Iface_DEFUN incomingFromIface(struct Message* m, struct Iface* iface)
  69. {
  70. struct UDPAddrIface_pvt* context = Identity_check((struct UDPAddrIface_pvt*) iface);
  71. Assert_true(Message_getLength(m) >= Sockaddr_OVERHEAD);
  72. if (((struct Sockaddr*)m->msgbytes)->flags & Sockaddr_flags_BCAST) {
  73. Log_debug(context->logger, "Attempted bcast, bcast unsupported");
  74. // bcast not supported.
  75. return Error(m, "UNHANDLED");
  76. }
  77. if (context->queueLen > UDPAddrIface_MAX_QUEUE) {
  78. Log_warn(context->logger, "DROP msg length [%d] to [%s] maximum queue length reached",
  79. Message_getLength(m), Sockaddr_print(context->pub.generic.addr, Message_getAlloc(m)));
  80. return Error(m, "OVERFLOW");
  81. }
  82. // This allocator will hold the message allocator in existance after it is freed.
  83. struct Allocator* reqAlloc = Allocator_child(context->allocator);
  84. Allocator_adopt(reqAlloc, Message_getAlloc(m));
  85. struct UDPAddrIface_WriteRequest_pvt* req =
  86. Allocator_clone(reqAlloc, (&(struct UDPAddrIface_WriteRequest_pvt) {
  87. .udp = context,
  88. .msg = m,
  89. .alloc = reqAlloc
  90. }));
  91. Identity_set(req);
  92. struct Sockaddr_storage ss;
  93. Er_assert(Message_epop(m, &ss, context->pub.generic.addr->addrLen));
  94. Assert_true(ss.addr.addrLen == context->pub.generic.addr->addrLen);
  95. req->length = Message_getLength(m);
  96. uv_buf_t buffers[] = {
  97. { .base = (char*)m->msgbytes, .len = Message_getLength(m) }
  98. };
  99. int ret = uv_udp_send(&req->uvReq, &context->uvHandle, buffers, 1,
  100. (const struct sockaddr*)ss.nativeAddr, (uv_udp_send_cb)&sendComplete);
  101. if (ret) {
  102. Log_info(context->logger, "DROP Failed writing to UDPAddrIface [%s]",
  103. uv_strerror(ret));
  104. Allocator_free(req->alloc);
  105. return Error(m, "UNHANDLED");
  106. }
  107. context->queueLen += Message_getLength(m);
  108. return NULL;
  109. }
  110. #if UDPAddrIface_PADDING_AMOUNT < 8
  111. #error
  112. #endif
  113. #define ALLOC(buff) (((struct Message**) &(buff[-(8 + (((uintptr_t)buff) % 8))]))[0])
  114. static void incoming(uv_udp_t* handle,
  115. ssize_t nread,
  116. const uv_buf_t* buf,
  117. const struct sockaddr* addr,
  118. unsigned flags)
  119. {
  120. struct UDPAddrIface_pvt* context = ifaceForHandle(handle);
  121. context->inCallback = 1;
  122. // Grab out the allocator which was placed there by allocate()
  123. struct Message* msg = buf->base ? ALLOC(buf->base) : NULL;
  124. // if nread < 0, we used to log uv_last_error, which doesn't exist anymore.
  125. if (nread == 0) {
  126. // Happens constantly
  127. //Log_debug(context->logger, "0 length read");
  128. } else {
  129. Er_assert(Message_truncate(msg, nread));
  130. Er_assert(Message_epush(msg, addr, context->pub.generic.addr->addrLen - Sockaddr_OVERHEAD));
  131. // make sure the sockaddr doesn't have crap in it which will
  132. // prevent it from being used as a lookup key
  133. Sockaddr_normalizeNative((struct sockaddr*) msg->msgbytes);
  134. Er_assert(Message_epush(msg, context->pub.generic.addr, Sockaddr_OVERHEAD));
  135. /*uint8_t buff[256] = {0};
  136. Assert_true(Hex_encode(buff, 255, m->bytes, context->pub.generic.addr->addrLen));
  137. Log_debug(context->logger, "Message from [%s]", buff);*/
  138. Iface_send(&context->pub.generic.iface, msg);
  139. }
  140. if (msg) {
  141. Allocator_free(Message_getAlloc(msg));
  142. }
  143. context->inCallback = 0;
  144. if (context->blockFreeInsideCallback) {
  145. Allocator_onFreeComplete((struct Allocator_OnFreeJob*) context->blockFreeInsideCallback);
  146. }
  147. }
  148. static void allocate(uv_handle_t* handle, size_t size, uv_buf_t* buf)
  149. {
  150. struct UDPAddrIface_pvt* context = ifaceForHandle((uv_udp_t*)handle);
  151. size = UDPAddrIface_BUFFER_CAP;
  152. struct Allocator* child = Allocator_child(context->allocator);
  153. struct Message* msg = Message_new(
  154. UDPAddrIface_BUFFER_CAP,
  155. UDPAddrIface_PADDING_AMOUNT + context->pub.generic.addr->addrLen,
  156. child
  157. );
  158. ALLOC(msg->msgbytes) = msg;
  159. buf->base = msg->msgbytes;
  160. buf->len = size;
  161. }
  162. static void onClosed(uv_handle_t* wasClosed)
  163. {
  164. struct UDPAddrIface_pvt* context =
  165. Identity_check((struct UDPAddrIface_pvt*) wasClosed->data);
  166. Allocator_onFreeComplete((struct Allocator_OnFreeJob*) context->closeHandleOnFree);
  167. }
  168. static int closeHandleOnFree(struct Allocator_OnFreeJob* job)
  169. {
  170. struct UDPAddrIface_pvt* context =
  171. Identity_check((struct UDPAddrIface_pvt*) job->userData);
  172. context->closeHandleOnFree = job;
  173. uv_close((uv_handle_t*)&context->uvHandle, onClosed);
  174. return Allocator_ONFREE_ASYNC;
  175. }
  176. static int blockFreeInsideCallback(struct Allocator_OnFreeJob* job)
  177. {
  178. struct UDPAddrIface_pvt* context =
  179. Identity_check((struct UDPAddrIface_pvt*) job->userData);
  180. if (!context->inCallback) {
  181. return 0;
  182. }
  183. context->blockFreeInsideCallback = job;
  184. return Allocator_ONFREE_ASYNC;
  185. }
  186. int UDPAddrIface_setDSCP(struct UDPAddrIface* iface, uint8_t dscp)
  187. {
  188. int res = 0;
  189. /* For win32 setsockopt is unable to mark the TOS field in IP header, do not support it now */
  190. #ifndef win32
  191. struct UDPAddrIface_pvt* context = Identity_check((struct UDPAddrIface_pvt*) iface);
  192. /* 6-bit DSCP, 2-bit ENC(useless for UDP) */
  193. int tos = dscp << 2;
  194. if (Sockaddr_getFamily(context->pub.generic.addr) == Sockaddr_AF_INET) {
  195. res = setsockopt(context->uvHandle.io_watcher.fd, IPPROTO_IP, IP_TOS,
  196. &tos, sizeof(tos));
  197. } else if (Sockaddr_getFamily(context->pub.generic.addr) == Sockaddr_AF_INET6) {
  198. res = setsockopt(context->uvHandle.io_watcher.fd, IPPROTO_IPV6, IPV6_TCLASS,
  199. &tos, sizeof(tos));
  200. }
  201. #endif
  202. return res;
  203. }
  204. int UDPAddrIface_getFd(struct UDPAddrIface* iface)
  205. {
  206. int out = -1;
  207. #ifndef win32
  208. struct UDPAddrIface_pvt* context = Identity_check((struct UDPAddrIface_pvt*) iface);
  209. out = context->uvHandle.io_watcher.fd;
  210. #endif
  211. return out;
  212. }
  213. int UDPAddrIface_setBroadcast(struct UDPAddrIface* iface, bool enable)
  214. {
  215. struct UDPAddrIface_pvt* context = Identity_check((struct UDPAddrIface_pvt*) iface);
  216. return uv_udp_set_broadcast(&context->uvHandle, enable ? 1 : 0);
  217. }
  218. Er_DEFUN(struct UDPAddrIface* UDPAddrIface_new(struct EventBase* eventBase,
  219. struct Sockaddr* addr,
  220. struct Allocator* alloc,
  221. struct Log* logger))
  222. {
  223. struct EventBase_pvt* base = EventBase_privatize(eventBase);
  224. struct UDPAddrIface_pvt* context =
  225. Allocator_clone(alloc, (&(struct UDPAddrIface_pvt) {
  226. .logger = logger,
  227. .allocator = alloc
  228. }));
  229. context->pub.generic.alloc = alloc;
  230. context->pub.generic.iface.send = incomingFromIface;
  231. Identity_set(context);
  232. if (addr) {
  233. Log_debug(logger, "Binding to address [%s]", Sockaddr_print(addr, alloc));
  234. }
  235. struct Sockaddr_storage ss;
  236. if (!addr) {
  237. Sockaddr_parse("0.0.0.0:0", &ss);
  238. addr = &ss.addr;
  239. }
  240. uv_udp_init(base->loop, &context->uvHandle);
  241. context->uvHandle.data = context;
  242. int ret;
  243. void* native = Sockaddr_asNative(addr);
  244. ret = uv_udp_bind(&context->uvHandle, (const struct sockaddr*)native, 0);
  245. if (ret) {
  246. Er_raise(alloc, "call to uv_udp_bind() failed [%s]", uv_strerror(ret));
  247. }
  248. ret = uv_udp_recv_start(&context->uvHandle, allocate, incoming);
  249. if (ret) {
  250. const char* err = uv_strerror(ret);
  251. uv_close((uv_handle_t*) &context->uvHandle, NULL);
  252. Er_raise(alloc, "uv_udp_recv_start() failed [%s]", err);
  253. }
  254. int nameLen = sizeof(struct Sockaddr_storage);
  255. Bits_memset(&ss, 0, sizeof(struct Sockaddr_storage));
  256. ret = uv_udp_getsockname(&context->uvHandle, (void*)ss.nativeAddr, &nameLen);
  257. if (ret) {
  258. const char* err = uv_strerror(ret);
  259. uv_close((uv_handle_t*) &context->uvHandle, NULL);
  260. Er_raise(alloc, "uv_udp_getsockname() failed [%s]", err);
  261. }
  262. ss.addr.addrLen = nameLen + 8;
  263. context->pub.generic.addr = Sockaddr_clone(&ss.addr, alloc);
  264. Log_debug(logger, "Bound to address [%s]", Sockaddr_print(context->pub.generic.addr, alloc));
  265. Allocator_onFree(alloc, closeHandleOnFree, context);
  266. Allocator_onFree(alloc, blockFreeInsideCallback, context);
  267. Er_ret(&context->pub);
  268. }