All files / lib dgram.js

98.35% Statements 1012/1029
96.54% Branches 251/260
96% Functions 48/50
98.35% Lines 1012/1029

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 206x 206x 206x 206x 206x 206x 206x 206x 41x 41x 41x 41x 41x 41x 206x 206x 206x 206x 206x 206x 206x 206x 206x 187x 187x 187x 187x 187x 187x 187x 206x 206x 206x 206x 206x 206x 114x 114x 114x 114x 203x 203x 203x 114x 114x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 114x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 114x 36x 36x 36x 30x 30x 30x 36x 6x 6x 24x 36x 114x 114x 27x 27x 27x 27x 27x 27x 26x 2x 2x 2x 24x 24x 1x 1x 1x 23x 23x 23x 27x 27x 114x 114x 164x 164x 164x 164x 164x 164x 164x 163x 163x 163x 164x 164x 87x 84x 84x 84x 87x 87x 62x 62x 62x 87x 87x 87x 87x 163x 163x 164x 164x 1x 1x 1x 1x 162x 162x 164x 164x 9x 9x 9x 9x 9x 9x 9x 9x 4x 4x 4x 4x 4x 4x 4x         4x 4x 4x 5x 5x 5x 5x 4x 4x 4x 4x 3x 3x 3x 3x 3x 3x 3x 3x 153x 153x 153x 153x 164x 41x 41x 41x 149x 112x 112x 112x 153x 153x 156x 128x 128x 5x 5x 128x 153x 153x 153x 153x 3x 3x 3x 3x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 153x 23x 23x 23x 23x 23x 23x 23x 2x 2x 2x 2x 23x 150x 127x 127x 126x 127x 127x 23x 23x 23x 23x 23x 23x 103x 103x 103x 153x 153x 153x 114x 114x 114x 19x 19x 11x 11x 13x 3x 3x 15x 15x 15x 15x 15x 15x 19x 13x 13x 13x 19x 13x 19x 4x 4x 4x 9x 9x 114x 114x 114x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 114x 114x 13x 13x 13x 13x 13x 13x 13x 13x     13x 13x 13x                     13x 13x 13x 13x 114x 114x 114x 3x 3x 3x 1x 1x 1x 3x 1x 1x 114x 114x 114x 114x 114x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 114x 114x 114x 178x 178x 18x 176x 2x 2x 2x 176x 176x 176x 176x 176x 178x 114x 114x 40x 40x 40x 40x 49x 49x 49x 43x 43x 41x 41x 49x 38x 38x 40x 114x 114x 31x 31x 31x 31x 31x 31x 26x 26x 26x 26x 31x 31x 114x 114x 23x 23x 23x 23x 114x 114x 3x 3x 3x 3x 114x 114x 23x 23x 23x 23x 23x 23x 23x 23x 23x 114x 27x 27x 27x 27x 27x 27x 27x 27x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 379x 379x 379x 379x 379x 379x 379x 379x 379x 379x 356x 168x 335x 188x 188x 188x 188x 379x 23x 10x 10x 3x 3x 3x 23x 13x 13x 23x 23x 23x 23x 373x 377x 333x 12x 333x 4x 4x 4x 321x 317x 317x 377x 2x 2x 2x 367x 367x 367x 364x 364x 364x 364x 364x 364x 364x 4x 4x 364x 3x 3x 361x 361x 361x 361x 364x 361x 361x 364x 361x 361x 361x 364x 27x 27x 27x 334x 334x 334x 334x 334x 334x 334x 334x 334x 334x 318x 364x 16x 16x 114x 114x 334x 334x 334x 334x 4x 2x 2x 2x 2x 2x 2x 334x 8x 8x 322x 322x 322x 322x 322x 322x 117x 117x 117x 322x 322x 322x 322x 16x 16x 322x 324x 319x 319x 319x 319x 319x 319x 3x 334x 2x 2x 2x 2x 334x 114x 1x 1x   1x 1x 1x 1x 1x 1x 114x 114x 149x 149x 149x 149x 149x 149x 149x 4x 4x 4x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 114x 114x 114x 145x 145x 145x 114x 114x 114x 106x 106x 106x 106x 106x 1x 1x 105x 105x 114x 114x 114x 29x 29x 29x 29x 29x 1x 1x 1x 1x 29x 1x 1x 114x 114x 114x 114x 3x 3x 1x 1x 114x 114x 114x 114x 3x 3x 3x 3x 1x 1x 1x 1x 114x 114x 114x 114x 3x 3x 3x 3x 1x 1x 1x 1x 114x 114x 114x 114x 3x 3x 1x 1x 2x 2x 114x 114x 114x 114x 8x 8x 8x 8x 8x 4x 4x 114x 114x 114x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 114x 114x 114x 114x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 114x 114x 114x 3x 3x 3x 3x 3x 1x 1x 2x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 114x 114x 114x 114x 3x 3x 3x 3x 3x 1x 1x 2x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 114x 114x 114x 826x 826x 3x 3x 3x 826x 114x 114x 146x 146x 146x 146x 146x 119x 119x 119x 146x 114x 114x 307x 307x 307x 1x 1x 306x 306x 307x 114x 114x 114x 4x 4x 4x 4x 4x 4x 114x 114x 114x 114x 8x 8x 8x 8x 8x 8x 114x 114x 114x 114x 6x 114x 114x 114x 114x 6x 114x 114x 114x 114x 9x 114x 114x 114x 114x 7x 114x 114x 114x 114x 114x 114x 1x 114x 114x 1x 114x 114x 114x 114x 114x 114x 1x 114x 114x 1x 114x 114x 114x 114x 114x 114x 2x 114x 114x 1x 114x 114x 114x 114x 114x 114x 1x 114x 114x 1x 114x 114x 114x 114x 114x 114x 1x 114x 114x 1x 114x 114x 114x 114x 114x 1x 114x 114x 114x 114x 1x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x  
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
 
