forked from Instanssi/effectserver
-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.coffee
93 lines (68 loc) · 2.24 KB
/
server.coffee
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
CSON = require "cson"
dgram = require "dgram"
fs = require "fs"
util = require "util"
EventEmitter = require "events"
process.on 'uncaughtException', (err) ->
console.log 'Caught exception', err
{EffectManager} = require "./lib/effectmanager"
{packetParse} = require "./lib/packetparser"
{webserver, websocket} = require "./web/webserver"
udpserver = dgram.createSocket("udp4")
onConfigRead = (error, config) ->
if error
console.error 'failed to read configuration file:', error
throw error
webserver.config = config
manager = new EffectManager config.hosts, config.mapping
manager.build()
webserver.get "/config.json", (req, res) ->
res.json manager.toJSON()
if process.env.TAG
firewall =
allowOnly:
tag: process.env.TAG
setTimeout ->
console.log "FIREWALL", firewall
, 1000
udpserver.on "message", (packet, rinfo) ->
try
cmds = packetParse packet
catch e
# TODO: catch only parse errors
websocket.sockets.volatile.emit "parseError",
error: e.message
address: rinfo.address
# Failed to parse the packet. We cannot continue from here at all.
return
results =
# Packet starts as anonymous always
tag: "anonymous"
address: rinfo.address
cmds: []
for cmd in cmds
# First fragment might tag this packet
if cmd.tag
results.tag = cmd.tag.substring(0, 15)
continue # to next fragment
if firewall?
if results.tag isnt firewall.allowOnly.tag
console.log "Bad tag '#{ results.tag }' we need '#{ firewall.allowOnly.tag }'"
continue
if error = manager.route cmd
cmd.error = error
results.cmds.push cmd
manager.commitAll()
# No debug when firewall is on
if not firewall?
websocket.sockets.volatile.emit "cmds", results
udpserver.on "listening", ->
console.log "Now listening on UDP port #{ config.servers.udpPort }"
udpserver.bind config.servers.udpPort
webserver.listen config.servers.httpPort, ->
console.log "Now listening on HTTP port #{ config.servers.httpPort }"
try
CSON.parseFile __dirname + '/config.cson', { format: 'cson' }, onConfigRead
catch e
console.log 'Unable to read config.cson!', e
process.exit 1