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