'use strict';
 
const {
  Array,
  ArrayIsArray,
  ObjectDefineProperty,
  ObjectSetPrototypeOf,
} = primordials;
 
const errors = require('internal/errors');
const {
  kStateSymbol,
  _createSocketHandle,
  newHandle,
} = require('internal/dgram');
const { guessHandleType } = internalBinding('util');
const {
  ERR_INVALID_ARG_TYPE,
  ERR_MISSING_ARGS,
  ERR_SOCKET_ALREADY_BOUND,
  ERR_SOCKET_BAD_BUFFER_SIZE,
  ERR_SOCKET_BUFFER_SIZE,
  ERR_SOCKET_DGRAM_IS_CONNECTED,
  ERR_SOCKET_DGRAM_NOT_CONNECTED,
  ERR_SOCKET_DGRAM_NOT_RUNNING,
  ERR_INVALID_FD_TYPE
} = errors.codes;
const {
  isInt32,
  validateString,
  validateNumber,
  validatePort,
} = require('internal/validators');
const { Buffer } = require('buffer');
const { deprecate } = require('internal/util');
const { isUint8Array } = require('internal/util/types');
const EventEmitter = require('events');
const {
  defaultTriggerAsyncIdScope,
  symbols: { async_id_symbol, owner_symbol }
} = require('internal/async_hooks');
const { UV_UDP_REUSEADDR } = internalBinding('constants').os;
 
const {
  constants: { UV_UDP_IPV6ONLY },
  UDP,
  SendWrap
} = internalBinding('udp_wrap');
 
const BIND_STATE_UNBOUND = 0;
const BIND_STATE_BINDING = 1;
const BIND_STATE_BOUND = 2;
 
const CONNECT_STATE_DISCONNECTED = 0;
const CONNECT_STATE_CONNECTING = 1;
const CONNECT_STATE_CONNECTED = 2;
 
const RECV_BUFFER = true;
const SEND_BUFFER = false;
 
// Lazily loaded
let cluster = null;
 
