All files / node-coap/lib server.js

86.13% Statements 267/310
85.06% Branches 148/174
90.63% Functions 29/32
86.27% Lines 264/306

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                    1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     820x 820x 5x         620x 310x     310x 6x 6x     310x 286x   310x 310x   310x       310x 10x 10x     310x 2x   308x 2139x       310x 309x     310x 305x   310x     310x 310x               310x   310x       310x   661x     564x 564x       310x   310x 1x   310x 1x     310x 7x 310x     1x   1x 8x             8x       7x   7x 11x 4x       7x   7x     1x 7x 7x 7x 7x   7x     1x 9x 9x 9x   9x       304x 820x         820x   820x 1692x     820x         1x 1x     1x 1x 1x 8x 8x 11x 2x         1x     1x 305x   305x 2x     305x 1x 1x     305x 290x 290x     305x 1x 1x       1x     304x 1x   304x 301x   304x 7x 7x   297x 297x   297x 297x 297x 1x   1x     1x 2x                     297x 290x       304x   304x       304x   304x 3x   304x 304x       304x     1x 209x 83x     209x 203x     209x 198x 194x   198x 198x 198x   11x     209x 209x   209x               1x   811x             34x     777x 777x 777x 777x 777x 777x     777x 2x 775x 69x 1x   69x 706x 9x       697x 24x 24x   3x     694x   694x 694x 694x   661x   661x 661x       661x 626x   35x 35x 1x       661x   661x 661x   661x 660x   1x       694x 694x 694x     694x   694x     694x 694x   694x   642x   642x 411x   642x 232x     642x 238x       404x 404x 394x 394x 394x           300x 300x                                                                                                       300x     1x 694x 642x     52x     1x 1507x   1507x 1420x   1507x                 673x   1x     1x 1x             1x 493x         493x     493x 411x   411x 1x 1x         492x   76x     416x 6x           416x       416x 416x   1x 1x     415x   415x         415x           415x 415x     415x 415x   415x                   415x 415x 415x 623804x 623804x 623804x   415x     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.
 */
 
require('./polyfill')
 
var dgram            = require('dgram')
  , os               = require('os')
  , net              = require('net')
  , util             = require('util')
  , series           = require('fastseries')
  , events           = require('events')
  , LRU              = require('lru-cache')
  , generate         = require('coap-packet').generate
  , IncomingMessage  = require('./incoming_message')
  , OutgoingMessage  = require('./outgoing_message')
  , ObserveStream    = require('./observe_write_stream')
  , parameters       = require('./parameters')
  , RetrySend        = require('./retry_send')
  , parseBlock2      = require('./helpers').parseBlock2
  , createBlock2     = require('./helpers').createBlock2
  , getOption        = require('./helpers').getOption
  , isNumeric        = require('./helpers').isNumeric
  , isBoolean        = require('./helpers').isBoolean
  , middlewares      = require('./middlewares')
  , debug            = require('debug')('CoAP Server')
  , parseBlockOption = require('./block').parseBlockOption
  , BlockCache       = require('./cache')
 
function handleEnding(err) {
  var request = this
  if (err) {
    request.server._sendError(Buffer.from(err.message), request.rsinfo, request.packet)
  }
}
 
