# all files / node-ipc/dao/ socketServer.js

63.29% Statements 100/158
55.68% Branches 49/88
73.68% Functions 14/19
63.29% Lines 100/158

    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

    1×

    1×
    1×
    1×

    4×
    4×

    4×

    4×

    4×

    4×

    4×

    1×
    2×

    2×
    2×
    2×

    2×

    2×

    2×

    2×

    2×

    2×

    1×

    1×
    2×
    2×
    2×

    2×
    2×

    2×

    2×

    2×

    2×

    2×

    2×

    1×
    2×
    2×

    2×
    2×

    2×

    2×

    2×

    2×

    2×
    2×
    2×

    2×

    2×
    2×

    2×

    1×
    2×

    1×
    4×

    4×
    2×

    4×
    4×

    4×

    4×

    4×

    2×

    2×
    2×

    2×

    2×

    2×

    4×

    4×

    1×
    4×

    4×
    2×
    2×
    2×

    2×

    2×
    2×

    2×

    4×

    4×

    4×
    1×
    1×

    1×

    1×

    3×
    1×
    1×

    1×

    2×

    2×

    2×

    1×

    1×
    2×
    2×

    2×

    1×
     'use strict';

    const net = require('net'),
        tls = require('tls'),
        fs = require('fs'),
        dgram = require('dgram'),
        eventParser = require('./eventParser.js'),
        Message = require('js-message');

    let Events = require('event-pubsub/es5');
    Eif(process.version[1]>4){
        Events = require('event-pubsub');
    }

    class Server extends Events{
        constructor(path,config,log,port){
            super();
            Object.assign(
                this,
                {
                    config          : config,
                    path            : path,
                    port            : port,
                    udp4            : false,
                    udp6            : false,
                    log             : log,
                    server          : false,
                    sockets         : [],
                    emit            : emit,
                    broadcast       : broadcast
                }
            );

            this.on(
                'close',
                serverClosed.bind(this)
            );
        }

        onStart(socket){
            this.trigger(
                'start',
                socket
            );
        }

        stop(){
            this.server.close();
        }

        start(){
            Iif(!this.path){
                this.log('Socket Server Path not specified, refusing to start');
                return;
            }

            fs.unlink(
                this.path,
                startServer.bind(this)
            );
        }
    }

    function emit(socket, type, data){
        this.log('dispatching event to socket', ' : ', type, data);

        let message=new Message;
        message.type=type;
        message.data=data;

        Iif(this.config.rawBuffer){
            console.log(this.config.encoding)
            message=new Buffer(type,this.config.encoding);
        }else{
            message=eventParser.format(message);
        }

        Eif(this.udp4 || this.udp6){

            Iif(!socket.address || !socket.port){
                this.log('Attempting to emit to a single UDP socket without supplying socket address or port. Redispatching event as broadcast to all connected sockets');
                this.broadcast(type,data);
                return;
            }

            this.server.write(
                message,
                socket
            );
            return;
        }

        socket.write(message);
    }

    function broadcast(type,data){
        this.log('broadcasting event to all known sockets listening to ', this.path,' : ', ((this.port)?this.port:''), type, data);
        let message=new Message;
        message.type=type;
        message.data=data;

        if(this.config.rawBuffer){
            message=new Buffer(type,this.config.encoding);
        }else{
            message=eventParser.format(message);
        }

        if(this.udp4 || this.udp6){
            for(let i=1, count=this.sockets.length; i<count; i++){
                this.server.write(message,this.sockets[i]);
            }
        }else{
            for(let i=0, count=this.sockets.length; i<count; i++){
                this.sockets[i].write(message);
            }
        }
    }

    function serverClosed(){
        for(let i=0, count=this.sockets.length; i<count; i++){
            let socket=this.sockets[i];
            let destroyedSocketId=false;

            Eif(socket){
                Iif(socket.readable){
                    continue;
                }
            }

            Iif(socket.id){
                destroyedSocketId=socket.id;
            }

            this.log('socket disconnected',destroyedSocketId.toString());

            Iif(socket && socket.destroy){
                socket.destroy();
            }

            this.sockets.splice(i,1);

            this.publish('socket.disconnected', socket, destroyedSocketId);

            return;
        }
    }

    function gotData(socket,data,UDPSocket){
        let sock=((this.udp4 || this.udp6)? UDPSocket : socket);
        Iif(this.config.rawBuffer){
            data=new Buffer(data,this.config.encoding);
            this.publish(
                'data',
                data,
                sock
            );
            return;
        }

        Eif(!this.ipcBuffer){
            this.ipcBuffer='';
        }

        data=(this.ipcBuffer+=data);

        Iif(data.slice(-1)!=eventParser.delimiter || data.indexOf(eventParser.delimiter) == -1){
            this.log('Messages are large, You may want to consider smaller messages.');
            return;
        }

        this.ipcBuffer='';

        data=eventParser.parse(data);

        while(data.length>0){
            let message=new Message;
            message.load(data.shift());

            this.log('received event of : ',message.type,message.data);

            Eif(message.data.id){
                sock.id=message.data.id;
            }

            this.publish(
                message.type,
                message.data,
                sock
            );
        }
    }

    function socketClosed(socket){
        this.publish(
            'close',
            socket
        );
    }

    function serverCreated(socket) {
        this.sockets.push(socket);

        if(socket.setEncoding){
            socket.setEncoding(this.config.encoding);
        }

        this.log('## socket connection to server detected ##');
        socket.on(
            'close',
            socketClosed.bind(this)
        );

        socket.on(
            'error',
            function(err){
                this.log('server socket error',err);

                this.publish('error',err);
            }.bind(this)
        );

        socket.on(
            'data',
            gotData.bind(this,socket)
        );

        socket.on(
            'message',
            function(msg,rinfo) {
                Iif (!rinfo){
                    return;
                }

                this.log('Received UDP message from ', rinfo.address, rinfo.port);
                let data;

                Iif(this.config.rawSocket){
                    data=new Buffer(msg,this.config.encoding);
                }else{
                    data=msg.toString();
                }
                socket.emit('data',data,rinfo);
            }.bind(this)
        );

        this.publish(
            'connect',
            socket
        );

        Iif(this.config.rawBuffer){
            return;
        }
    }

    function startServer() {
        this.log(
            'starting server on ',this.path,
            ((this.port)?`:${this.port}`:'')
        );

        if(!this.udp4 && !this.udp6){
            Eif(!this.config.tls){
                this.log('starting TCP server',this.config.tls);
                this.server=net.createServer(
                    serverCreated.bind(this)
                );
            }else{
                startTLSServer.bind(this);
            }
        }else{
            this.server=dgram.createSocket(
                ((this.udp4)? 'udp4':'udp6')
            );
            this.server.write=UDPWrite.bind(this);
            this.server.on(
                'listening',
                function UDPServerStarted() {
                    serverCreated.bind(this)(this.server);
                }.bind(this)
            );
        }

        this.server.on(
            'error',
            function(err){
                this.log('server error',err);

                this.publish(
                    'error',
                    err
                );
            }
        );

        this.server.maxConnections=this.config.maxConnections;

        if(!this.port){
            this.log('starting server as', 'Unix || Windows Socket');
            Iif (process.platform ==='win32'){
                this.path = this.path.replace(/^\//, '');
                this.path = this.path.replace(/\//g, '-');
                this.path= `\\\\.\\pipe\\${this.path}`;
            }

            this.server.listen(
                this.path,
                this.onStart.bind(this)
            );

            return;
        }

        if(!this.udp4 && !this.udp6){
            this.log('starting server as', (this.config.tls?'TLS':'TCP'));
            this.server.listen(
                this.port,
                this.path,
                this.onStart.bind(this)
            );
            return;
        }

        this.log('starting server as',((this.udp4)? 'udp4':'udp6'));

        this.server.bind(
            this.port,
            this.path
        );

        this.onStart(
            {
                address : this.path,
                port    : this.port
            }
        );
    }

    function startTLSServer(){
        this.log('starting TLS server',this.config.tls);
        if(this.config.tls.private){
            this.config.tls.key=fs.readFileSync(this.config.tls.private);
        }else{
            this.config.tls.key=fs.readFileSync(`${__dirname}/../local-node-ipc-certs/private/server.key`);
        }
        if(this.config.tls.public){
            this.config.tls.cert=fs.readFileSync(this.config.tls.public);
        }else{
            this.config.tls.cert=fs.readFileSync(`${__dirname}/../local-node-ipc-certs/server.pub`);
        }
        if(this.config.tls.dhparam){
            this.config.tls.dhparam=fs.readFileSync(this.config.tls.dhparam);
        }
        if(this.config.tls.trustedConnections){
            if(typeof this.config.tls.trustedConnections === 'string'){
                this.config.tls.trustedConnections=[this.config.tls.trustedConnections];
            }
            this.config.tls.ca=[];
            for(let i=0; i<this.config.tls.trustedConnections.length; i++){
                this.config.tls.ca.push(
                    fs.readFileSync(this.config.tls.trustedConnections[i])
                );
            }
        }
        this.server=tls.createServer(
            this.config.tls,
            serverCreated.bind(this)
        );
    }

    function UDPWrite(message,socket){
        let data=new Buffer(message, this.config.encoding);
        this.server.send(
            data,
            0,
            data.length,
            socket.port,
            socket.address,
            function(err, bytes) {
                Iif(err){
                    this.log('error writing data to socket',err);
                    this.publish(
                        'error',
                        function(err){
                            this.publish('error',err);
                        }
                    );
                }
            }
        );
    }

    module.exports=Server;