-
Notifications
You must be signed in to change notification settings - Fork 2
/
cryo
executable file
·403 lines (373 loc) · 9.99 KB
/
cryo
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
395
396
397
398
399
400
401
402
403
#!/usr/bin/env node
/* networked cry node -- 2012 -- pancake@nopcode.org */
var net = require ('net');
var exec = require ("child_process").exec
var spawn = require ("child_process").spawn
var rl = require ('readline').createInterface (
process.stdin, process.stdout, completer);
var use_udp = true
var cmd_notify = "mplayer "+__dirname+"/lib/message.oga"
var cmd_error = "mplayer "+__dirname+"/lib/error.oga"
var UUID = 0;
var port = 9999
var host = undefined
var iam = process.env ["USER"] || undefined
var key = ''
var udp_port = 9999;
var cry = __dirname + "/cry"
var forward = false; // not yet implemented
var reconnect = true;
var reconnect_every = 5;
/* --- */
var p = spawn ("sh", [ "-c", "cry -l| grep ^p|head -n1|awk '{print $2}'" ])
p.stdout.on ('data', function (data) {
iam = (""+data).trim ();
});
/* --- */
switch (process.argv.length) {
case 4:
key = process.argv[2]
udp_port = port = process.argv[3]
break;
case 5:
key = process.argv[2]
host = process.argv[3]
udp_port = port = process.argv[4]
break;
default:
console.log ("client: cryo [pubkey] [host] [port]")
console.log ("server: cryo [pubkey] [port]")
process.exit (1);
break;
}
rl.set_prompt = function (x) {
var id = peer? peer.uuid: -1;
if (x) rl.setPrompt ('['+key+'] \x1b[32m<'+x+':'+id+'> \x1b[0m', (key+x+id).length+7);
}
rl.set_prompt (iam)
rl.prompt ();
function system(x) {
var c = x.split (/ /g)
spawn(c[0], c.splice(1))
}
var cryo_import = function (name, key) {
var p = spawn (cry, ['-i', name, '-']);
var body = "";
p.stdout.on ('data', function (data) { body += data; });
p.stdout.on ('close', function (code) { print (body) });
p.stdin.on ("drain", function () { p.stdin.end (); });
p.stdin.write (key)
}
var enc = (function (msg, cb) {
var p = spawn (cry, ['-e', key]);
var body = "";
p.stdout.on ('data', function (data) { body += data; });
p.stdout.on ('close', function (code) { cb (body); });
p.stdin.on ("drain", function () { p.stdin.end (); });
p.stdin.write (msg)
})
var dec = (function (msg, cb) {
var oclosed = false;
var eclosed = false;
var body = "";
var nkey = ""
var p = spawn (cry, ['-d']);
p.stderr.on ('data', function (data) {
nkey = (""+data).trim ()
if (nkey.indexOf (' ') != -1)
console.error ("ERROR "+nkey);
});
p.stderr.on ('close', function (code) { eclosed = true; if (oclosed) cb (nkey, body); });
p.stdout.on ('data', function (data) { body += data; });
p.stdout.on ('close', function (code) { oclosed = true; if (eclosed) cb (nkey, body); });
p.stdin.on ("drain", function () { p.stdin.end (); });
p.stdin.write (msg.replace (/\r/g,''));
})
var peers = [];
var peer = undefined
function set_peer (n) {
var i = 0;
for (var p in peers) {
if (n == i++) {
if ((peer = peers[p])) {
key = peer.key
return true;
}
return false;
}
}
return false;
}
function list_peers () {
var i = 0;
for (var x in peers) {
var p = peers[x];
if (p) {
var pn = "";
if (p.pub_name)
pn = "@("+p.pub_name+")";
console.log (peer == p? '*': ' ',
i, p.host+":"+p.port, p.key, pn);
}
i++;
}
}
var offline = function () {
status ("offline");
system (cmd_error);
}
var sendmsg = offline;
function peersend (data, type) {
if (type) {
try { if (peer) peer.sock.write (type+"\n"+data)
} catch (e) { print ("cannot write 0", e) }
return;
}
type = "msg";
enc (data, function (x) {
try { if (peer) peer.sock.write (type+"\n"+x)
} catch (e) { print ("cannot write 1") }
});
}
function cryo_disconnect (host, port) {
if (peer) peer.sock.destroy ();
}
var _status = undefined;
function status(x) {
if (x) { print (x); return _status = x; }
return _status;
}
function print (x) {
var d = new Date ();
function atoi (x) { if (x<10) return "0"+x; return x; }
now = ((""+x).indexOf ('<') != -1)?
atoi (d.getHours ()) + ":" + atoi (d.getMinutes ())+" ": "";
console.log ("\r\x1b[0K"+now+x)
rl.prompt (true);
}
function cryo_decode_msg (uuid, data) {
var noff = data.indexOf ('\n');
if (noff != -1) {
header = data.substring (0, noff).split (' ')
data = data.substring (noff+1)
} else header = [];
var input = (""+data).replace (/==/,'_=').split ('=');
for (var i=0; i<input.length;i++) {
var str = input[i].trim ().replace(/_/,'=') + "=";
if (str == "=") continue;
switch (header[0]) {
case 'pong':
dec (str, function (x, y) {
print ("PONG <"+x+":"+uuid+"> "+y.trim ())
});
break;
case 'ping':
dec (str, function (x, y) {
enc (y.trim(), function (x2) {
sendmsg (x2, "pong")
print ("PONG <"+x+":"+uuid+"> "+y.trim ())
});
});
break;
case 'pub':
print ("Received public key from "+header[1])
console.log (data)
console.log ("Type /import to accept it")
peer.pub_name = header[1];
peer.pub = data
rl.prompt (true);
break;
case 'msg':
dec (str, function (x, y) {
rl.set_prompt (x);
system (cmd_notify);
print ("<"+key+":"+uuid+"> "+y.trim ())
});
break;
default:
print ("Invalid packet");
break;
}
}
}
function cryo_pub (k) {
var p = spawn (cry, ['-p', k]);
var pubkey = "";
p.stdout.on ('data', function (data) {
pubkey += (""+data)
});
p.stdout.on ('close', function (data) {
if (pubkey.length>0) {
sendmsg (pubkey, "pub "+k);
} else print ("Cannot find pubkey");
});
}
function newPeer (c) {
var uuid = UUID++;
print ("peer "+uuid+" connected");
c.setNoDelay ();
var p = peers[uuid] = {
'host': c.remoteAddress,
'port': c.remotePort,
'uuid': uuid,
'key' : key,
'sock': c
};
if (!peer) peer = p;
sendmsg = peersend
return p;
}
function delPeer (p) {
print ('peer disconnected');
if (peer == p) {
sendmsg = offline;
peer = undefined
}
delete peers[p.uuid]
}
function cryo_connect (host, port) {
status ("connecting to "+host+":"+port);
var c = net.connect (port, host, function () {
var p = newPeer (c);
c.on ('data', function (data) { cryo_decode_msg (p.uuid, ""+data) });
c.on ('end', function () { delPeer (p); });
});
c.on ('error', offline);
}
function cryo_listen (port) {
/* listen */
var server = net.createServer (function (c) {
var p = newPeer (c);
c.on ('data', function (data) { cryo_decode_msg (p.uuid, ""+data) });
c.on ('end', function () { delPeer (p); });
c.on ('error', offline);
});
server.listen (port, function () {
print ('listening on '+ port);
});
}
/* main */
if (host) {
cryo_connect (host, port);
if (reconnect) {
setInterval (function (x) {
if (sendmsg == offline) {
if (status () == "connecting")
return;
cryo_connect (host, port);
}
}, reconnect_every*1000);
}
} else cryo_listen (port);
var commands = {
'help': { callback: function () {
for (var k in commands) {
var av = commands[k].help.split("\t")
nsp = Array (15-(av[0].length+k.length)).join (' ')
console.log ("/"+k+" "+av[0]+nsp+av[1])
}
}, help: "\tshow this help message" },
'connect': { callback: function(args) {
if (args[1]) host = args[1]
if (args[2]) port = args[2]
cryo_disconnect ();
cryo_connect (host, port)
}, help: "[h p]\tconnect to remote host and port" },
'disconnect': { callback: function() {
cryo_disconnect ()
}, help: "\tunlink current peer" },
'key': { callback: function (args) {
if (args[1]) {
if (peer) peer.key = key = args[1];
} else print (key);
}, help: "[k]\tset pub key for current peer" },
'keys': { callback: function (args) {
cryo_cmd ("!cry -l")
}, help: "\talias for !cry -l" },
'ping': { callback: function (args) {
var uuid = ""+Math.floor (Math.random ()*999999)
console.log ("PING "+uuid)
enc (uuid, function (x) {
sendmsg (x, "ping")
});
}, help: "\tsend ping. expect pong" },
'peer': { callback: function (args) {
if (args[1]) {
if (!set_peer (args[1]))
print ("invalid peer id")
} else if (peer) print (peer.uuid);
}, help: "[p]\tselect peer" },
'exit': { callback: function () {
console.log ("byebye");
process.exit (0);
}, help: "\tquit this program" },
'import': { callback: function () {
if (peer && peer.pub_name && peer.pub) {
cryo_import (peer.pub_name, peer.pub);
peer.pub_name = peer.pub = undefined;
} else print ("Nothing to import");
}, help: "\timport given key" },
'list': { callback: function() {
list_peers ()
}, help: "\tlist all peers" },
'lan': { callback: function(args) {
var cmd = args.splice(1).join (' ')
var client = dgram.createSocket ("udp4");
//client.setBroadcast (true)
client.bind ()
client.setBroadcast (true)
enc (cmd, function (str, y) {
str = new Buffer ("msg\n"+str)
client.send (str, 0, str.length, udp_port, "255.255.255.255", function (err, bytes) {
//client.send (str, 0, str.length, udp_port, "127.0.0.1", function (err, bytes) {
client.close();
});
});
}, help: "[m]\tsend lan message (udp broadcast)" },
'pub': { callback: function(args) {
if (args[1]) cryo_pub (args[1]);
else console.log ("Missing argument");
}, help: "\tannounce public key" }
}
var n=0, completions = new Array (commands.length)
for (var k in commands) completions[n++] = "/"+k;
function completer (line) {
var hits = completions.filter (function(c) { if (c.indexOf (line) == 0) { return c; }});
return [hits && hits.length ? hits : completions, line];
}
function cryo_cmd (str) {
switch (str[0]) {
case '!':
var p = spawn ("sh", ["-c", str.substring (1)])
if (p) {
var body = "";
p.stdout.on ('data', function (data) { body += data; });
p.stdout.on ('close', function (data) { print (body.trim()) });
}
break;
case '/':
var args = str.substring (1).split (/ /);
var cb = commands[args[0]];
if (cb) cb.callback (args)
else console.error ("Invalid command.");
break;
default:
if (str.length>0) sendmsg (str);
}
}
rl.on ('line', function (line) {
var str = line.trim ();
cryo_cmd (str);
rl.prompt ();
}).on ('close', function () {
console.log ("^D");
process.exit (0);
});
if (use_udp && udp_port != 0) {
var dgram = require('dgram');
print ("listening udp packets on port "+udp_port)
var server = dgram.createSocket ("udp4", function (msg, rinfo) {
cryo_decode_msg ('udp', ""+msg)
});
server.bind (udp_port, '0.0.0.0')
}