function CoAPServer(options, listener) {
  if (!(this instanceof CoAPServer)) {
    return new CoAPServer(options, listener)
  }
 
  if (typeof options === 'function') {
    listener = options
    options = null
  }
 
  if (!options)
    options = {}
 
  this._options = options
  this._proxiedRequests = {}
 
  this._middlewares = [
    middlewares.parseRequest
  ]
 
  if (options.proxy) {
    this._middlewares.push(middlewares.proxyRequest)
    this._middlewares.push(middlewares.handleProxyResponse)
  }
 
  if (typeof options.clientIdentifier === 'function') {
    this._clientIdentifier = options.clientIdentifier
  } else {
    this._clientIdentifier = (request) => {
      return `${request.rsinfo.address}:${request.rsinfo.port}`
    }    
  }
 
  if (!this._options.piggybackReplyMs || !isNumeric(this._options.piggybackReplyMs)) {
    this._options.piggybackReplyMs = parameters.piggybackReplyMs
  }
 
  if (!isBoolean(this._options.sendAcksForNonConfirmablePackets)) {
    this._options.sendAcksForNonConfirmablePackets = parameters.sendAcksForNonConfirmablePackets
  }
  this._middlewares.push(middlewares.handleServerRequest)
 
  // Multicast settings
  this._multicastAddress = options.multicastAddress ? options.multicastAddress : null
  this._multicastInterface = options.multicastInterface ? options.multicastInterface : null
 
  // We use an LRU cache for the responses to avoid
  // DDOS problems.
  // max packet size is 1280
  // 32 MB / 1280 = 26214
  // The max lifetime is roughly 200s per packet.
  // Which gave us 131 packets/second guarantee
  let max = 32768 * 1024
 
  Iif (typeof options.cacheSize === 'number' && options.cacheSize >= 0) {
    max = options.cacheSize
  }
 
  this._lru = new LRU({
      max
    , length: function(n) { return n.buffer.byteLength }
    , maxAge: (parameters.exchangeLifetime * 1000)
    , dispose:  function(key, value) {
                  Eif (value.sender)
                    value.sender.reset()
                }
  })
  
  this._series = series()
  
  this._block1Cache = new BlockCache(parameters.exchangeLifetime * 1000, () => {
    return {}
  })
  this._block2Cache = new BlockCache(parameters.exchangeLifetime * 1000, () => {
    return null
  })
 
  if (listener)
    this.on('request', listener)
  debug('initialized')
}
 
util.inherits(CoAPServer, events.EventEmitter)
 
CoAPServer.prototype._sendError = function(payload, rsinfo, packet) {
  var message = generate({
    code: '5.00',
    payload: payload,
    messageId: (packet)?packet.messageId:undefined,
    token: (packet)?packet.token:undefined
  })
 
  this._sock.send(message, 0, message.length, rsinfo.port)
}
 
function removeProxyOptions(packet) {
  var cleanOptions = []
 
  for (var i = 0; i < packet.options.length; i++) {
    if (packet.options[i].name.toLowerCase() !== 'proxy-uri' && packet.options[i].name.toLowerCase() !== 'proxy-scheme') {
      cleanOptions.push(packet.options[i])
    }
  }
 
  packet.options = cleanOptions
 
  return packet
}
 
CoAPServer.prototype._sendProxied = function(packet, proxyUri, callback) {
  var url = require('url').parse(proxyUri)
    , host = url.hostname
    , port = url.port
    , message = generate(removeProxyOptions(packet))
 
  this._sock.send(message, 0, message.length, port, host, callback)
}
 
CoAPServer.prototype._sendReverseProxied = function(packet, rsinfo, callback) {
  var host = rsinfo.address
    , port = rsinfo.port
    , message = generate(packet)
 
  this._sock.send(message, 0, message.length, port, host, callback)
}
 
function handleRequest(server) {
  return function (msg, rsinfo) {
    var request = {
        raw: msg,
        rsinfo: rsinfo,
        server: server
      }
      , activeMiddlewares = []
 
    for (var i = 0; i < server._middlewares.length; i++) {
      activeMiddlewares.push(server._middlewares[i])
    }
 
    server._series(request, activeMiddlewares, request, handleEnding)
  }
}
 
function allAddresses(type) {
    var family = 'IPv4'
    Iif (type === 'udp6') {
        family = 'IPv6'
    }
    var addresses = []
    var interfaces = os.networkInterfaces()
    for (var ifname in interfaces)  {
        Eif (interfaces.hasOwnProperty(ifname)) {
            interfaces[ifname].forEach(function (a) {
                if (a.family == family) {
                    addresses.push(a.address)
                }
            })
        }
    }
    return addresses
}
 
