All files / tar/lib unpack.js

100% Statements 201/201
100% Branches 159/159
100% Functions 40/40
100% Lines 191/191
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    3x 3x 3x 3x 3x 3x 3x   3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x       106x 106x 4x   106x 106x 106x 94x 94x     106x   106x 102x   4x     106x     106x     106x         106x       106x   106x 106x 106x   106x 106x 492x       415x 84x       492x 136x 136x 9x 127x     483x 467x 467x 2x 2x   465x 2x 2x 2x       481x 2x   479x   481x       492x 11x   481x   481x               475x         6x                   19x 19x 19x       397x                   195x 195x 195x 195x 194x 184x 194x 2x 2x   194x   195x       87x 87x 87x 3x 84x 73x 84x 2x 2x   84x 84x         6x 6x       21x       19x       310x       321x 321x       4x 4x         310x 310x 310x 4x 306x 306x 2x 304x 284x 20x 14x 9x 7x   2x   5x   6x           463x 1x   462x       269x     19x     21x       153x                     21x 21x 1x 20x 20x             47x       165x 165x 3x 162x 162x 17x 2x 15x 2x   13x 13x 6x 3x 2x   3x   7x 12x   1x       145x         74x 74x 74x 73x 73x 67x 58x 58x     67x 2x 2x     67x   1x       66x 66x 66x 1x 65x 56x 56x     65x 2x 2x     65x       231x 231x               2x         19x 19x 17x   2x         3x 3x  
'use strict'
 
const assert = require('assert')
const EE = require('events').EventEmitter
const Parser = require('./parse.js')
const fs = require('fs')
const path = require('path')
const mkdir = require('./mkdir.js')
const mkdirSync = mkdir.sync
 
const ONENTRY = Symbol('onEntry')
const CHECKFS = Symbol('checkFs')
const MAKEFS = Symbol('makeFs')
const FILE = Symbol('file')
const DIRECTORY = Symbol('directory')
const LINK = Symbol('link')
const SYMLINK = Symbol('symlink')
const HARDLINK = Symbol('hardlink')
const UNSUPPORTED = Symbol('unsupported')
const UNKNOWN = Symbol('unknown')
const CHECKPATH = Symbol('checkPath')
const MKDIR = Symbol('mkdir')
const ONERROR = Symbol('onError')
const PENDING = Symbol('pending')
const PEND = Symbol('pend')
const UNPEND = Symbol('unpend')
const ENDED = Symbol('ended')
const MAYBECLOSE = Symbol('maybeClose')
const SKIP = Symbol('skip')
 
class Unpack extends Parser {
  constructor (opt) {
    super(opt)
    if (!opt)
      opt = {}
 
    this[PENDING] = 0
    this[ENDED] = false
    this.on('end', _ => {
      this[ENDED] = true
      this[MAYBECLOSE]()
    })
 
    this.dirCache = opt.dirCache || new Map()
 
    if (opt.preserveOwner === undefined)
      this.preserveOwner = process.getuid && process.getuid() === 0
    else
      this.preserveOwner = !!opt.preserveOwner
 
    // do not unpack over files that are newer than what's in the archive
    this.newer = !!opt.newer
 
    // do not unpack over ANY files
    this.keep = !!opt.keep
 
    // do not set mtime/atime of extracted entries
    this.noMtime = !!opt.noMtime
 
    // allow .., absolute path entries, and unpacking through symlinks
    // without this, warn and skip .., relativize absolutes, and error
    // on symlinks in extraction path
    this.preservePaths = !!opt.preservePaths
 
    // unlink files and links before writing. This breaks existing hard
    // links, and removes symlink directories rather than erroring
    this.unlink = !!opt.unlink
 
    this.cwd = path.resolve(opt.cwd || process.cwd())
    this.strip = +opt.strip || 0
    this.umask = typeof opt.umask === 'number' ? opt.umask : process.umask()
    // default mode for dirs created as parents
    this.dmode = opt.dmode || (0o0777 & (~this.umask))
    this.fmode = opt.fmode || (0o0666 & (~this.umask))
    this.on('entry', entry => this[ONENTRY](entry))
  }
 
  [MAYBECLOSE] () {
    if (this[ENDED] && this[PENDING] === 0)
      this.emit('close')
  }
 
