All files / node-coap/lib agent.js

89.46% Statements 263/294
79.07% Branches 136/172
92.59% Functions 25/27
89.42% Lines 262/293

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                    1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x   1x 1x         104x 2x   102x 15x   102x 98x   102x 82x 82x     102x   102x     1x   1x   410x   410x 291x     119x 119x 119x       785x 785x   6x     779x   93x     686x 686x     119x 3x     119x           119x 119x 119x   119x 119x   119x 119x     1x 112x 72x   40x 23x   40x     40x     1x 40x 1x   40x 17x   23x 23x     1x 686x     686x 686x 686x 30x     30x 30x       686x 51x 34x     51x   15x     36x 9x           9x 9x 9x       662x 21x           21x 21x     662x         662x   662x                 662x   662x                                                   662x 634x       662x 132x     530x     530x 398x   398x         530x   398x 4x 4x 1x         397x   397x   385x 385x 385x     385x         385x       385x 385x 385x   385x     12x   12x       144x 24x     23x     1x       120x 12x   108x   80x     120x 21x 21x 5x 5x   21x 1x 1x 1x   1x   1x 1x     99x     120x 117x     120x     1x 304x   304x     304x 304x   304x     1x 689x 1x   689x             1x 308x       308x   308x 308x   308x     304x 272x       304x 7x 7x       304x 304x 304x 3x 1x   2x   301x   303x 303x 303x 7x       303x 303x 303x     303x 303x         303x 303x   1x 1x   302x       308x   308x   308x   308x 308x   308x 56x 56x 56x         308x 4x     308x   308x 732x     308x 8x 8x     308x 732x   725x 725x           308x 10x 1x 1x 1x 1x   1x 1x 1x           308x 2x 306x 25x   281x   308x   308x   308x     1x 9x 9x 9x 9x 9x 9x         616x 38x 86x   56x 56x 56x       1x 4x 4x 4x 4x 1x     3x 3x 3x 3x 3x 4x 7x     3x 3x 3x 3x     1x  
'use strict'
 
/*
 * Copyright (c) 2013-2021 node-coap contributors.
 *
 * node-coap is licensed under an MIT +no-false-attribs license.
 * All rights not explicitly granted in the MIT license are reserved.
 * See the included LICENSE file for more details.
 */
 
var util                  = require('util')
  , crypto                = require('crypto')
  , events                = require('events')
  , dgram                 = require('dgram')
  , parse                 = require('coap-packet').parse
  , generate              = require('coap-packet').generate
  , IncomingMessage       = require('./incoming_message')
  , OutgoingMessage       = require('./outgoing_message')
  , ObserveStream         = require('./observe_read_stream')
  , RetrySend             = require('./retry_send')
  , parseBlock2           = require('./helpers').parseBlock2
  , createBlock2          = require('./helpers').createBlock2
  , getOption             = require('./helpers').getOption
  , removeOption          = require('./helpers').removeOption
  , maxToken              = Math.pow(2, 32)
  , maxMessageId          = Math.pow(2, 16)
  , pf                    = require('./polyfill')
  , hasDNSbug             = true
  , SegmentedTransmission = require("./segmentation").SegmentedTransmission
  , parseBlockOption      = require("./block").parseBlockOption;
 
(function () {
  var major = parseInt(process.version.match(/^v([^.]+).*$/)[1])
 
  Eif (major >= 4) {
    hasDNSbug = false
  }
})()
 
function Agent(opts) {
  if (!(this instanceof Agent))
    return new Agent(opts)
 
  if (!opts)
    opts = {}
 
  if (!opts.type)
    opts.type = 'udp4'
 
  if (opts.socket) {
    opts.type = opts.socket.type
    delete opts.port
  }
 
  this._opts = opts
 
  this._init(opts.socket)
}
 
util.inherits(Agent, events.EventEmitter)
 