CoAPServer.prototype.listen = function(port, address, done) {
  var that = this
 
  if (port == undefined) {
    port = parameters.coapPort
  }
 
  if (typeof port === 'function') {
    done = port
    port = parameters.coapPort
  }
 
  if (typeof address === 'function') {
    done = address
    address = null
  }
 
  if (this._sock) {
    Eif (done)
      done(new Error('Already listening'))
    else
      throw new Error('Already listening')
 
    return this
  }
 
  if (address && net.isIPv6(address))
    this._options.type = 'udp6'
 
  if (!this._options.type)
    this._options.type = 'udp4'
 
  if (port instanceof events.EventEmitter) {
    this._sock = port
    if (done) setImmediate(done)
  } else {
    this._internal_socket = true
    this._sock = dgram.createSocket({type: this._options.type, reuseAddr : true})
 
    this._sock.bind(port, address || null, function () {
      try {
        if (that._multicastAddress) {
          that._sock.setMulticastLoopback(true)
 
          Iif (that._multicastInterface) {
            that._sock.addMembership(that._multicastAddress, that._multicastInterface)
          } else {
            allAddresses(that._options.type).forEach(function(_interface) {
              that._sock.addMembership(that._multicastAddress, _interface)
            })
          }
        }
      } catch (err) {
        if (done)
          return done(err)
        else
          throw err
      }
 
      if (done)
        return done()
    })
  }
 
  this._sock.on('message', handleRequest(this))
 
  this._sock.on('error', function(error) {
    that.emit('error', error)
  })
 
  Eif (parameters.pruneTimerPeriod) {
    // Start LRU pruning timer
    this._lru.pruneTimer = setInterval(function () {
      that._lru.prune()
    }, parameters.pruneTimerPeriod*1000)
    Eif (this._lru.pruneTimer.unref) {
      this._lru.pruneTimer.unref()
    }
  }
 
  return this
}
 
CoAPServer.prototype.close = function(done) {
  if (done) {
    setImmediate(done)
  }
 
  if (this._lru.pruneTimer) {
    clearInterval(this._lru.pruneTimer)
  }
 
  if (this._sock) {
    if (this._internal_socket) {
      this._sock.close()
    }
    this._lru.reset()
    this._sock = null
    this.emit('close')
  } else {
    this._lru.reset()
  }
 
  this._block2Cache.reset()
  this._block1Cache.reset()
 
  return this
}
 
/**
 * Entry point for a new datagram from the client.
 * @param {Packet} packet The packet that was sent from the client.
 * @param {Object} rsinfo Connection info 
 */
