|
| 1 | +const cluster = require('cluster'); |
| 2 | +const ldap = require('ldapjs'); |
| 3 | +const os = require('os'); |
| 4 | + |
| 5 | +const threads = []; |
| 6 | +threads.getNext = function () { |
| 7 | + return (Math.floor(Math.random() * this.length)); |
| 8 | +}; |
| 9 | + |
| 10 | +const serverOptions = { |
| 11 | + connectionRouter: (socket) => { |
| 12 | + socket.pause(); |
| 13 | + console.log('ldapjs client requesting connection'); |
| 14 | + let routeTo = threads.getNext(); |
| 15 | + threads[routeTo].send({ type: 'connection' }, socket); |
| 16 | + } |
| 17 | +}; |
| 18 | + |
| 19 | +const server = ldap.createServer(serverOptions); |
| 20 | + |
| 21 | +if (cluster.isMaster) { |
| 22 | + for (let i = 0; i < os.cpus().length; i++) { |
| 23 | + let thread = cluster.fork({ |
| 24 | + 'id': i |
| 25 | + }); |
| 26 | + thread.id = i; |
| 27 | + thread.on('message', function (msg) { |
| 28 | + |
| 29 | + }); |
| 30 | + threads.push(thread); |
| 31 | + } |
| 32 | + |
| 33 | + server.listen(1389, function () { |
| 34 | + console.log('ldapjs listening at ' + server.url); |
| 35 | + }); |
| 36 | +} else { |
| 37 | + let threadId = process.env.id; |
| 38 | + serverOptions.connectionRouter = (connection) => { |
| 39 | + console.log('should not be hit'); |
| 40 | + }; |
| 41 | + |
| 42 | + process.on('message', (msg, socket) => { |
| 43 | + switch (msg.type) { |
| 44 | + case 'connection': |
| 45 | + server.newConnection(socket); |
| 46 | + socket.resume(); |
| 47 | + console.log('ldapjs client connection accepted on ' + threadId.toString()); |
| 48 | + } |
| 49 | + }); |
| 50 | + |
| 51 | + server.search('dc=example', function (req, res, next) { |
| 52 | + console.log('ldapjs search initiated on ' + threadId.toString()); |
| 53 | + var obj = { |
| 54 | + dn: req.dn.toString(), |
| 55 | + attributes: { |
| 56 | + objectclass: ['organization', 'top'], |
| 57 | + o: 'example' |
| 58 | + } |
| 59 | + }; |
| 60 | + |
| 61 | + if (req.filter.matches(obj.attributes)) |
| 62 | + res.send(obj); |
| 63 | + |
| 64 | + res.end(); |
| 65 | + }); |
| 66 | +} |
0 commit comments