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