const errnoException = errors.errnoException;
const exceptionWithHostPort = errors.exceptionWithHostPort;
 
 
function Socket(type, listener) {
  EventEmitter.call(this);
  let lookup;
  let recvBufferSize;
  let sendBufferSize;
 
  let options;
  if (type !== null && typeof type === 'object') {
    options = type;
    type = options.type;
    lookup = options.lookup;
    recvBufferSize = options.recvBufferSize;
    sendBufferSize = options.sendBufferSize;
  }
 
  const handle = newHandle(type, lookup);
  handle[owner_symbol] = this;
 
  this[async_id_symbol] = handle.getAsyncId();
  this.type = type;
 
  if (typeof listener === 'function')
    this.on('message', listener);
 
  this[kStateSymbol] = {
    handle,
    receiving: false,
    bindState: BIND_STATE_UNBOUND,
    connectState: CONNECT_STATE_DISCONNECTED,
    queue: undefined,
    reuseAddr: options && options.reuseAddr, // Use UV_UDP_REUSEADDR if true.
    ipv6Only: options && options.ipv6Only,
    recvBufferSize,
    sendBufferSize
  };
}
ObjectSetPrototypeOf(Socket.prototype, EventEmitter.prototype);
ObjectSetPrototypeOf(Socket, EventEmitter);
 
 
function createSocket(type, listener) {
  return new Socket(type, listener);
}
 
 
function startListening(socket) {
  const state = socket[kStateSymbol];
 
  state.handle.onmessage = onMessage;
  // Todo: handle errors
  state.handle.recvStart();
  state.receiving = true;
  state.bindState = BIND_STATE_BOUND;
 
  if (state.recvBufferSize)
    bufferSize(socket, state.recvBufferSize, RECV_BUFFER);
 
  if (state.sendBufferSize)
    bufferSize(socket, state.sendBufferSize, SEND_BUFFER);
 
  socket.emit('listening');
}
 
function replaceHandle(self, newHandle) {
  const state = self[kStateSymbol];
  const oldHandle = state.handle;
 
  // Set up the handle that we got from master.
  newHandle.lookup = oldHandle.lookup;
  newHandle.bind = oldHandle.bind;
  newHandle.send = oldHandle.send;
  newHandle[owner_symbol] = self;
 
  // Replace the existing handle by the handle we got from master.
  oldHandle.close();
  state.handle = newHandle;
  // Check if the udp handle was connected and set the state accordingly
  if (isConnected(self))
    state.connectState = CONNECT_STATE_CONNECTED;
}
 
function bufferSize(self, size, buffer) {
  if (size >>> 0 !== size)
    throw new ERR_SOCKET_BAD_BUFFER_SIZE();
 
  const ctx = {};
  const ret = self[kStateSymbol].handle.bufferSize(size, buffer, ctx);
  if (ret === undefined) {
    throw new ERR_SOCKET_BUFFER_SIZE(ctx);
  }
  return ret;
}
 
// Query master process to get the server handle and utilize it.
function bindServerHandle(self, options, errCb) {
  if (!cluster)
    cluster = require('cluster');
 
  const state = self[kStateSymbol];
  cluster._getServer(self, options, (err, handle) => {
    if (err) {
      errCb(err);
      return;
    }
 
    if (!state.handle) {
      // Handle has been closed in the mean time.
      return handle.close();
    }
 
    replaceHandle(self, handle);
    startListening(self);
  });
}
 