CoAPServer.prototype._handle = function(packet, rsinfo) {
 
  if (packet.code[0] !== '0') {
    // According to RFC7252 Section 4.2 receiving a confirmable messages
    // that can't be processed, should be rejected by ignoring it AND
    // sending a reset. In this case confirmable response message would
    // be silently ignored, which is not exactly as stated in the standard.
    // However, sending a reset would interfere with a coap client which is
    // re-using a socket (see pull-request #131).
    return
  }
 
  var sock      = this._sock
    , lru       = this._lru
    , Message   = OutMessage
    , that = this
    , request   = new IncomingMessage(packet, rsinfo)
    , cached    = lru.peek(this._toKey(request, packet, true))
    , response
 
  if (cached && !packet.ack && !packet.reset) {
    return sock.send(cached, 0, cached.length, rsinfo.port, rsinfo.address)
  } else if (cached && (packet.ack || packet.reset)) {
    if (cached.response && packet.reset) {
      cached.response.end()
    }
    return lru.del(this._toKey(request, packet, false))
  } else if (packet.ack || packet.reset) {
    return // nothing to do, ignoring silently
  }
 
 
  if (request.headers['Observe'] === 0) {
    Message = ObserveStream
    if (packet.code !== '0.01')
      // it is not a GET
      return this._sendError(Buffer.from('Observe can only be present with a GET'), rsinfo)
  }
 
  var cache_key = this._toCacheKey(request, packet)
 
  packet.piggybackReplyMs = this._options.piggybackReplyMs
  var generateResponse = function() {
    var response = new Message(packet, function(response, packet) {
      var buf
        , sender = new RetrySend(sock, rsinfo.port, rsinfo.address)
 
      try {
        buf = generate(packet)
      } catch(err) {
        return response.emit('error', err)
      }
      if (Message === OutMessage) {
        sender.on('error', response.emit.bind(response, 'error'))
      } else {
        buf.response = response
        sender.on('error', function() {
          response.end()
        })
      }
  
      var key = that._toKey(request, 
          packet, packet.ack || !packet.confirmable)
      lru.set(key, buf)
      buf.sender = sender
  
      if (that._options.sendAcksForNonConfirmablePackets || packet.confirmable) {
        sender.send(buf, packet.ack || packet.reset || packet.confirmable === false)
      } else {
        debug('OMIT ACK PACKAGE')
      }
    })
  
    response.statusCode = '2.05'
    response._request = request._packet
    response._cachekey = cache_key
 
    //inject this function so the response can add an entry to the cache
    response._addCacheEntry = that._block2Cache.add.bind(that._block2Cache)
 
    return response
  }
 
  response = generateResponse()
  request.rsinfo = rsinfo
  
  if (packet.token && packet.token.length > 0) {
    // return cached value only if this request is not the first block request
    var block2Buff = getOption(packet.options, 'Block2')
    var requestedBlockOption
    if (block2Buff) {
      requestedBlockOption = parseBlock2(block2Buff)
    }
    if (!requestedBlockOption) {
      requestedBlockOption = {num: 0}
    }
 
    if (requestedBlockOption.num < 1) {
      Iif(this._block2Cache.remove(cache_key)) {
        debug('first block2 request, removed old entry from cache')
      }
    } else {
      debug('check if packet token is in cache, key:', cache_key)
      if (this._block2Cache.contains(cache_key)) {
        debug('found cached payload, key:', cache_key)
        response.end(this._block2Cache.get(cache_key))
        return
      }
    }
  }
  // else goes here?
  {
    var block1Buff = getOption(packet.options, 'Block1')
    Iif(block1Buff) {
      var blockState = parseBlockOption(block1Buff)
 
      if(blockState) {
        /** @type {{[k:string]:Buffer}} */
        let cachedData = this._block1Cache.getWithDefaultInsert(cache_key)
        var blockByteSize = Math.pow(2, 4 + blockState.blockSize)
        var incomingByteIndex = blockState.sequenceNumber * blockByteSize
        // Store in the cache object, use the byte index as the key
        cachedData[incomingByteIndex] = request.payload
  
        if(!blockState.moreBlocks) {
          // Last block
          var byteOffsets = Object.keys(cachedData)
            .map((str) => {
              return parseInt(str)
            }).sort((a, b) => {
              return a - b
            })
          var byteTotalSum = incomingByteIndex + request.payload.length
          var next = 0
          var concat = Buffer.alloc(byteTotalSum)
          for(var i = 0; i < byteOffsets.length; i++) {
            if(byteOffsets[i] == next) {
              var buff = cachedData[byteOffsets[i]]
              buff.copy(concat, next, 0, buff.length)
              next += buff.length
            } else {
              throw new Error("Byte offset not the next in line...")
            }
          }
          
          this._block1Cache.remove(cache_key)
 
          if(next == concat.length) {
            request.payload = concat
          } else {
            throw new Error("Last byte index is not equal to the concat buffer length!")
          }
        } else {
          // More blocks to come. ACK this block
          response.code = "2.31"
          response.setOption("Block1", block1Buff)
          response.end()
          return
        }
      } else {
        throw new Error("Invalid block state" + blockState)
      }
    }
  }
 
  this.emit('request', request, response)
}
 
