-
Notifications
You must be signed in to change notification settings - Fork 171
/
wz-xml-file-editor.js
433 lines (402 loc) · 13.7 KB
/
wz-xml-file-editor.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
/*
* Wazuh app - Wazuh XML file editor
* Copyright (C) 2015-2019 Wazuh, Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Find more information about this on the LICENSE file.
*/
import template from './wz-xml-file-editor.html';
import CodeMirror from '../../utils/codemirror/lib/codemirror';
import { uiModules } from 'ui/modules';
const app = uiModules.get('app/wazuh', []);
app.directive('wzXmlFileEditor', function() {
return {
restrict: 'E',
scope: {
fileName: '@fileName',
validFn: '&',
data: '=data',
targetName: '=targetName',
closeFn: '&',
savingParam: '&'
},
controller(
$scope,
$document,
$location,
appState,
errorHandler,
groupHandler,
rulesetHandler,
configHandler,
apiReq,
$rootScope,
$window
) {
const window = $window;
$scope.targetNameShown = $scope.targetName;
$scope.configError = false;
/**
* Custom .replace method. Instead of using .replace which
* evaluates regular expressions.
* Alternative using split + join, same result.
*/
String.prototype.xmlReplace = function(str, newstr) {
return this.split(str).join(newstr);
};
let firstTime = true;
const parser = new DOMParser(); // eslint-disable-line
/**
* Escape "&" characters.
* @param {*} text
*/
const replaceIllegalXML = text => {
const oDOM = parser.parseFromString(text, 'text/html');
const lines = oDOM.documentElement.textContent.split('\n');
for (const line of lines) {
const sanitized = line.trim().xmlReplace('&', '&');
/**
* Do not remove this condition. We don't want to replace
* non-sanitized lines.
*/
if (!line.includes(sanitized)) {
text = text.xmlReplace(line.trim(), sanitized);
}
}
return text;
};
// Block function if there is another check in progress
let checkingXmlError = false;
const checkXmlParseError = () => {
if (checkingXmlError) return;
checkingXmlError = true;
try {
const text = $scope.xmlCodeBox.getValue();
let xml = replaceIllegalXML(text);
xml = xml.replace(/..xml.+\?>/, '');
const xmlDoc = parser.parseFromString(
`<file>${xml}</file>`,
'text/xml'
);
const parsererror = xmlDoc.getElementsByTagName('parsererror');
$scope.validFn({
valid: !!parsererror.length || !xml || !xml.length
});
if (parsererror.length) {
const xmlFullError = parsererror[0].textContent;
$scope.xmlError =
(xmlFullError.match('error\\s.+\n') || [])[0] ||
'Error validating XML';
} else {
$scope.xmlError = false;
}
} catch (error) {
errorHandler.handle(error, 'Error validating XML');
}
checkingXmlError = false;
$scope.$applyAsync();
dynamicHeight();
return;
};
const autoFormat = xml => {
var reg = /(>)\s*(<)(\/*)/g;
var wsexp = / *(.*) +\n/g;
var contexp = /(<.+>)(.+\n)/g;
xml = xml
.replace(reg, '$1\n$2$3')
.replace(wsexp, '$1\n')
.replace(contexp, '$1\n$2');
var formatted = '';
var lines = xml.split('\n');
var indent = 0;
var lastType = 'other';
var transitions = {
'single->single': 0,
'single->closing': -1,
'single->opening': 0,
'single->other': 0,
'closing->single': 0,
'closing->closing': -1,
'closing->opening': 0,
'closing->other': 0,
'opening->single': 1,
'opening->closing': 0,
'opening->opening': 1,
'opening->other': 1,
'other->single': 0,
'other->closing': -1,
'other->opening': 0,
'other->other': 0
};
for (var i = 0; i < lines.length; i++) {
var ln = lines[i];
if (ln.match(/\s*<\?xml/)) {
formatted += ln + '\n';
continue;
}
var single = Boolean(ln.match(/<.+\/>/)); // is this line a single tag? ex. <br />
var closing = Boolean(ln.match(/<\/.+>/)); // is this a closing tag? ex. </a>
var opening = Boolean(ln.match(/<[^!].*>/)); // is this even a tag (that's not <!something>)
var type = single
? 'single'
: closing
? 'closing'
: opening
? 'opening'
: 'other';
var fromTo = lastType + '->' + type;
lastType = type;
var padding = '';
indent += transitions[fromTo];
for (var j = 0; j < indent; j++) {
padding += '\t';
}
if (fromTo == 'opening->closing')
formatted = formatted.substr(0, formatted.length - 1) + ln + '\n';
// substr removes line break (\n) from prev loop
else formatted += padding + ln + '\n';
}
return formatted.trim();
};
const validateAfterSent = async (node = false) => {
$scope.configError = false;
try {
const clusterStatus = await apiReq.request(
'GET',
`/cluster/status`,
{}
);
const clusterData = ((clusterStatus || {}).data || {}).data || {};
const isCluster =
clusterData.enabled === 'yes' && clusterData.running === 'yes';
let validation = false;
if (node && isCluster) {
validation = await apiReq.request(
'GET',
`/cluster/${node}/configuration/validation`,
{}
);
} else {
validation = isCluster
? await apiReq.request(
'GET',
`/cluster/configuration/validation`,
{}
)
: await apiReq.request(
'GET',
`/manager/configuration/validation`,
{}
);
}
const data = ((validation || {}).data || {}).data || {};
const isOk = data.status === 'OK';
if (!isOk && Array.isArray(data.details)) {
$scope.configError = data.details;
$scope.$applyAsync();
dynamicHeight();
throw new Error('Validation error');
}
return true;
} catch (error) {
return Promise.reject(error);
}
};
const saveFile = async params => {
let close = true;
const warnMsg =
'File has been updated, but there are errors in the configuration';
try {
const text = $scope.xmlCodeBox.getValue();
const xml = replaceIllegalXML(text);
if (params.group) {
close = false;
await groupHandler.sendConfiguration(params.group, xml);
try {
await validateAfterSent(false);
} catch (err) {
params.showRestartManager = 'warn';
}
const msg = 'Success. Group has been updated';
params.showRestartManager
? params.showRestartManager !== 'warn'
? showRestartMessage(msg, params.showRestartManager)
: errorHandler.handle(warnMsg, '', true)
: errorHandler.info(msg);
} else if (params.rule) {
close = false;
await rulesetHandler.sendRuleConfiguration(
params.rule,
xml,
params.isNewFile && !params.isOverwrite
);
try {
await validateAfterSent(false);
} catch (err) {
params.showRestartManager = 'warn';
}
const msg = 'Success. Rules updated';
params.showRestartManager
? params.showRestartManager !== 'warn'
? showRestartMessage(msg, params.showRestartManager)
: errorHandler.handle(warnMsg, '', true)
: errorHandler.info(msg);
} else if (params.decoder) {
close = false;
await rulesetHandler.sendDecoderConfiguration(
params.decoder,
xml,
params.isNewFile && !params.isOverwrite
);
try {
await validateAfterSent(false);
} catch (err) {
params.showRestartManager = 'warn';
}
const msg = 'Success. Decoders has been updated';
params.showRestartManager
? params.showRestartManager !== 'warn'
? showRestartMessage(msg, params.showRestartManager)
: errorHandler.handle(warnMsg, '', true)
: errorHandler.info(msg);
} else if (params.node) {
close = false;
await configHandler.saveNodeConfiguration(params.node, xml);
try {
await validateAfterSent(params.node);
} catch (err) {
params.showRestartManager = 'warn';
}
const msg = `Success. Node (${
params.node
}) configuration has been updated`;
params.showRestartManager
? params.showRestartManager !== 'warn'
? showRestartMessage(msg, params.node)
: errorHandler.handle(warnMsg, '', true)
: errorHandler.info(msg);
} else if (params.manager) {
await configHandler.saveManagerConfiguration(xml);
try {
await validateAfterSent(false);
} catch (err) {
params.showRestartManager = 'warn';
}
const msg = 'Success. Manager configuration has been updated';
params.showRestartManager
? params.showRestartManager !== 'warn'
? showRestartMessage(msg, params.showRestartManager)
: errorHandler.handle(warnMsg, '', true)
: errorHandler.info(msg);
}
$scope.savingParam();
if (close) $scope.closeFn({ reload: true });
} catch (error) {
$scope.savingParam();
if ((error || '').includes('Wazuh API error: 1905')) {
$scope.configError = ['File name already exists'];
$scope.$emit('showSaveAndOverwrite', {});
} else {
errorHandler.handle(error, 'Error');
}
}
return;
};
$scope.xmlCodeBox = CodeMirror.fromTextArea(
$document[0].getElementById('xml_box'),
{
lineNumbers: true,
lineWrapping: true,
matchClosing: true,
matchBrackets: true,
mode: 'text/xml',
theme: 'ttcn',
foldGutter: true,
styleSelectedText: true,
gutters: ['CodeMirror-foldgutter']
}
);
$(window).on('resize', function() {
dynamicHeight();
});
const dynamicHeight = () => {
setTimeout(function() {
const editorContainer = $('.wzXmlEditor');
const headerContainer = $('#wzXmlEditorHeader');
const windows = $(window).height();
const offsetTop = getPosition(editorContainer[0]).y;
editorContainer.height(windows - (offsetTop + 20));
$('.wzXmlEditorBody .CodeMirror').css({
height: 'calc(100% - ' + (headerContainer.height() - 22) + 'px)'
});
}, 1);
};
const init = (data = false) => {
try {
$('.wzXmlEditor').height(0);
$scope.xmlError = false;
dynamicHeight();
$scope.xmlCodeBox.setValue(autoFormat(data || $scope.data));
firstTime = false;
setTimeout(() => {
$scope.xmlCodeBox.refresh();
}, 1);
} catch (error) {
errorHandler.handle(error, 'Fetching original file');
}
};
init();
// Refresh content if it's not the very first time we are loading data
$scope.$on('fetchedFile', (ev, params) => {
if (!firstTime) {
init(params.data);
}
});
$scope.xmlCodeBox.on('change', () => {
checkXmlParseError();
});
$scope.doRestart = () => {
$scope.restartBtn = false;
$scope.$emit('performRestart', {});
};
const showRestartMessage = async (msg, target) => {
errorHandler.info(msg);
$scope.restartBtn = true;
$scope.$applyAsync();
$scope.$emit('showRestartBtn', { msg, target });
dynamicHeight();
};
$scope.$on('saveXmlFile', (ev, params) => saveFile(params));
$scope.$on('removeRestartMsg', () => {
$scope.restartBtn = false;
$scope.$applyAsync();
dynamicHeight();
});
$rootScope.$on('changedInputFileName', (ev, params) => {
$scope.targetNameShown = params.name;
$scope.$applyAsync();
});
$scope.$on('$destroy', function() {
$location.search('editingFile', null);
appState.setNavigation({ status: true });
});
function getPosition(element) {
var xPosition = 0;
var yPosition = 0;
while (element) {
xPosition +=
element.offsetLeft - element.scrollLeft + element.clientLeft;
yPosition +=
element.offsetTop - element.scrollTop + element.clientTop;
element = element.offsetParent;
}
return { x: xPosition, y: yPosition };
}
},
template
};
});