-
Notifications
You must be signed in to change notification settings - Fork 2
/
ssdp.js
195 lines (134 loc) · 4.51 KB
/
ssdp.js
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
const dgram = require("dgram");
const url = require("url");
const WebSocket = require("ws");
const { xml2json } = require("xml-js");
const request = require("./request");
const logger = require("./system/logger.js");
const log = logger.create("forwarder/ssdp");
let uri = new url.URL(process.env.BACKEND_URL);
uri.protocol = (process.env.BACKEND_PROTOCOL === "https" ? "wss" : "ws");
uri.pathname = "/api/ssdp";
uri.search = `x-auth-token=${process.env.AUTH_TOKEN}`;
const ws = new WebSocket(uri);
const socket = dgram.createSocket({
type: "udp4",
reuseAddr: true
});
ws.on("close", (code) => {
log.debug(`Disconnected from ${ws.url}`);
socket.close(() => {
process.exit(code);
});
});
async function parseHeader(msg, { address, port }) {
let headers = {};
let lines = msg.toString().split("\r\n");
let type = lines[0];
if (type.endsWith("* HTTP/1.1")) {
type = type.split(" ")[0];
} else if (type === "HTTP/1.1 200 OK") {
type = "SEARCH-RESPONSE";
} else {
console.log("Unknwon type");
}
// store head key/value pair in object
lines.slice(1, lines.length - 2).forEach((line) => {
let [key, ...value] = line.split(":");
let k = key.toLowerCase();
let v = value.join(":").trim().replaceAll(`"`, "");
headers[k] = v;
});
// add additional client headers
headers["X-REMOTE-ADDRESS"] = address;
headers["X-REMOTE-PORT"] = port;
// for better handling, convert to lowercase
type = type.toLowerCase();
if (!["m-search", "notify", "search-response"].includes(type)) {
console.log("UNKNOWN SSDP MESSAGE");
throw new Error(`unknown ssdp message type ${type}`);
}
return {
headers,
type
};
}
function fetchLocation(uri) {
return new Promise((resolve, reject) => {
request(uri, (err, result) => {
if (err) {
reject(err);
} else {
let { body } = result;
let json = xml2json(body.toString(), {
compact: true,
spaces: 4
});
resolve(json);
}
});
});
}
socket.on("message", async (msg, { address, port }) => {
log.trace("Message on udp socket received", msg, { address, port });
if (ws.readyState === ws.OPEN) {
try {
// prase header & set additional remote header
// X-REMOTE-ADDRESS = address
// X-REMOTE-PORT = port
let { headers, type } = await parseHeader(msg, {
address,
port
});
// extract location & nts
// (to fetch description)
let { location, nts } = headers;
// create from header object
// a new `msg` like string
/*
let head = Object.keys(headers).map((key) => {
return `${key}=${headers[key]}\r\n`;
});
*/
// check if we handle a notification & device is alive
// if so do a http requestion to the location header value
if (type === "notify" && nts === "ssdp:alive" && location) {
let description = await fetchLocation(location);
let data = Buffer.concat([
//Buffer.from(type), // DRAFT!
//Buffer.from(head), // DRAFT!
Buffer.from(msg),
Buffer.from(description),
Buffer.from("\r\n"),
Buffer.from("\r\n")
]);
// feedback
//console.log(`Send to server from client udp://${address}:${port} `, data.toString());
ws.send(data);
} else {
/*
let data = Buffer.concat([
Buffer.from(type),
Buffer.from(head)
]);
*/
ws.send(msg);
}
} catch (err) {
console.error(err);
}
}
});
socket.on("listening", () => {
const address = socket.address();
log.info(`Server listening udp://${address.address}:${address.port}`);
socket.addMembership("239.255.255.250");
});
ws.on("message", (msg) => {
log.trace("Send message to multicast addr", msg);
socket.send(msg, 0, msg.length, 1900, "239.255.255.250");
});
ws.on("open", () => {
log.info(`Connected to ${ws.url}`);
// bind socket
socket.bind(1900, "0.0.0.0");
});