Agent.prototype._init = function initSock(socket) {
  
  this._closing = false
  
  if (this._sock) {
    return
  }
 
  var that = this
  this._sock = socket || dgram.createSocket(this._opts.type)
  this._sock.on('message', function(msg, rsinfo) {
    var packet
      , message
      , outSocket
    try {
      packet = parse(msg)
    } catch(err) {
      return
    }
 
    if (packet.code[0] === '0' && packet.code !== '0.00') {
      // ignore this packet since it's not a response.
      return
    }
 
    outSocket = that._sock.address()
    that._handle(msg, rsinfo, outSocket)
  })
 
  if(this._opts.port) {
    this._sock.bind( this._opts.port )
  }
 
  this._sock.on('error', function(err) {
    // we are skipping DNS errors
    if(!hasDNSbug || err.code !== 'ENOTFOUND')
      that.emit('error', err)
  })
 
  this._msgIdToReq = {}
  this._tkToReq = {}
  this._tkToMulticastResAddr = {}
 
  this._lastToken = Math.floor(Math.random() * (maxToken - 1))
  this._lastMessageId = Math.floor(Math.random() * (maxMessageId - 1))
  
  this._msgInFlight = 0
  this._requests = 0
}
 
Agent.prototype._cleanUp = function cleanUp() {
  if (--this._requests !== 0)
    return
 
  if (!this._opts.socket)
    this._closing = true
 
  Iif (this._msgInFlight !== 0)
    return
 
  this._doClose()
}
 
Agent.prototype._doClose = function() {
  for (var k in this._msgIdToReq)
    this._msgIdToReq[k].sender.reset()
 
  if (this._opts.socket)
    return
 
  this._sock.close()
  this._sock = null
}
 
Agent.prototype._handle = function handle(msg, rsinfo, outSocket) {
  var packet = parse(msg)
    , buf
    , response
    , that = this
    , req = this._msgIdToReq[packet.messageId]
    , ackSent = function(err) {
        Iif (err && req)
          req.emit('error', err)
 
        that._msgInFlight--
        Iif (that._closing && that._msgInFlight === 0) {
          that._doClose()
        }
      }
  if (!req) {
    if (packet.token.length > 0) {
      req = this._tkToReq[packet.token.toString('hex')]
    }
 
    if ((packet.ack || packet.reset) && !req) {
      // Nothing to do on unknown or duplicate ACK/RST packet
      return
    }
 
    if (!req) {
      buf = generate({
          code: '0.00'
        , reset: true
        , messageId: packet.messageId
      })
 
      this._msgInFlight++
      this._sock.send(buf, 0, buf.length, rsinfo.port, rsinfo.address, ackSent)
      return
    }
  }
 
  if (packet.confirmable) {
    buf = generate({
        code: '0.00'
      , ack: true
      , messageId: packet.messageId
    })
 
    this._msgInFlight++
    this._sock.send(buf, 0, buf.length, rsinfo.port, rsinfo.address, ackSent)
  }
 
  Iif (packet.code != '0.00' && (req._packet.token.length != packet.token.length || pf.compareBuffers(req._packet.token, packet.token) != 0)) {
    // The tokens don't match, ignore the message since it is a malformed response
    return
  }
 
  var block1Buff = getOption(packet.options, 'Block1')
  var block1
  Iif(block1Buff) {
    block1 = parseBlockOption(block1Buff)
    // check for error
    if (!block1) {
      req.sender.reset()
      return req.emit('error', new Error('Failed to parse block1'))
    }
  }
 
  req.sender.reset()
 
  Iif(block1 && packet.ack) {
    // var initialRequest = this._msgIdToReq[packet.messageId];
    //If the client takes too long to respond then the retry sender will send
    // another packet with the previous messageId, which we've already removed.
    var segmentedSender = req.segmentedSender
    if(segmentedSender) {
 
      //If there's more to send/receive, then carry on!
      if(segmentedSender.remaining() > 0) {
        if(segmentedSender.isCorrectACK(packet, block1)) {
          delete this._msgIdToReq[req._packet.messageId]
          req._packet.messageId = that._nextMessageId()
          this._msgIdToReq[req._packet.messageId] = req
          segmentedSender.receiveACK(packet, block1)
        } else {
          segmentedSender.resendPreviousPacket()
        }
        return
      } else {
        // console.log("Packet received done");
        removeOption(req._packet.options, "Block1")
        delete req.segmentedSender
      }
    }
  }
 
  if (!packet.confirmable && !req.multicast) {
    delete this._msgIdToReq[packet.messageId]
  }
 
  // Drop empty messages (ACKs), but process RST
  if (packet.code == '0.00' && !packet.reset) {
    return
  }
 
  var block2Buff = getOption(packet.options, 'Block2')
  var block2
  // if we got blockwise (2) response
  if (block2Buff) {
    block2 = parseBlock2(block2Buff)
    // check for error
    Iif (!block2) {
      req.sender.reset()
      return req.emit('error', new Error('failed to parse block2'))
    }
  }
  if (block2) {
 
    if (req.multicast) {
      req = this._convertMulticastToUnicastRequest(req, rsinfo)
      if (!req) {
        return
      }
    }
 
    // accumulate payload
    req._totalPayload = Buffer.concat([req._totalPayload, packet.payload])
 
    if (block2.moreBlock2) {
      // increase message id for next request
      delete this._msgIdToReq[req._packet.messageId]
      req._packet.messageId = that._nextMessageId()
      this._msgIdToReq[req._packet.messageId] = req
 
      // next block2 request
      var block2Val = createBlock2({
        moreBlock2: false,
        num: block2.num+1,
        size: block2.size
      })
      Iif (!block2Val) {
        req.sender.reset()
        return req.emit('error', new Error('failed to create block2'))
      }
      req.setOption('Block2', block2Val)
      req._packet.payload = null
      req.sender.send(generate(req._packet))
 
      return
    } else {
      // get full payload
      packet.payload = req._totalPayload
      // clear the payload incase of block2
      req._totalPayload = Buffer.alloc(0)
    }
  }
 
  if (req.response) {
    if (req.response.append) {
      // it is an observe request
      // and we are already streaming
      return req.response.append(packet)
    } else {
      // TODO There is a previous response but is not an ObserveStream !
      return
    }
 
  }
  else if (block2) {
    delete that._tkToReq[req._packet.token.toString('hex')]
  }
  else if (!req.url.observe && !req.multicast) {
    // it is not, so delete the token
    delete that._tkToReq[packet.token.toString('hex')]
  }
 
  if (req.url.observe && packet.code !== '4.04') {
    response = new ObserveStream(packet, rsinfo, outSocket)
    response.on('close', function() {
      delete that._tkToReq[packet.token.toString('hex')]
      that._cleanUp()
    })
    response.on('deregister', function() {
      var deregister_url = Object.assign({}, req.url)
      deregister_url.observe = 1
      deregister_url.token = req._packet.token
 
      let deregister_req = that.request(deregister_url)
      // If the request fails, we'll deal with it with a RST message anyway.
      deregister_req.on('error', function() {})
      deregister_req.end()
    })
  } else {
      response = new IncomingMessage(packet, rsinfo, outSocket)
  }
 
  if (!req.multicast) {
    req.response = response
  }
 
  req.emit('response', response)
}
 