Socket.prototype.bind = function(port_, address_ /* , callback */) {
  let port = port_;
 
  healthCheck(this);
  const state = this[kStateSymbol];
 
  if (state.bindState !== BIND_STATE_UNBOUND)
    throw new ERR_SOCKET_ALREADY_BOUND();
 
  state.bindState = BIND_STATE_BINDING;
 
  const cb = arguments.length && arguments[arguments.length - 1];
  if (typeof cb === 'function') {
    function removeListeners() {
      this.removeListener('error', removeListeners);
      this.removeListener('listening', onListening);
    }
 
    function onListening() {
      removeListeners.call(this);
      cb.call(this);
    }
 
    this.on('error', removeListeners);
    this.on('listening', onListening);
  }
 
  if (port !== null &&
      typeof port === 'object' &&
      typeof port.recvStart === 'function') {
    replaceHandle(this, port);
    startListening(this);
    return this;
  }
 
  // Open an existing fd instead of creating a new one.
  if (port !== null && typeof port === 'object' &&
      isInt32(port.fd) && port.fd > 0) {
    const fd = port.fd;
    const exclusive = !!port.exclusive;
    const state = this[kStateSymbol];
 
    if (!cluster)
      cluster = require('cluster');
 
    if (cluster.isWorker && !exclusive) {
      bindServerHandle(this, {
        address: null,
        port: null,
        addressType: this.type,
        fd,
        flags: null
      }, (err) => {
        // Callback to handle error.
        const ex = errnoException(err, 'open');
        state.bindState = BIND_STATE_UNBOUND;
        this.emit('error', ex);
      });
      return this;
    }
 
    const type = guessHandleType(fd);
    if (type !== 'UDP')
      throw new ERR_INVALID_FD_TYPE(type);
    const err = state.handle.open(fd);
 
    if (err)
      throw errnoException(err, 'open');
 
    // Check if the udp handle was connected and set the state accordingly
    if (isConnected(this))
      state.connectState = CONNECT_STATE_CONNECTED;
 
    startListening(this);
    return this;
  }
 
  let address;
  let exclusive;
 
  if (port !== null && typeof port === 'object') {
    address = port.address || '';
    exclusive = !!port.exclusive;
    port = port.port;
  } else {
    address = typeof address_ === 'function' ? '' : address_;
    exclusive = false;
  }
 
  // Defaulting address for bind to all interfaces
  if (!address) {
    if (this.type === 'udp4')
      address = '0.0.0.0';
    else
      address = '::';
  }
 
  // Resolve address first
  state.handle.lookup(address, (err, ip) => {
    if (err) {
      state.bindState = BIND_STATE_UNBOUND;
      this.emit('error', err);
      return;
    }
 
    if (!cluster)
      cluster = require('cluster');
 
    let flags = 0;
    if (state.reuseAddr)
      flags |= UV_UDP_REUSEADDR;
    if (state.ipv6Only)
      flags |= UV_UDP_IPV6ONLY;
 
    if (cluster.isWorker && !exclusive) {
      bindServerHandle(this, {
        address: ip,
        port: port,
        addressType: this.type,
        fd: -1,
        flags: flags
      }, (err) => {
        // Callback to handle error.
        const ex = exceptionWithHostPort(err, 'bind', ip, port);
        state.bindState = BIND_STATE_UNBOUND;
        this.emit('error', ex);
      });
    } else {
      if (!state.handle)
        return; // Handle has been closed in the mean time
 
      const err = state.handle.bind(ip, port || 0, flags);
      if (err) {
        const ex = exceptionWithHostPort(err, 'bind', ip, port);
        state.bindState = BIND_STATE_UNBOUND;
        this.emit('error', ex);
        // Todo: close?
        return;
      }
 
      startListening(this);
    }
  });
 
  return this;
};
 