CoAPServer.prototype._toCacheKey = function toCacheKey(request, packet) {
  if (packet.token && packet.token.length > 0) {
    return `${packet.token.toString('hex')}/${this._clientIdentifier(request)}`
  }
 
  return null
}
 
CoAPServer.prototype._toKey = function toKey(request, packet, appendToken) {
  var result = `${this._clientIdentifier(request)}/${packet.messageId}`
 
  if (appendToken)
    result += packet.token.toString('hex')
 
  return result
}
 
/*
new out message
inherit from OutgoingMessage
to handle cached answer and blockwise (2)
*/
function OutMessage() {
  OutgoingMessage.apply(this, Array.prototype.slice.call(arguments))
}
util.inherits(OutMessage, OutgoingMessage)
 
// maxBlock2 is in formular 2**(i+4), and must <= 2**(6+4)
var maxBlock2 = Math.pow(2, Math.floor(Math.log(parameters.maxPacketSize)/Math.log(2)))
Iif (maxBlock2 > Math.pow(2, (6+4)))
  maxBlock2 = Math.pow(2, (6+4))
 
/**
 * Entry point for a response from the server
 * @param {Buffer} payload A buffer-like object containing data to send back to the client.
 */
OutMessage.prototype.end = function(payload) {
  var that = this
  
  // removeOption(this._request.options, 'Block1'); 
  // add logic for Block1 sending
 
  var block2Buff = getOption(this._request.options, 'Block2')
  var requestedBlockOption
  // if we got blockwise (2) request
  if (block2Buff) {
    requestedBlockOption = parseBlock2(block2Buff)
    // bad option
    if (!requestedBlockOption) {
      that.statusCode = '4.02'
      return OutgoingMessage.prototype.end.call(that)
    }
  }
 
  // if payload is suitable for ONE message, shoot it out
  if (!payload ||
    ((!requestedBlockOption) && (payload.length < parameters.maxPacketSize)))
    return OutgoingMessage.prototype.end.call(this, payload)
 
  // for the first request, block2 option may be missed
  if (!requestedBlockOption)
    requestedBlockOption = {
      size: maxBlock2,
      num: 0
    }
 
  // block2 size should not bigger than maxBlock2
  Iif (requestedBlockOption.size > maxBlock2)
    requestedBlockOption.size = maxBlock2
 
  // block number should have limit
  var lastBlockNum = Math.ceil(payload.length/requestedBlockOption.size) - 1
  if (requestedBlockOption.num > lastBlockNum) {
    // precondition fail, may request for out of range block
    that.statusCode = '4.02'
    return OutgoingMessage.prototype.end.call(that)
  }
  // check if requested block is the last
  var moreFlag = requestedBlockOption.num < lastBlockNum
  
  var block2 = createBlock2({
    moreBlock2: moreFlag,
    num: requestedBlockOption.num,
    size: requestedBlockOption.size
  })
  Iif (!block2) {
    // this catch never be match,
    // since we're gentleman, just handle it
    that.statusCode = '4.02'
    return OutgoingMessage.prototype.end.call(that)
  }
  this.setOption('Block2', block2)
  this.setOption('ETag', _toETag(payload))
 
  // cache it
  Eif (this._request.token && this._request.token.length > 0) {
    this._addCacheEntry(this._cachekey, payload)
  }
  OutgoingMessage.prototype.end.call(this, payload.slice((requestedBlockOption.num)*requestedBlockOption.size, (requestedBlockOption.num+1)*requestedBlockOption.size))
}
 
/*
calculate id of a payload by xor each 2-byte-block from it
use to generate etag
  payload         an input buffer, represent payload need to generate id (hash)
  id              return var, is a buffer(2)
*/
function _toETag(payload) {
  var id = Buffer.of(0, 0)
  var i = 0
  do {
    id[0] ^= payload[i]
    id[1] ^= payload[i+1]
    i += 2
  } while (i<payload.length)
  return id
}
 
module.exports = CoAPServer