uid-number.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. module.exports = uidNumber
  2. // This module calls into get-uid-gid.js, which sets the
  3. // uid and gid to the supplied argument, in order to find out their
  4. // numeric value. This can't be done in the main node process,
  5. // because otherwise node would be running as that user from this
  6. // point on.
  7. var child_process = require("child_process")
  8. , path = require("path")
  9. , uidSupport = process.getuid && process.setuid
  10. , uidCache = {}
  11. , gidCache = {}
  12. function uidNumber (uid, gid, cb) {
  13. if (!uidSupport) return cb()
  14. if (typeof cb !== "function") cb = gid, gid = null
  15. if (typeof cb !== "function") cb = uid, uid = null
  16. if (gid == null) gid = process.getgid()
  17. if (uid == null) uid = process.getuid()
  18. if (!isNaN(gid)) gid = gidCache[gid] = +gid
  19. if (!isNaN(uid)) uid = uidCache[uid] = +uid
  20. if (uidCache.hasOwnProperty(uid)) uid = uidCache[uid]
  21. if (gidCache.hasOwnProperty(gid)) gid = gidCache[gid]
  22. if (typeof gid === "number" && typeof uid === "number") {
  23. return process.nextTick(cb.bind(null, null, uid, gid))
  24. }
  25. var getter = require.resolve("./get-uid-gid.js")
  26. child_process.execFile( process.execPath
  27. , [getter, uid, gid]
  28. , function (code, out, stderr) {
  29. if (code) {
  30. var er = new Error("could not get uid/gid\n" + stderr)
  31. er.code = code
  32. return cb(er)
  33. }
  34. try {
  35. out = JSON.parse(out+"")
  36. } catch (ex) {
  37. return cb(ex)
  38. }
  39. if (out.error) {
  40. var er = new Error(out.error)
  41. er.errno = out.errno
  42. return cb(er)
  43. }
  44. if (isNaN(out.uid) || isNaN(out.gid)) return cb(new Error(
  45. "Could not get uid/gid: "+JSON.stringify(out)))
  46. cb(null, uidCache[uid] = +out.uid, gidCache[gid] = +out.gid)
  47. })
  48. }