Socket.prototype.connect = function(port, address, callback) {
  port = validatePort(port, 'Port', { allowZero: false });
  if (typeof address === 'function') {
    callback = address;
    address = '';
  } else if (address === undefined) {
    address = '';
  }
 
  validateString(address, 'address');
 
  const state = this[kStateSymbol];
 
  if (state.connectState !== CONNECT_STATE_DISCONNECTED)
    throw new ERR_SOCKET_DGRAM_IS_CONNECTED();
 
  state.connectState = CONNECT_STATE_CONNECTING;
  if (state.bindState === BIND_STATE_UNBOUND)
    this.bind({ port: 0, exclusive: true }, null);
 
  if (state.bindState !== BIND_STATE_BOUND) {
    enqueue(this, _connect.bind(this, port, address, callback));
    return;
  }
 
  _connect.call(this, port, address, callback);
};
 
 
function _connect(port, address, callback) {
  const state = this[kStateSymbol];
  if (callback)
    this.once('connect', callback);
 
  const afterDns = (ex, ip) => {
    defaultTriggerAsyncIdScope(
      this[async_id_symbol],
      doConnect,
      ex, this, ip, address, port, callback
    );
  };
 
  state.handle.lookup(address, afterDns);
}
 
 
function doConnect(ex, self, ip, address, port, callback) {
  const state = self[kStateSymbol];
  if (!state.handle)
    return;
 
  if (!ex) {
    const err = state.handle.connect(ip, port);
    if (err) {
      ex = exceptionWithHostPort(err, 'connect', address, port);
    }
  }
 
  if (ex) {
    state.connectState = CONNECT_STATE_DISCONNECTED;
    return process.nextTick(() => {
      if (callback) {
        self.removeListener('connect', callback);
        callback(ex);
      } else {
        self.emit('error', ex);
      }
    });
  }
 
  state.connectState = CONNECT_STATE_CONNECTED;
  process.nextTick(() => self.emit('connect'));
}
 
 
Socket.prototype.disconnect = function() {
  const state = this[kStateSymbol];
  if (state.connectState !== CONNECT_STATE_CONNECTED)
    throw new ERR_SOCKET_DGRAM_NOT_CONNECTED();
 
  const err = state.handle.disconnect();
  if (err)
    throw errnoException(err, 'connect');
  else
    state.connectState = CONNECT_STATE_DISCONNECTED;
};
 
 
// Thin wrapper around `send`, here for compatibility with dgram_legacy.js
Socket.prototype.sendto = function(buffer,
                                   offset,
                                   length,
                                   port,
                                   address,
                                   callback) {
  validateNumber(offset, 'offset');
  validateNumber(length, 'length');
  validateNumber(port, 'port');
  validateString(address, 'address');
 
  this.send(buffer, offset, length, port, address, callback);
};
 
 
function sliceBuffer(buffer, offset, length) {
  if (typeof buffer === 'string') {
    buffer = Buffer.from(buffer);
  } else if (!isUint8Array(buffer)) {
    throw new ERR_INVALID_ARG_TYPE('buffer',
                                   ['Buffer', 'Uint8Array', 'string'], buffer);
  }
 
  offset = offset >>> 0;
  length = length >>> 0;
 
  return buffer.slice(offset, offset + length);
}
 
 
function fixBufferList(list) {
  const newlist = new Array(list.length);
 
  for (let i = 0, l = list.length; i < l; i++) {
    const buf = list[i];
    if (typeof buf === 'string')
      newlist[i] = Buffer.from(buf);
    else if (!isUint8Array(buf))
      return null;
    else
      newlist[i] = buf;
  }
 
  return newlist;
}
 
 
function enqueue(self, toEnqueue) {
  const state = self[kStateSymbol];
 
  // If the send queue hasn't been initialized yet, do it, and install an
  // event handler that flushes the send queue after binding is done.
  if (state.queue === undefined) {
    state.queue = [];
    self.once(EventEmitter.errorMonitor, onListenError);
    self.once('listening', onListenSuccess);
  }
  state.queue.push(toEnqueue);
}
 
 
function onListenSuccess() {
  this.removeListener(EventEmitter.errorMonitor, onListenError);
  clearQueue.call(this);
}
 
 
function onListenError(err) {
  this.removeListener('listening', onListenSuccess);
  this[kStateSymbol].queue = undefined;
}
 
 
function clearQueue() {
  const state = this[kStateSymbol];
  const queue = state.queue;
  state.queue = undefined;
 
  // Flush the send queue.
  for (const queueEntry of queue)
    queueEntry();
}
 