  [CHECKPATH] (entry) {
    if (this.strip) {
      const parts = entry.path.split(/\/|\\/)
      if (parts.length < this.strip)
        return false
      entry.path = parts.slice(this.strip).join('/')
    }
 
    if (!this.preservePaths) {
      const p = entry.path
      if (p.match(/(^|\/|\\)\.\.(\\|\/|$)/)) {
        this.warn('path contains \'..\'', p)
        return false
      }
      if (path.isAbsolute(p)) {
        const parsed = path.parse(p)
        this.warn('stripping ' + parsed.root + ' from absolute path', p)
        entry.path = p.substr(parsed.root.length)
      }
    }
 
    if (path.isAbsolute(entry.path))
      entry.absolute = entry.path
    else
      entry.absolute = path.resolve(this.cwd, entry.path)
 
    return true
  }
 
  [ONENTRY] (entry) {
    if (!this[CHECKPATH](entry))
      return entry.resume()
 
    assert.equal(typeof entry.absolute, 'string')
 
    switch (entry.type) {
      case 'File':
      case 'OldFile':
      case 'ContiguousFile':
      case 'Link':
      case 'SymbolicLink':
      case 'Directory':
      case 'GNUDumpDir':
        return this[CHECKFS](entry)
 
      case 'CharacterDevice':
      case 'BlockDevice':
      case 'FIFO':
        return this[UNSUPPORTED](entry)
 
      // this should be impossible
      /* istanbul ignore next */
      default:
        return this.emit('error', new Error('unknown type: ' + entry.type))
    }
  }
 
  [ONERROR] (er, entry) {
    this.warn(er.message, er)
    this[UNPEND]()
    entry.resume()
  }
 
  [MKDIR] (dir, mode, cb) {
    mkdir(dir, {
      preserve: this.preservePaths,
      unlink: this.unlink,
      cache: this.dirCache,
      cwd: this.cwd,
      mode: mode
    }, cb)
  }
 
  [FILE] (entry) {
    const mode = entry.mode & 0o7777 || this.fmode
    const stream = fs.createWriteStream(entry.absolute, { mode: mode })
    stream.on('error', er => this[ONERROR](er, entry))
    stream.on('close', _ => {
      if (entry.mtime && !this.noMtime)
        fs.utimes(entry.absolute, entry.atime || new Date(), entry.mtime, _ => _)
      if (entry.uid && this.preserveOwner)
        fs.chown(
          entry.absolute, entry.uid, entry.gid || process.getgid(), _ => _
        )
      this[UNPEND]()
    })
    entry.pipe(stream)
  }
 
  [DIRECTORY] (entry) {
    const mode = entry.mode & 0o7777 || this.dmode
    this[MKDIR](entry.absolute, mode, er => {
      if (er)
        return this[ONERROR](er, entry)
      if (entry.mtime && !this.noMtime)
        fs.utimes(entry.absolute, entry.atime || new Date(), entry.mtime, _ => _)
      if (entry.uid && this.preserveOwner)
        fs.chown(
          entry.absolute, entry.uid, entry.gid || process.getgid(), _ => _
        )
      this[UNPEND]()
      entry.resume()
    })
  }
 
  [UNSUPPORTED] (entry) {
    this.warn('unsupported entry type: ' + entry.type, entry)
    entry.resume()
  }
 
  [SYMLINK] (entry) {
    this[LINK](entry, entry.linkpath, 'symlink')
  }
 
  [HARDLINK] (entry) {
    this[LINK](entry, path.resolve(this.cwd, entry.linkpath), 'link')
  }
 
  [PEND] () {
    this[PENDING]++
  }
 
  [UNPEND] () {
    this[PENDING]--
    this[MAYBECLOSE]()
  }
 
  [SKIP] (entry) {
    this[UNPEND]()
    entry.resume()
  }
 
  // check if a thing is there, and if so, try to clobber it
  [CHECKFS] (entry) {
    this[PEND]()
    this[MKDIR](path.dirname(entry.absolute), this.dmode, er => {
      if (er)
        return this[ONERROR](er, entry)
      fs.lstat(entry.absolute, (er, st) => {
        if (st && (this.keep || this.newer && st.mtime > entry.mtime))
          this[SKIP](entry)
        else if (er || (entry.type === 'File' && !this.unlink && st.isFile()))
          this[MAKEFS](null, entry)
        else if (st.isDirectory()) {
          if (entry.type === 'Directory') {
            if (!entry.mode || (st.mode & 0o7777) === entry.mode)
              this[MAKEFS](null, entry)
            else
              fs.chmod(entry.absolute, entry.mode, er => this[MAKEFS](er, entry))
          } else
            fs.rmdir(entry.absolute, er => this[MAKEFS](er, entry))
        } else
          fs.unlink(entry.absolute, er => this[MAKEFS](er, entry))
      })
    })
  }
 