Agent.prototype._nextToken = function nextToken() {
  var buf = Buffer.alloc(8)
 
  Iif (++this._lastToken === maxToken)
    this._lastToken = 0
 
  buf.writeUInt32BE(this._lastToken, 0)
  crypto.randomBytes(4).copy(buf, 4)
 
  return buf
}
 
Agent.prototype._nextMessageId = function nextToken() {
  if (++this._lastMessageId === maxMessageId)
    this._lastMessageId = 1
 
  return this._lastMessageId
}
 
/**
 * Entry point for a new client-side request.
 * @param {*} url A String representing a CoAP URL, or an object with the appropriate parameters. 
 */
Agent.prototype.request = function request(url) {
  this._init()
  
  var req
    , response
    , options = url.options || url.headers
    , option
    , that = this
    , multicastTimeout = url.multicastTimeout !== undefined ? parseInt(url.multicastTimeout) : 20000
 
  req = new OutgoingMessage({}, function(req, packet) {
    var buf
 
    if (url.confirmable !== false) {
      packet.confirmable = true
    }
 
    // multicast message should be forced non-confirmable
    if (url.multicast === true) {
      req.multicast = true
      packet.confirmable = false
    }
 
    var token
    Eif (!(packet.ack || packet.reset)) {
      packet.messageId = that._nextMessageId()
      if ((url.token instanceof Buffer) && (url.token.length > 0)) {
        if (url.token.length > 8) {
          return req.emit('error', new Error('Token may be no longer than 8 bytes.'))
        }
        packet.token = url.token
      } else {
        packet.token = that._nextToken()
      }
      token = packet.token.toString('hex')
      that._tkToMulticastResAddr[token] = []
      if (req.multicast) {
        that._tkToMulticastResAddr[token] = []
      }
    }
 
    that._msgIdToReq[packet.messageId] = req
    Eif (token) {
      that._tkToReq[token] = req
    }
 
    var block1Buff = getOption(packet.options, 'Block1')
    Iif(block1Buff) {
      // Setup for a segmented transmission
      req.segmentedSender = new SegmentedTransmission(block1Buff[0], req, packet)
      req.segmentedSender.sendNext()
    } else {
      try {
        buf = generate(packet)
      } catch(err) {
        req.sender.reset()
        return req.emit('error', err)
      }
      req.sender.send(buf, !packet.confirmable)
    }
  })
 
  req.sender = new RetrySend(this._sock, url.port, url.hostname || url.host, url.retrySend)
 
  req.url = url
 
  req.statusCode = url.method || 'GET'
 
  urlPropertyToPacketOption(url, req, 'pathname', 'Uri-Path', '/')
  urlPropertyToPacketOption(url, req, 'query', 'Uri-Query', '&')
 
  if (options) {
    for (option in options) {
      Eif (options.hasOwnProperty(option)) {
        req.setOption(option, options[option])
      }
    }
  }
 
  if (url.proxyUri) {
    req.setOption('Proxy-Uri', url.proxyUri)
  }
 
  req.sender.on('error', req.emit.bind(req, 'error'))
 
  req.sender.on('sending', function() {
    that._msgInFlight++
  })
 
  req.sender.on('timeout', function (err) {
    req.emit('timeout', err)
    that.abort(req)
  })
 
  req.sender.on('sent', function() {
    if (req.multicast) return
 
    that._msgInFlight--
    Iif (that._closing && that._msgInFlight === 0) {
      that._doClose()
    }
  })
 
  // Start multicast monitoring timer in case of multicast request
  if (url.multicast === true) {
    req.multicastTimer = setTimeout(function() {
      Eif (req._packet.token) {
        var token = req._packet.token.toString('hex')
        delete that._tkToReq[token]
        delete that._tkToMulticastResAddr[token]
      }
      delete that._msgIdToReq[req._packet.messageId]
      that._msgInFlight--
      Iif (that._msgInFlight === 0 && that._closing) {
        that._doClose()
      }
    }, multicastTimeout)
  }
 
  if (typeof (url.observe) === "number")
    req.setOption('Observe', url.observe)
  else if (url.observe)
    req.setOption('Observe', null)
  else
    req.on('response', this._cleanUp.bind(this))
 
  this._requests++
 
  req._totalPayload = Buffer.alloc(0)
 
  return req
}
 