function isConnected(self) {
  try {
    self.remoteAddress();
    return true;
  } catch {
    return false;
  }
}
 
 
// valid combinations
// For connectionless sockets
// send(buffer, offset, length, port, address, callback)
// send(buffer, offset, length, port, address)
// send(buffer, offset, length, port, callback)
// send(buffer, offset, length, port)
// send(bufferOrList, port, address, callback)
// send(bufferOrList, port, address)
// send(bufferOrList, port, callback)
// send(bufferOrList, port)
// For connected sockets
// send(buffer, offset, length, callback)
// send(buffer, offset, length)
// send(bufferOrList, callback)
// send(bufferOrList)
Socket.prototype.send = function(buffer,
                                 offset,
                                 length,
                                 port,
                                 address,
                                 callback) {
 
  let list;
  const state = this[kStateSymbol];
  const connected = state.connectState === CONNECT_STATE_CONNECTED;
  if (!connected) {
    if (address || (port && typeof port !== 'function')) {
      buffer = sliceBuffer(buffer, offset, length);
    } else {
      callback = port;
      port = offset;
      address = length;
    }
  } else {
    if (typeof length === 'number') {
      buffer = sliceBuffer(buffer, offset, length);
      if (typeof port === 'function') {
        callback = port;
        port = null;
      }
    } else {
      callback = offset;
    }
 
    if (port || address)
      throw new ERR_SOCKET_DGRAM_IS_CONNECTED();
  }
 
  if (!ArrayIsArray(buffer)) {
    if (typeof buffer === 'string') {
      list = [ Buffer.from(buffer) ];
    } else if (!isUint8Array(buffer)) {
      throw new ERR_INVALID_ARG_TYPE('buffer',
                                     ['Buffer', 'Uint8Array', 'string'],
                                     buffer);
    } else {
      list = [ buffer ];
    }
  } else if (!(list = fixBufferList(buffer))) {
    throw new ERR_INVALID_ARG_TYPE('buffer list arguments',
                                   ['Buffer', 'string'], buffer);
  }
 
  if (!connected)
    port = validatePort(port, 'Port', { allowZero: false });
 
  // Normalize callback so it's either a function or undefined but not anything
  // else.
  if (typeof callback !== 'function')
    callback = undefined;
 
  if (typeof address === 'function') {
    callback = address;
    address = undefined;
  } else if (address && typeof address !== 'string') {
    throw new ERR_INVALID_ARG_TYPE('address', ['string', 'falsy'], address);
  }
 
  healthCheck(this);
 
  if (state.bindState === BIND_STATE_UNBOUND)
    this.bind({ port: 0, exclusive: true }, null);
 
  if (list.length === 0)
    list.push(Buffer.alloc(0));
 
  // If the socket hasn't been bound yet, push the outbound packet onto the
  // send queue and send after binding is complete.
  if (state.bindState !== BIND_STATE_BOUND) {
    enqueue(this, this.send.bind(this, list, port, address, callback));
    return;
  }
 
  const afterDns = (ex, ip) => {
    defaultTriggerAsyncIdScope(
      this[async_id_symbol],
      doSend,
      ex, this, ip, list, address, port, callback
    );
  };
 
  if (!connected) {
    state.handle.lookup(address, afterDns);
  } else {
    afterDns(null, null);
  }
};
 
function doSend(ex, self, ip, list, address, port, callback) {
  const state = self[kStateSymbol];
 
  if (ex) {
    if (typeof callback === 'function') {
      process.nextTick(callback, ex);
      return;
    }
 
    process.nextTick(() => self.emit('error', ex));
    return;
  } else if (!state.handle) {
    return;
  }
 
  const req = new SendWrap();
  req.list = list;  // Keep reference alive.
  req.address = address;
  req.port = port;
  if (callback) {
    req.callback = callback;
    req.oncomplete = afterSend;
  }
 
  let err;
  if (port)
    err = state.handle.send(req, list, list.length, port, ip, !!callback);
  else
    err = state.handle.send(req, list, list.length, !!callback);
 
  if (err >= 1) {
    // Synchronous finish. The return code is msg_length + 1 so that we can
    // distinguish between synchronous success and asynchronous success.
    if (callback)
      process.nextTick(callback, null, err - 1);
    return;
  }
 
  if (err && callback) {
    // Don't emit as error, dgram_legacy.js compatibility
    const ex = exceptionWithHostPort(err, 'send', address, port);
    process.nextTick(callback, ex);
  }
}
 
function afterSend(err, sent) {
  if (err) {
    err = exceptionWithHostPort(err, 'send', this.address, this.port);
  } else {
    err = null;
  }
 
  this.callback(err, sent);
}
 
Socket.prototype.close = function(callback) {
  const state = this[kStateSymbol];
  const queue = state.queue;
 
  if (typeof callback === 'function')
    this.on('close', callback);
 
  if (queue !== undefined) {
    queue.push(this.close.bind(this));
    return this;
  }
 
  healthCheck(this);
  stopReceiving(this);
  state.handle.close();
  state.handle = null;
  defaultTriggerAsyncIdScope(this[async_id_symbol],
                             process.nextTick,
                             socketCloseNT,
                             this);
 
  return this;
};
 
 
function socketCloseNT(self) {
  self.emit('close');
}
 
 
Socket.prototype.address = function() {
  healthCheck(this);
 
  const out = {};
  const err = this[kStateSymbol].handle.getsockname(out);
  if (err) {
    throw errnoException(err, 'getsockname');
  }
 
  return out;
};
 
