-
Notifications
You must be signed in to change notification settings - Fork 0
/
ciscoxml.js
649 lines (572 loc) · 19.7 KB
/
ciscoxml.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
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
/**
* Created by delian on 3/8/15.
*/
var net = require('net');
var debug = require('debug')('ciscoxml');
var util = require('util');
var xml2js = require('xml2js');
var tls = require('tls');
//var clone = require('clone');
var xmlBuilder = new xml2js.Builder({ rootName: 'Request' });
var xmlParser = xml2js.parseString;
// TODO: Error handling and state cleaning when the TCP session is disconnected
function Session(config) {
if (!(this instanceof Session)) return new Session(config);
var me = this;
me.config = {
host: '127.0.0.1',
port: '38751',
userPromptRegex: /(Username|Login)\:\s*/i,
passPromptRegex: /Password\:\s*/i,
xmlPromptRegex: /XML\>\s*/,
authFailRegex: /Authentication Failed/i,
username: 'guest',
password: 'guest',
connectErrCnt: 3,
autoConnect: true,
ssl: false, // If present and it is an object, we assume it will contain the SSL options of the TLS module
autoDisconnect: 60000,
keepAlive: 30000,
noDelay: true
};
if (typeof config == 'object') util._extend(me.config,config);
me.client = false;
me.connected = false;
me.connecting = false;
me.authenticated = false;
me.buffer = "";
me.autoDisconnectId = null;
me.rawQueue = []; // This queue contains the tasks we like to execute - data + callback for response
me.rawQueueBlocked = false;
return this;
}
Session.prototype.js2xml = function(obj,cb) {
var e;
try {
cb(null,xmlBuilder.buildObject(obj));
} catch(e) {
cb(e,null);
}
};
Session.prototype.xml2js = xmlParser;
Session.prototype.objPretty = function(obj) {
function pretty(o) {
if (o instanceof Array) {
for (var n=0;n<o.length;n++)
if (typeof o[n] == 'string') {
if (/^\d+$/.test(o[n])) o[n]=parseInt(o[n]);
if (o[n]=='true' || o[n]=='false') o[n]=(o[n]=='true')?true:false;
}
return o.forEach(pretty);
}
if (typeof o == 'object') {
Object.keys(o).forEach(function(n) {
if (o[n] instanceof Array) {
if (o[n].length==1)
o[n] = o[n][0];
else
if (o[n].length==0) o[n] = '';
}
if (typeof o[n] == 'string') {
if (/^\d+$/.test(o[n])) o[n]=parseInt(o[n]);
if (o[n]=='true' || o[n]=='false') o[n]=(o[n]=='true')?true:false;
}
pretty(o[n]);
});
}
}
pretty(obj);
return obj;
};
/**
* This is a function that should be called when a session is terminated
*/
Session.prototype.onEnd = function() {
debug('Session ended');
var me = this;
me.connected = false;
me.authenticated = false;
// Distribute errors if we have tasks waiting
if (me.rawQueueBlocked) {
debug('ERROR: Remote side disconnected, but we still wait for response');
return me.errorRawTask(new Error('Remote side disconnected'));
}
if (me.rawQueue.length>0) { // This should never happen
debug('WARN: Remote side disconnected, but we have tasks waiting');
if (me.config.autoConnect) {
debug('WARN: autoConnect is true. Reconnect');
me.connect();
}
}
};
/**
* Connect to the remote site
* @param config
* @param cb
*/
Session.prototype.connect = function(config,callback) {
var me = this;
var cb = function() {};
if (typeof callback == 'function') cb = callback;
if (typeof config == 'function') cb = config;
if (typeof config == 'object') util._extend(me.config,config);
debug('Trying to connect to %s:%s, SSL %s',me.config.host, me.config.port, me.config.ssl?'Yes':'No');
if (me.config.connectErrCnt<=0) {
debug('ERROR: We have no more right to retry!');
return cb(new Error('No more connect retry!'));
}
if (me.connecting) return; // Connection is ongoing
me.connecting = true;
function connectProc() {
debug('Connected to %s:%s',me.config.host,me.config.port);
me.connected = true;
me.authenticated = false;
me.connecting = false;
me.client.on('data',function(data) {
// We receive data
me.buffer += data;
if (!me.authenticated) {
// Check for authentication
// Check for Login: or Username: and send the username
// Check for Password: and send password
// Check for XML and terminate the authentication
debug('AUTH: >>> %s',me.buffer);
if (me.buffer.match(me.config.xmlPromptRegex)) {
me.authenticated = true;
me.buffer = "";
debug('AUTH: ---- Authentication successful!');
me.nextRawTask(); // Lets add the next task if it is waiting
if (cb) cb(null,me); // Start the callback once
cb = null; // Avoid double call of the callback
return; // Successful completion
} else {
if (me.buffer.match(me.config.userPromptRegex)) {
me.client.write(me.config.username+'\r\n');
me.buffer = "";
debug('AUTH: <<< %s',me.config.username);
}
if (me.buffer.match(me.config.passPromptRegex)) {
me.client.write(me.config.password+'\r\n');
me.buffer = "";
debug('AUTH: <<< %s',me.config.password);
}
if (me.buffer.match(me.config.authFailRegex)) {
debug('AUTH: !!!! Authentication failed!');
if (cb) cb(new Error('Authentication Failed'));
return me.client.end(); // Fail
}
}
return;
}
if (me.buffer.match(me.config.xmlPromptRegex)) {
me.buffer = me.buffer.replace(me.config.xmlPromptRegex,'');
}
// We are authenticated and we receive data. Lets filter <Response ..>...</Response> and return it back to a CB queue
if (me.buffer.match(/\<\/Response\>/i)) {
debug('RESPONSE: <<< %s',me.buffer);
me.popNextTask(me.buffer);
me.buffer = me.buffer.replace(/^[\s\S]*<\/Response\>/i,''); // Remove it from the buffer
//debug('TRIM: buffer left to be %s', me.buffer);
}
// if (me.buffer.match(/\<\/Notification\>/i)) {
// debug('NOTIFICATION: <<< %s',me.buffer);
// me.notify(me.buffer);
// me.buffer = me.buffer.replace(/^[\s\S]*<\/Notification\>/i,'');
// }
});
}
if (me.config.ssl) {
me.client = tls.connect(
me.config.port,
me.config.host,
typeof me.config.ssl == 'object'?me.config.ssl:{},
function() {
debug('SSL connected!');
connectProc();
}
);
me.client.setNoDelay(this.config.noDelay);
me.client.setKeepAlive(this.config.keepAlive);
} else {
me.client = new net.Socket();
me.client.setNoDelay(this.config.noDelay);
me.client.setKeepAlive(this.config.keepAlive);
me.client.connect(
me.config.port,
me.config.host,
connectProc
)
}
me.client.on('end',function() {
me.onEnd();
});
me.client.on('error',function(err) {
debug('ERROR: Connect error %s',err);
if (cb) cb(err);
me.errorRawTask(err);
if (me.config.connectErrCnt>0) me.config.connectErrCnt--;
me.connecting = false;
});
};
/**
* Disconnect from the remote site
* @param cb
*/
Session.prototype.disconnect = function(callback) {
var cb = function() {};
if (typeof callback == 'function') cb = callback;
if (this.config.connectErrCnt>0) this.config.connectErrCnt++; // to avoid normal decrease of the counter
this.client.end();
debug('SESSION disconnected');
cb();
};
/**
* Execute the next task if we are not waiting for response
*/
Session.prototype.nextRawTask = function() {
var me = this;
if (!(me.connected && me.authenticated)) {
if (!me.config.autoConnect) return;
debug('WARN: Next task is dispatched, but we are not yet connected. Connect...');
return me.connect(); // Connect has automatic nextRawTask execution
}
if (me.rawQueueBlocked) return;
if (me.rawQueue.length == 0) {
// Execute autoDisconnect
if (me.config.autoDisconnect && me.config.autoDisconnect>0) {
if (me.autoDisconnectId) clearTimeout(me.autoDisconnectId);
me.autoDisconnectId = setTimeout(function() {
debug('WARN: Timeout expired with no new tasks. Autodisconnect');
me.disconnect();
},me.config.autoDisconnect);
return;
}
}
if (me.autoDisconnectId) clearTimeout(me.autoDisconnectId);
me.rawQueueBlocked = true;
var data = me.rawQueue[0].data;
if (!data.match(/\r\n$/)) data += '\r\n';
me.client.write(data,function() {
debug('QUEUE: >>> data sent to device %s',data);
});
};
/**
* Remove the top task blocked task
*/
Session.prototype.popNextTask = function(data) {
if (!this.rawQueueBlocked) return;
if (typeof this.rawQueue[0].cb == 'function') this.rawQueue[0].cb(null,data);
this.rawQueue.shift();
this.rawQueueBlocked = false;
this.nextRawTask();
};
/**
* Sends raw data and expects callback
* @param data
* @param cb
*/
Session.prototype.sendRaw = function(data,callback,priority) {
var cb = function() {};
if (typeof callback == 'function') cb = callback;
debug('QUEUE: New task has been add with %s and priority %s',data,priority?'first':'last');
if ((!(this.connected && this.authenticated))&&(!this.config.autoConnect)) {
debug('ERROR: new task has been dispatched, but we are not yet connected!');
return cb(new Error('Not connected'));
}
if (priority)
this.rawQueue.splice(this.rawQueueBlocked?1:0,0,{ data: data, cb: cb }); // The first possible execution
else
this.rawQueue.push({ data: data, cb: cb }); // Add it at the end
this.nextRawTask();
};
/**
* Discard all of the tasks in the raw queue
*/
Session.prototype.discardRawQueue = function() {
if (this.rawQueue.length>0) debug('DISCARD %d raw tasks!',this.rawQueue.length);
this.rawQueue = [];
this.rawQueueBlocked = false;
};
/**
* Notification
* @param buffer
*/
Session.prototype.notify = function(buffer) {
// TODO: Implement notification system
debug('WARN: Notification code is not yet implemented!');
};
/**
* Executes error to all waiting tasks in the raw queue
* @param err
*/
Session.prototype.errorRawTask = function(err) {
if (this.rawQueue.length>0) debug('Notify with error %d raw tasks!',this.rawQueue.length);
this.rawQueue.forEach(function(q) {
if (typeof q.cb == 'function') q.cb(err);
});
this.discardRawQueue();
};
// ------ XML ------
Session.prototype.sendRawObj = function(data,callback,priority) {
var cb = function() {};
if (typeof callback == 'function') cb = callback;
if (typeof data != 'object') {
debug('ERROR: We received request not in the right format! %s',data);
return cb(new Error('Incorrect data'));
}
var me = this;
if (typeof data['$'] == 'undefined') data['$'] = { MajorVersion: '1', MinorVersion: '0' };
me.js2xml(data,function(err,data) {
me.sendRaw(data,function (err,data) {
if (err) return cb(err,data);
me.xml2js(data,cb); // Now we could inherit the error from the XML parsing
},priority);
});
};
/**
* Run GetNext request with IteratorID = id
* @param id
* @param cb
*/
Session.prototype.getNext = function(id,cb) {
debug('Execute getNext request with id %s',id);
return this.sendRawObj({ GetNext: { $: { IteratorID: id } } },cb,true);
};
/**
* This is the same as sendRawObj but automatically handles getNext is it is present
* @param data
* @param cb
* @returns {*}
*/
Session.prototype.sendRequest = function(data,callback) {
var cb = function() {};
if (typeof callback == 'function') cb=callback;
if (typeof data != 'object') {
debug('ERROR: We received request not in the right format! %s',data);
cb(new Error('Incorrect data'));
return;
}
var me = this;
return me.sendRawObj(data,function(err,resp) {
if (err) return cb(err,resp);
// Test for Iterator
if (resp && resp.Response && resp.Response['$']) {
if (resp.Response['$'].IteratorID) {
return me.getNext(resp.Response['$'].IteratorID,function(err,resp2) {
if (err) return cb(err,resp2);
cb(err,util._extend(resp,resp2)); // Merge the data
},true); // Set it with priority
}
}
cb(err,resp);
});
};
// ------ Global Commands ------
Session.prototype.rootGetDataSpaceInfo = function(cb) {
return this.sendRequest({ GetDataSpaceInfo: '' },cb);
};
Session.prototype.getConfig = function(p1,p2) {
var cb = null;
var req = {
Get: {
Configuration: ''
}
};
if (typeof p1 == 'function') cb = p1;
else if (p1) req.Get.Configuration = p1;
if (typeof p2 == 'function') cb = p2;
else if (p2) req.Get.Configuration = p2;
return this.sendRequest(req,cb);
};
Session.prototype.setAction = function(p1,p2) {
var cb = null;
var req = {
Set: {
Action: ''
}
};
if (typeof p1 == 'function') cb = p1;
else if (p1) req.Set.Action = p1;
if (typeof p2 == 'function') cb = p2;
else if (p2) req.Set.Action = p2;
return this.sendRequest(req,cb);
};
Session.prototype.getOper = function(p1,p2) {
var cb = null;
var req = {
Get: {
Operational: ''
}
};
if (typeof p1 == 'function') cb = p1;
else if (p1) req.Get.Operational = p1;
if (typeof p2 == 'function') cb = p2;
else if (p2) req.Get.Operational = p2;
return this.sendRequest(req,cb);
};
/**
* Expands path in a format similar to XPath
* For example Hostname = <Hostname/>
*
* @param path
*/
Session.prototype.pathExpand = function (path) {
function name(a) { // Returns only the name of the property
return a.replace(/\(.*\)/g,'').replace(/\{.*\}/g,'').replace(/\=.*$/,'');
}
function attribs(a) { // Expands attributes and property
var o = {};
return o;
}
var obj = {};
var o = obj;
var a = path.split('.');
for (var a = path.split('.'); a.length; o=o[name(a[0])]=attribs(a.shift()));
return obj;
};
Session.prototype.pathExpandXml = function(path) {
var data = this.pathExpand(path);
if (typeof data['$'] == 'undefined') data['$'] = { MajorVersion: '1', MinorVersion: '0' };
return xmlBuilder.buildObject(data);
};
Session.prototype.requestByPath = function(path,cb) {
return this.sendRequest(this.pathExpand(path),cb);
};
Session.prototype.reqPathPath = function(path,p1,p2) {
var cb = null;
var filter = null;
var me = this;
if (p1 instanceof RegExp) filter = p1;
if (p2 instanceof RegExp) filter = p2;
if (typeof p1 == 'function') cb = p1;
if (typeof p2 == 'function') cb = p2;
return me.requestByPath(path,function(err,data) {
if (err) {
if (cb) cb(err,data);
return;
}
//debug('We will execute callback %o',cb);
//debug('We will search data with filter %o',filter);
if (cb) cb(err,me.obj2path(data,filter))
});
};
// CLI Exec
/**
* Execute string command in a CLI config mode
* @param cmd
* @param cb
* @returns {*}
*/
Session.prototype.cliConfig = function(cmd,cb) {
return this.sendRequest({ CLI: { Configuration: cmd }},cb);
};
Session.prototype.cliExec = function(cmd,cb) {
return this.sendRequest({ CLI: { Exec: cmd }},cb);
};
Session.prototype.commit = function(p1,p2) {
var cb = null;
var o = { Commit: {} };
if (typeof p1 == 'object') o.Commit.$ = p1;
if (typeof p2 == 'object') o.Commit.$ = p2;
if (typeof p1 == 'function') cb = p1;
if (typeof p2 == 'function') cb = p2;
return this.sendRequest(o, cb);
};
Session.prototype.rollback = function(p1,p2) {
var cb = null;
var o = { Rollback: {} };
if (typeof p1 == 'object') o.Rollback = p1;
if (typeof p2 == 'object') o.Rollback = p2;
if (typeof p1 == 'function') cb = p1;
if (typeof p2 == 'function') cb = p2;
return this.sendRequest(o, cb);
};
Session.prototype.alarmRegister = function(p1,p2) {
var cb = null;
var o = { Alarm: { Register: {} } };
if (typeof p1 == 'object') o.Alarm.Register = p1;
if (typeof p2 == 'object') o.Alarm.Register = p2;
if (typeof p1 == 'function') cb = p1;
if (typeof p2 == 'function') cb = p2;
return this.sendRequest(o, cb);
};
Session.prototype.alarmDeRegister = function(p1,p2) {
var cb = null;
var o = { Alarm: { Register: {} } };
if (typeof p1 == 'object') o.Alarm.Deregister = p1;
if (typeof p2 == 'object') o.Alarm.Deregister = p2;
if (typeof p1 == 'function') cb = p1;
if (typeof p2 == 'function') cb = p2;
return this.sendRequest(o, cb);
};
Session.prototype.getConfigurationHistory = function(p1,p2) {
var cb = null;
var o = { GetConfigurationHistory: {} };
if (typeof p1 == 'object') o.GetConfigurationHistory.$ = p1;
if (typeof p2 == 'object') o.GetConfigurationHistory.$ = p2;
if (typeof p1 == 'function') cb = p1;
if (typeof p2 == 'function') cb = p2;
return this.sendRequest(o, cb);
};
Session.prototype.getConfigurationSessions = function(cb) {
return this.sendRequest({ GetConfigurationSessions: {} }, cb);
};
Session.prototype.lock = function(cb) {
return this.sendRequest({ Lock: {} }, cb);
};
Session.prototype.clear = function(cb) {
return this.sendRequest({ Clear: {} }, cb);
};
Session.prototype.unlock = function(cb) {
return this.sendRequest({ Unlock: {} }, cb);
};
// Abort is just a form of Unlock
Session.prototype.abort = Session.prototype.unlock;
/**
* Converts obj to path and could apply a filter
* @param obj
* @param filter
* @returns {Array}
*/
Session.prototype.obj2path = function(obj,filter) {
var o = [];
var f = filter instanceof RegExp;
if (f) debug('OBJ2PATH conversion with filter %o',filter);
function push(s,v) {
if (f) {
debug('OBJ2PATH test s:%s v:%s is %s',s,v,filter.test(s) || filter.test(v));
if (filter.test(s) || filter.test(v)) return o.push([s,v]);
return o;
}
return o.push([s,v]);
}
function trace(s,p) {
if (p instanceof Array) {
p.forEach(function(n) {
trace(s,n);
});
return o;
}
if (typeof p == 'object') {
if (typeof p['$'] == 'object') {
// Lets extract the attributes
s = s + '('+Object.keys(p['$']).map(function(n) { return '"'+n+'"="'+p['$'][n]+'"'; }).join(",")+')';
}
if (p['_']) {
return push(s,p['_']);
}
var t = Object.keys(p).filter(function(n) { return n!='$' });
if (t.length>0) return t.forEach(function(n) {
if (s)
trace(s+'.'+n,p[n]);
else
trace(n,p[n]);
});
return push(s,'');
}
return push(s,p);
}
trace('',obj);
return o;
};
module.exports = Session;