Agent.prototype.abort = function (req) {
  req.sender.removeAllListeners()
  req.sender.reset()
  this._cleanUp()
  delete this._msgIdToReq[req._packet.messageId]
  Eif (req._packet.token) {
    delete this._tkToReq[req._packet.token.toString('hex')]
  }
}
 
function urlPropertyToPacketOption(url, req, property, option, separator) {
  if (url[property])
    req.setOption(option, url[property].normalize('NFC').split(separator)
      .filter(function(part) { return part !== '' })
      .map(function(part) {
        var buf = Buffer.alloc(Buffer.byteLength(part))
        buf.write(part)
        return buf
      }))
}
 
Agent.prototype._convertMulticastToUnicastRequest = function (req, rsinfo) {
  var unicastReq = this.request(req.url)
  var unicastAddress = rsinfo.address.split('%')[0]
  var token = req._packet.token.toString('hex')
  if (this._tkToMulticastResAddr[token].includes(unicastAddress)) {
    return null
  }
 
  unicastReq.url.host = unicastAddress
  unicastReq.sender._host = unicastAddress
  clearTimeout(unicastReq.multicastTimer)
  unicastReq.url.multicast = false
  req.eventNames().forEach(eventName => {
    req.listeners(eventName).forEach(listener => {
      unicastReq.on(eventName, listener)
    })
  })
  this._tkToMulticastResAddr[token].push(unicastAddress)
  unicastReq._packet.token = this._nextToken()
  this._requests++
  return unicastReq
}
 
module.exports = Agent