Socket.prototype.remoteAddress = function() {
  healthCheck(this);
 
  const state = this[kStateSymbol];
  if (state.connectState !== CONNECT_STATE_CONNECTED)
    throw new ERR_SOCKET_DGRAM_NOT_CONNECTED();
 
  const out = {};
  const err = state.handle.getpeername(out);
  if (err)
    throw errnoException(err, 'getpeername');
 
  return out;
};
 
 
Socket.prototype.setBroadcast = function(arg) {
  const err = this[kStateSymbol].handle.setBroadcast(arg ? 1 : 0);
  if (err) {
    throw errnoException(err, 'setBroadcast');
  }
};
 
 
Socket.prototype.setTTL = function(ttl) {
  validateNumber(ttl, 'ttl');
 
  const err = this[kStateSymbol].handle.setTTL(ttl);
  if (err) {
    throw errnoException(err, 'setTTL');
  }
 
  return ttl;
};
 
 
Socket.prototype.setMulticastTTL = function(ttl) {
  validateNumber(ttl, 'ttl');
 
  const err = this[kStateSymbol].handle.setMulticastTTL(ttl);
  if (err) {
    throw errnoException(err, 'setMulticastTTL');
  }
 
  return ttl;
};
 
 
Socket.prototype.setMulticastLoopback = function(arg) {
  const err = this[kStateSymbol].handle.setMulticastLoopback(arg ? 1 : 0);
  if (err) {
    throw errnoException(err, 'setMulticastLoopback');
  }
 
  return arg; // 0.4 compatibility
};
 
 
Socket.prototype.setMulticastInterface = function(interfaceAddress) {
  healthCheck(this);
  validateString(interfaceAddress, 'interfaceAddress');
 
  const err = this[kStateSymbol].handle.setMulticastInterface(interfaceAddress);
  if (err) {
    throw errnoException(err, 'setMulticastInterface');
  }
};
 
Socket.prototype.addMembership = function(multicastAddress,
                                          interfaceAddress) {
  healthCheck(this);
 
  if (!multicastAddress) {
    throw new ERR_MISSING_ARGS('multicastAddress');
  }
 
  const { handle } = this[kStateSymbol];
  const err = handle.addMembership(multicastAddress, interfaceAddress);
  if (err) {
    throw errnoException(err, 'addMembership');
  }
};
 
 
Socket.prototype.dropMembership = function(multicastAddress,
                                           interfaceAddress) {
  healthCheck(this);
 
  if (!multicastAddress) {
    throw new ERR_MISSING_ARGS('multicastAddress');
  }
 
  const { handle } = this[kStateSymbol];
  const err = handle.dropMembership(multicastAddress, interfaceAddress);
  if (err) {
    throw errnoException(err, 'dropMembership');
  }
};
 
