1'use strict'; 2 3const { 4 Symbol, 5} = primordials; 6 7const { codes } = require('internal/errors'); 8const { UDP } = internalBinding('udp_wrap'); 9const { guessHandleType } = internalBinding('util'); 10const { isInt32 } = require('internal/validators'); 11const { UV_EINVAL } = internalBinding('uv'); 12const { ERR_INVALID_ARG_TYPE, ERR_SOCKET_BAD_TYPE } = codes; 13const kStateSymbol = Symbol('state symbol'); 14let dns; // Lazy load for startup performance. 15 16 17function lookup4(lookup, address, callback) { 18 return lookup(address || '127.0.0.1', 4, callback); 19} 20 21 22function lookup6(lookup, address, callback) { 23 return lookup(address || '::1', 6, callback); 24} 25 26function newHandle(type, lookup) { 27 if (lookup === undefined) { 28 if (dns === undefined) { 29 dns = require('dns'); 30 } 31 32 lookup = dns.lookup; 33 } else if (typeof lookup !== 'function') { 34 throw new ERR_INVALID_ARG_TYPE('lookup', 'Function', lookup); 35 } 36 37 if (type === 'udp4') { 38 const handle = new UDP(); 39 40 handle.lookup = lookup4.bind(handle, lookup); 41 return handle; 42 } 43 44 if (type === 'udp6') { 45 const handle = new UDP(); 46 47 handle.lookup = lookup6.bind(handle, lookup); 48 handle.bind = handle.bind6; 49 handle.connect = handle.connect6; 50 handle.send = handle.send6; 51 return handle; 52 } 53 54 throw new ERR_SOCKET_BAD_TYPE(); 55} 56 57 58function _createSocketHandle(address, port, addressType, fd, flags) { 59 const handle = newHandle(addressType); 60 let err; 61 62 if (isInt32(fd) && fd > 0) { 63 const type = guessHandleType(fd); 64 if (type !== 'UDP') { 65 err = UV_EINVAL; 66 } else { 67 err = handle.open(fd); 68 } 69 } else if (port || address) { 70 err = handle.bind(address, port || 0, flags); 71 } 72 73 if (err) { 74 handle.close(); 75 return err; 76 } 77 78 return handle; 79} 80 81 82module.exports = { 83 kStateSymbol, 84 _createSocketHandle, 85 newHandle 86}; 87