  [MAKEFS] (er, entry) {
    if (er)
      return this[ONERROR](er, entry)
 
    switch (entry.type) {
      case 'File':
      case 'OldFile':
      case 'ContiguousFile':
        return this[FILE](entry)
 
      case 'Link':
        return this[HARDLINK](entry)
 
      case 'SymbolicLink':
        return this[SYMLINK](entry)
 
      case 'Directory':
      case 'GNUDumpDir':
        return this[DIRECTORY](entry)
 
      // should be impossible
      /* istanbul ignore next */
      default:
        return this.emit('error', new Error('unknown type: ' + entry.type))
    }
  }
 
  [LINK] (entry, linkpath, link) {
    // XXX: get the type ('file' or 'dir') for windows
    fs[link](linkpath, entry.absolute, er => {
      if (er)
        return this[ONERROR](er, entry)
      this[UNPEND]()
      entry.resume()
    })
  }
}
 
class UnpackSync extends Unpack {
  constructor (opt) {
    super(opt)
  }
 
  [CHECKFS] (entry) {
    const er = this[MKDIR](path.dirname(entry.absolute), this.dmode)
    if (er)
      return this[ONERROR](er, entry)
    try {
      const st = fs.lstatSync(entry.absolute)
      if (this.keep || this.newer && st.mtime > entry.mtime)
        return this[SKIP](entry)
      else if (entry.type === 'File' && !this.unlink && st.isFile())
        return this[MAKEFS](null, entry)
      else {
        try {
          if (st.isDirectory()) {
            if (entry.type === 'Directory') {
              if (entry.mode && (st.mode & 0o7777) !== entry.mode)
                fs.chmodSync(entry.absolute, entry.mode)
            } else
              fs.rmdirSync(entry.absolute)
          } else
            fs.unlinkSync(entry.absolute)
          return this[MAKEFS](null, entry)
        } catch (er) {
          return this[ONERROR](er, entry)
        }
      }
    } catch (er) {
      return this[MAKEFS](null, entry)
    }
  }
 
  [FILE] (entry) {
    const mode = entry.mode & 0o7777 || this.fmode
    try {
      const fd = fs.openSync(entry.absolute, 'w', mode)
      entry.on('data', buf => fs.writeSync(fd, buf, 0, buf.length, null))
      entry.on('end', _ => {
        if (entry.mtime && !this.noMtime) {
          try {
            fs.futimesSync(fd, entry.atime || new Date(), entry.mtime)
          } catch (er) {}
        }
        if (entry.uid && this.preserveOwner) {
          try {
            fs.fchownSync(fd, entry.uid, entry.gid || process.getgid())
          } catch (er) {}
        }
        try { fs.closeSync(fd) } catch (er) { this[ONERROR](er, entry) }
      })
    } catch (er) { this[ONERROR](er, entry) }
  }
 
  [DIRECTORY] (entry) {
    const mode = entry.mode & 0o7777 || this.dmode
    const er = this[MKDIR](entry.absolute, mode)
    if (er)
      return this[ONERROR](er, entry)
    if (entry.mtime && !this.noMtime) {
      try {
        fs.utimesSync(entry.absolute, entry.atime || new Date(), entry.mtime)
      } catch (er) {}
    }
    if (entry.uid && this.preserveOwner) {
      try {
        fs.chownSync(entry.absolute, entry.uid, entry.gid || process.getgid())
      } catch (er) {}
    }
    entry.resume()
  }
 
  [MKDIR] (dir, mode) {
    try {
      return mkdir.sync(dir, {
        preserve: this.preservePaths,
        unlink: this.unlink,
        cache: this.dirCache,
        cwd: this.cwd,
        mode: mode
      })
    } catch (er) {
      return er
    }
  }
 
  [LINK] (entry, linkpath, link) {
    try {
      fs[link + 'Sync'](linkpath, entry.absolute)
      entry.resume()
    } catch (er) {
      return this[ONERROR](er, entry)
    }
  }
}
 
Unpack.Sync = UnpackSync
module.exports = Unpack