Socket.prototype.addSourceSpecificMembership = function(sourceAddress,
                                                        groupAddress,
                                                        interfaceAddress) {
  healthCheck(this);
 
  if (typeof sourceAddress !== 'string') {
    throw new ERR_INVALID_ARG_TYPE('sourceAddress', 'string', sourceAddress);
  }
 
  if (typeof groupAddress !== 'string') {
    throw new ERR_INVALID_ARG_TYPE('groupAddress', 'string', groupAddress);
  }
 
  const err =
    this[kStateSymbol].handle.addSourceSpecificMembership(sourceAddress,
                                                          groupAddress,
                                                          interfaceAddress);
  if (err) {
    throw errnoException(err, 'addSourceSpecificMembership');
  }
};
 
 
Socket.prototype.dropSourceSpecificMembership = function(sourceAddress,
                                                         groupAddress,
                                                         interfaceAddress) {
  healthCheck(this);
 
  if (typeof sourceAddress !== 'string') {
    throw new ERR_INVALID_ARG_TYPE('sourceAddress', 'string', sourceAddress);
  }
 
  if (typeof groupAddress !== 'string') {
    throw new ERR_INVALID_ARG_TYPE('groupAddress', 'string', groupAddress);
  }
 
  const err =
    this[kStateSymbol].handle.dropSourceSpecificMembership(sourceAddress,
                                                           groupAddress,
                                                           interfaceAddress);
  if (err) {
    throw errnoException(err, 'dropSourceSpecificMembership');
  }
};
 
 
function healthCheck(socket) {
  if (!socket[kStateSymbol].handle) {
    // Error message from dgram_legacy.js.
    throw new ERR_SOCKET_DGRAM_NOT_RUNNING();
  }
}
 
 
function stopReceiving(socket) {
  const state = socket[kStateSymbol];
 
  if (!state.receiving)
    return;
 
  state.handle.recvStop();
  state.receiving = false;
}
 
 
function onMessage(nread, handle, buf, rinfo) {
  const self = handle[owner_symbol];
  if (nread < 0) {
    return self.emit('error', errnoException(nread, 'recvmsg'));
  }
  rinfo.size = buf.length; // compatibility
  self.emit('message', buf, rinfo);
}
 
 
Socket.prototype.ref = function() {
  const handle = this[kStateSymbol].handle;
 
  if (handle)
    handle.ref();
 
  return this;
};
 
 
Socket.prototype.unref = function() {
  const handle = this[kStateSymbol].handle;
 
  if (handle)
    handle.unref();
 
  return this;
};
 
 
Socket.prototype.setRecvBufferSize = function(size) {
  bufferSize(this, size, RECV_BUFFER);
};
 
 
Socket.prototype.setSendBufferSize = function(size) {
  bufferSize(this, size, SEND_BUFFER);
};
 
 
Socket.prototype.getRecvBufferSize = function() {
  return bufferSize(this, 0, RECV_BUFFER);
};
 
 
Socket.prototype.getSendBufferSize = function() {
  return bufferSize(this, 0, SEND_BUFFER);
};
 
 
// Deprecated private APIs.
ObjectDefineProperty(Socket.prototype, '_handle', {
  get: deprecate(function() {
    return this[kStateSymbol].handle;
  }, 'Socket.prototype._handle is deprecated', 'DEP0112'),
  set: deprecate(function(val) {
    this[kStateSymbol].handle = val;
  }, 'Socket.prototype._handle is deprecated', 'DEP0112')
});
 
 
ObjectDefineProperty(Socket.prototype, '_receiving', {
  get: deprecate(function() {
    return this[kStateSymbol].receiving;
  }, 'Socket.prototype._receiving is deprecated', 'DEP0112'),
  set: deprecate(function(val) {
    this[kStateSymbol].receiving = val;
  }, 'Socket.prototype._receiving is deprecated', 'DEP0112')
});
 
 
ObjectDefineProperty(Socket.prototype, '_bindState', {
  get: deprecate(function() {
    return this[kStateSymbol].bindState;
  }, 'Socket.prototype._bindState is deprecated', 'DEP0112'),
  set: deprecate(function(val) {
    this[kStateSymbol].bindState = val;
  }, 'Socket.prototype._bindState is deprecated', 'DEP0112')
});
 
 
ObjectDefineProperty(Socket.prototype, '_queue', {
  get: deprecate(function() {
    return this[kStateSymbol].queue;
  }, 'Socket.prototype._queue is deprecated', 'DEP0112'),
  set: deprecate(function(val) {
    this[kStateSymbol].queue = val;
  }, 'Socket.prototype._queue is deprecated', 'DEP0112')
});
 
 
ObjectDefineProperty(Socket.prototype, '_reuseAddr', {
  get: deprecate(function() {
    return this[kStateSymbol].reuseAddr;
  }, 'Socket.prototype._reuseAddr is deprecated', 'DEP0112'),
  set: deprecate(function(val) {
    this[kStateSymbol].reuseAddr = val;
  }, 'Socket.prototype._reuseAddr is deprecated', 'DEP0112')
});
 
 
Socket.prototype._healthCheck = deprecate(function() {
  healthCheck(this);
}, 'Socket.prototype._healthCheck() is deprecated', 'DEP0112');
 
 
Socket.prototype._stopReceiving = deprecate(function() {
  stopReceiving(this);
}, 'Socket.prototype._stopReceiving() is deprecated', 'DEP0112');
 
 
// Legacy alias on the C++ wrapper object. This is not public API, so we may
// want to runtime-deprecate it at some point. There's no hurry, though.
ObjectDefineProperty(UDP.prototype, 'owner', {
  get() { return this[owner_symbol]; },
  set(v) { return this[owner_symbol] = v; }
});
 
 
module.exports = {
  _createSocketHandle: deprecate(
    _createSocketHandle,
    'dgram._createSocketHandle() is deprecated',
    'DEP0112'
  ),
  createSocket,
  Socket
};