luci-base: fix host validation function
[project/luci.git] / modules / luci-base / htdocs / luci-static / resources / validation.js
1 'use strict';
2 'require baseclass';
3
4 var Validator = baseclass.extend({
5 __name__: 'Validation',
6
7 __init__: function(field, type, optional, vfunc, validatorFactory) {
8 this.field = field;
9 this.optional = optional;
10 this.vfunc = vfunc;
11 this.vstack = validatorFactory.compile(type);
12 this.factory = validatorFactory;
13 },
14
15 assert: function(condition, message) {
16 if (!condition) {
17 this.field.classList.add('cbi-input-invalid');
18 this.error = message;
19 return false;
20 }
21
22 this.field.classList.remove('cbi-input-invalid');
23 this.error = null;
24 return true;
25 },
26
27 apply: function(name, value, args) {
28 var func;
29
30 if (typeof(name) === 'function')
31 func = name;
32 else if (typeof(this.factory.types[name]) === 'function')
33 func = this.factory.types[name];
34 else
35 return false;
36
37 if (value != null)
38 this.value = value;
39
40 return func.apply(this, args);
41 },
42
43 validate: function() {
44 /* element is detached */
45 if (!findParent(this.field, 'body') && !findParent(this.field, '[data-field]'))
46 return true;
47
48 this.field.classList.remove('cbi-input-invalid');
49 this.value = (this.field.value != null) ? this.field.value : '';
50 this.error = null;
51
52 var valid;
53
54 if (this.value.length === 0)
55 valid = this.assert(this.optional, _('non-empty value'));
56 else
57 valid = this.vstack[0].apply(this, this.vstack[1]);
58
59 if (valid !== true) {
60 this.field.setAttribute('data-tooltip', _('Expecting: %s').format(this.error));
61 this.field.setAttribute('data-tooltip-style', 'error');
62 this.field.dispatchEvent(new CustomEvent('validation-failure', { bubbles: true }));
63 return false;
64 }
65
66 if (typeof(this.vfunc) == 'function')
67 valid = this.vfunc(this.value);
68
69 if (valid !== true) {
70 this.assert(false, valid);
71 this.field.setAttribute('data-tooltip', valid);
72 this.field.setAttribute('data-tooltip-style', 'error');
73 this.field.dispatchEvent(new CustomEvent('validation-failure', { bubbles: true }));
74 return false;
75 }
76
77 this.field.removeAttribute('data-tooltip');
78 this.field.removeAttribute('data-tooltip-style');
79 this.field.dispatchEvent(new CustomEvent('validation-success', { bubbles: true }));
80 return true;
81 },
82
83 });
84
85 var ValidatorFactory = baseclass.extend({
86 __name__: 'ValidatorFactory',
87
88 create: function(field, type, optional, vfunc) {
89 return new Validator(field, type, optional, vfunc, this);
90 },
91
92 compile: function(code) {
93 var pos = 0;
94 var esc = false;
95 var depth = 0;
96 var stack = [ ];
97
98 code += ',';
99
100 for (var i = 0; i < code.length; i++) {
101 if (esc) {
102 esc = false;
103 continue;
104 }
105
106 switch (code.charCodeAt(i))
107 {
108 case 92:
109 esc = true;
110 break;
111
112 case 40:
113 case 44:
114 if (depth <= 0) {
115 if (pos < i) {
116 var label = code.substring(pos, i);
117 label = label.replace(/\\(.)/g, '$1');
118 label = label.replace(/^[ \t]+/g, '');
119 label = label.replace(/[ \t]+$/g, '');
120
121 if (label && !isNaN(label)) {
122 stack.push(parseFloat(label));
123 }
124 else if (label.match(/^(['"]).*\1$/)) {
125 stack.push(label.replace(/^(['"])(.*)\1$/, '$2'));
126 }
127 else if (typeof this.types[label] == 'function') {
128 stack.push(this.types[label]);
129 stack.push(null);
130 }
131 else {
132 L.raise('SyntaxError', 'Unhandled token "%s"', label);
133 }
134 }
135
136 pos = i+1;
137 }
138
139 depth += (code.charCodeAt(i) == 40);
140 break;
141
142 case 41:
143 if (--depth <= 0) {
144 if (typeof stack[stack.length-2] != 'function')
145 L.raise('SyntaxError', 'Argument list follows non-function');
146
147 stack[stack.length-1] = this.compile(code.substring(pos, i));
148 pos = i+1;
149 }
150
151 break;
152 }
153 }
154
155 return stack;
156 },
157
158 parseInteger: function(x) {
159 return (/^-?\d+$/.test(x) ? +x : NaN);
160 },
161
162 parseDecimal: function(x) {
163 return (/^-?\d+(?:\.\d+)?$/.test(x) ? +x : NaN);
164 },
165
166 parseIPv4: function(x) {
167 if (!x.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/))
168 return null;
169
170 if (RegExp.$1 > 255 || RegExp.$2 > 255 || RegExp.$3 > 255 || RegExp.$4 > 255)
171 return null;
172
173 return [ +RegExp.$1, +RegExp.$2, +RegExp.$3, +RegExp.$4 ];
174 },
175
176 parseIPv6: function(x) {
177 if (x.match(/^([a-fA-F0-9:]+):(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/)) {
178 var v6 = RegExp.$1, v4 = this.parseIPv4(RegExp.$2);
179
180 if (!v4)
181 return null;
182
183 x = v6 + ':' + (v4[0] * 256 + v4[1]).toString(16)
184 + ':' + (v4[2] * 256 + v4[3]).toString(16);
185 }
186
187 if (!x.match(/^[a-fA-F0-9:]+$/))
188 return null;
189
190 var prefix_suffix = x.split(/::/);
191
192 if (prefix_suffix.length > 2)
193 return null;
194
195 var prefix = (prefix_suffix[0] || '0').split(/:/);
196 var suffix = prefix_suffix.length > 1 ? (prefix_suffix[1] || '0').split(/:/) : [];
197
198 if (suffix.length ? (prefix.length + suffix.length > 7)
199 : ((prefix_suffix.length < 2 && prefix.length < 8) || prefix.length > 8))
200 return null;
201
202 var i, word;
203 var words = [];
204
205 for (i = 0, word = parseInt(prefix[0], 16); i < prefix.length; word = parseInt(prefix[++i], 16))
206 if (prefix[i].length <= 4 && !isNaN(word) && word <= 0xFFFF)
207 words.push(word);
208 else
209 return null;
210
211 for (i = 0; i < (8 - prefix.length - suffix.length); i++)
212 words.push(0);
213
214 for (i = 0, word = parseInt(suffix[0], 16); i < suffix.length; word = parseInt(suffix[++i], 16))
215 if (suffix[i].length <= 4 && !isNaN(word) && word <= 0xFFFF)
216 words.push(word);
217 else
218 return null;
219
220 return words;
221 },
222
223 types: {
224 integer: function() {
225 return this.assert(!isNaN(this.factory.parseInteger(this.value)), _('valid integer value'));
226 },
227
228 uinteger: function() {
229 return this.assert(this.factory.parseInteger(this.value) >= 0, _('positive integer value'));
230 },
231
232 float: function() {
233 return this.assert(!isNaN(this.factory.parseDecimal(this.value)), _('valid decimal value'));
234 },
235
236 ufloat: function() {
237 return this.assert(this.factory.parseDecimal(this.value) >= 0, _('positive decimal value'));
238 },
239
240 ipaddr: function(nomask) {
241 return this.assert(this.apply('ip4addr', null, [nomask]) || this.apply('ip6addr', null, [nomask]),
242 nomask ? _('valid IP address') : _('valid IP address or prefix'));
243 },
244
245 ip4addr: function(nomask) {
246 var re = nomask ? /^(\d+\.\d+\.\d+\.\d+)$/ : /^(\d+\.\d+\.\d+\.\d+)(?:\/(\d+\.\d+\.\d+\.\d+)|\/(\d{1,2}))?$/,
247 m = this.value.match(re);
248
249 return this.assert(m && this.factory.parseIPv4(m[1]) && (m[2] ? this.factory.parseIPv4(m[2]) : (m[3] ? this.apply('ip4prefix', m[3]) : true)),
250 nomask ? _('valid IPv4 address') : _('valid IPv4 address or network'));
251 },
252
253 ip6addr: function(nomask) {
254 var re = nomask ? /^([0-9a-fA-F:.]+)$/ : /^([0-9a-fA-F:.]+)(?:\/(\d{1,3}))?$/,
255 m = this.value.match(re);
256
257 return this.assert(m && this.factory.parseIPv6(m[1]) && (m[2] ? this.apply('ip6prefix', m[2]) : true),
258 nomask ? _('valid IPv6 address') : _('valid IPv6 address or prefix'));
259 },
260
261 ip4prefix: function() {
262 return this.assert(!isNaN(this.value) && this.value >= 0 && this.value <= 32,
263 _('valid IPv4 prefix value (0-32)'));
264 },
265
266 ip6prefix: function() {
267 return this.assert(!isNaN(this.value) && this.value >= 0 && this.value <= 128,
268 _('valid IPv6 prefix value (0-128)'));
269 },
270
271 cidr: function() {
272 return this.assert(this.apply('cidr4') || this.apply('cidr6'), _('valid IPv4 or IPv6 CIDR'));
273 },
274
275 cidr4: function() {
276 var m = this.value.match(/^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\/(\d{1,2})$/);
277 return this.assert(m && this.factory.parseIPv4(m[1]) && this.apply('ip4prefix', m[2]), _('valid IPv4 CIDR'));
278 },
279
280 cidr6: function() {
281 var m = this.value.match(/^([0-9a-fA-F:.]+)\/(\d{1,3})$/);
282 return this.assert(m && this.factory.parseIPv6(m[1]) && this.apply('ip6prefix', m[2]), _('valid IPv6 CIDR'));
283 },
284
285 ipnet4: function() {
286 var m = this.value.match(/^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/);
287 return this.assert(m && this.factory.parseIPv4(m[1]) && this.factory.parseIPv4(m[2]), _('IPv4 network in address/netmask notation'));
288 },
289
290 ipnet6: function() {
291 var m = this.value.match(/^([0-9a-fA-F:.]+)\/([0-9a-fA-F:.]+)$/);
292 return this.assert(m && this.factory.parseIPv6(m[1]) && this.factory.parseIPv6(m[2]), _('IPv6 network in address/netmask notation'));
293 },
294
295 ip6hostid: function() {
296 if (this.value == "eui64" || this.value == "random")
297 return true;
298
299 var v6 = this.factory.parseIPv6(this.value);
300 return this.assert(!(!v6 || v6[0] || v6[1] || v6[2] || v6[3]), _('valid IPv6 host id'));
301 },
302
303 ipmask: function() {
304 return this.assert(this.apply('ipmask4') || this.apply('ipmask6'),
305 _('valid network in address/netmask notation'));
306 },
307
308 ipmask4: function() {
309 return this.assert(this.apply('cidr4') || this.apply('ipnet4') || this.apply('ip4addr'),
310 _('valid IPv4 network'));
311 },
312
313 ipmask6: function() {
314 return this.assert(this.apply('cidr6') || this.apply('ipnet6') || this.apply('ip6addr'),
315 _('valid IPv6 network'));
316 },
317
318 port: function() {
319 var p = this.factory.parseInteger(this.value);
320 return this.assert(p >= 0 && p <= 65535, _('valid port value'));
321 },
322
323 portrange: function() {
324 if (this.value.match(/^(\d+)-(\d+)$/)) {
325 var p1 = +RegExp.$1;
326 var p2 = +RegExp.$2;
327 return this.assert(p1 <= p2 && p2 <= 65535,
328 _('valid port or port range (port1-port2)'));
329 }
330
331 return this.assert(this.apply('port'), _('valid port or port range (port1-port2)'));
332 },
333
334 macaddr: function() {
335 return this.assert(this.value.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null,
336 _('valid MAC address'));
337 },
338
339 host: function(ipv4only) {
340 return this.assert(this.apply('hostname') || this.apply(ipv4only == 1 ? 'ip4addr' : 'ipaddr', null, ['nomask']),
341 _('valid hostname or IP address'));
342 },
343
344 hostname: function(strict) {
345 if (this.value.length <= 253)
346 return this.assert(
347 (this.value.match(/^[a-zA-Z0-9_]+$/) != null ||
348 (this.value.match(/^[a-zA-Z0-9_][a-zA-Z0-9_\-.]*[a-zA-Z0-9]$/) &&
349 this.value.match(/[^0-9.]/))) &&
350 (!strict || !this.value.match(/^_/)),
351 _('valid hostname'));
352
353 return this.assert(false, _('valid hostname'));
354 },
355
356 network: function() {
357 return this.assert(this.apply('uciname') || this.apply('host'),
358 _('valid UCI identifier, hostname or IP address'));
359 },
360
361 hostport: function(ipv4only) {
362 var hp = this.value.split(/:/);
363 return this.assert(hp.length == 2 && this.apply('host', hp[0], [ipv4only]) && this.apply('port', hp[1]),
364 _('valid host:port'));
365 },
366
367 ip4addrport: function() {
368 var hp = this.value.split(/:/);
369 return this.assert(hp.length == 2 && this.apply('ip4addr', hp[0], [true]) && this.apply('port', hp[1]),
370 _('valid IPv4 address:port'));
371 },
372
373 ipaddrport: function(bracket) {
374 var m4 = this.value.match(/^([^\[\]:]+):(\d+)$/),
375 m6 = this.value.match((bracket == 1) ? /^\[(.+)\]:(\d+)$/ : /^([^\[\]]+):(\d+)$/);
376
377 if (m4)
378 return this.assert(this.apply('ip4addr', m4[1], [true]) && this.apply('port', m4[2]),
379 _('valid address:port'));
380
381 return this.assert(m6 && this.apply('ip6addr', m6[1], [true]) && this.apply('port', m6[2]),
382 _('valid address:port'));
383 },
384
385 wpakey: function() {
386 var v = this.value;
387
388 if (v.length == 64)
389 return this.assert(v.match(/^[a-fA-F0-9]{64}$/), _('valid hexadecimal WPA key'));
390
391 return this.assert((v.length >= 8) && (v.length <= 63), _('key between 8 and 63 characters'));
392 },
393
394 wepkey: function() {
395 var v = this.value;
396
397 if (v.substr(0, 2) === 's:')
398 v = v.substr(2);
399
400 if ((v.length == 10) || (v.length == 26))
401 return this.assert(v.match(/^[a-fA-F0-9]{10,26}$/), _('valid hexadecimal WEP key'));
402
403 return this.assert((v.length === 5) || (v.length === 13), _('key with either 5 or 13 characters'));
404 },
405
406 uciname: function() {
407 return this.assert(this.value.match(/^[a-zA-Z0-9_]+$/), _('valid UCI identifier'));
408 },
409
410 range: function(min, max) {
411 var val = this.factory.parseDecimal(this.value);
412 return this.assert(val >= +min && val <= +max, _('value between %f and %f').format(min, max));
413 },
414
415 min: function(min) {
416 return this.assert(this.factory.parseDecimal(this.value) >= +min, _('value greater or equal to %f').format(min));
417 },
418
419 max: function(max) {
420 return this.assert(this.factory.parseDecimal(this.value) <= +max, _('value smaller or equal to %f').format(max));
421 },
422
423 length: function(len) {
424 var val = '' + this.value;
425 return this.assert(val.length == +len,
426 _('value with %d characters').format(len));
427 },
428
429 rangelength: function(min, max) {
430 var val = '' + this.value;
431 return this.assert((val.length >= +min) && (val.length <= +max),
432 _('value between %d and %d characters').format(min, max));
433 },
434
435 minlength: function(min) {
436 return this.assert((''+this.value).length >= +min,
437 _('value with at least %d characters').format(min));
438 },
439
440 maxlength: function(max) {
441 return this.assert((''+this.value).length <= +max,
442 _('value with at most %d characters').format(max));
443 },
444
445 or: function() {
446 var errors = [];
447
448 for (var i = 0; i < arguments.length; i += 2) {
449 if (typeof arguments[i] != 'function') {
450 if (arguments[i] == this.value)
451 return this.assert(true);
452 errors.push('"%s"'.format(arguments[i]));
453 i--;
454 }
455 else if (arguments[i].apply(this, arguments[i+1])) {
456 return this.assert(true);
457 }
458 else {
459 errors.push(this.error);
460 }
461 }
462
463 var t = _('One of the following: %s');
464
465 return this.assert(false, t.format('\n - ' + errors.join('\n - ')));
466 },
467
468 and: function() {
469 for (var i = 0; i < arguments.length; i += 2) {
470 if (typeof arguments[i] != 'function') {
471 if (arguments[i] != this.value)
472 return this.assert(false, '"%s"'.format(arguments[i]));
473 i--;
474 }
475 else if (!arguments[i].apply(this, arguments[i+1])) {
476 return this.assert(false, this.error);
477 }
478 }
479
480 return this.assert(true);
481 },
482
483 neg: function() {
484 this.value = this.value.replace(/^[ \t]*![ \t]*/, '');
485
486 if (arguments[0].apply(this, arguments[1]))
487 return this.assert(true);
488
489 return this.assert(false, _('Potential negation of: %s').format(this.error));
490 },
491
492 list: function(subvalidator, subargs) {
493 this.field.setAttribute('data-is-list', 'true');
494
495 var tokens = this.value.match(/[^ \t]+/g);
496 for (var i = 0; i < tokens.length; i++)
497 if (!this.apply(subvalidator, tokens[i], subargs))
498 return this.assert(false, this.error);
499
500 return this.assert(true);
501 },
502
503 phonedigit: function() {
504 return this.assert(this.value.match(/^[0-9\*#!\.]+$/),
505 _('valid phone digit (0-9, "*", "#", "!" or ".")'));
506 },
507
508 timehhmmss: function() {
509 return this.assert(this.value.match(/^[0-6][0-9]:[0-6][0-9]:[0-6][0-9]$/),
510 _('valid time (HH:MM:SS)'));
511 },
512
513 dateyyyymmdd: function() {
514 if (this.value.match(/^(\d\d\d\d)-(\d\d)-(\d\d)/)) {
515 var year = +RegExp.$1,
516 month = +RegExp.$2,
517 day = +RegExp.$3,
518 days_in_month = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
519
520 var is_leap_year = function(year) {
521 return ((!(year % 4) && (year % 100)) || !(year % 400));
522 }
523
524 var get_days_in_month = function(month, year) {
525 return (month === 2 && is_leap_year(year)) ? 29 : days_in_month[month - 1];
526 }
527
528 /* Firewall rules in the past don't make sense */
529 return this.assert(year >= 2015 && month && month <= 12 && day && day <= get_days_in_month(month, year),
530 _('valid date (YYYY-MM-DD)'));
531
532 }
533
534 return this.assert(false, _('valid date (YYYY-MM-DD)'));
535 },
536
537 unique: function(subvalidator, subargs) {
538 var ctx = this,
539 option = findParent(ctx.field, '[data-widget][data-name]'),
540 section = findParent(option, '.cbi-section'),
541 query = '[data-widget="%s"][data-name="%s"]'.format(option.getAttribute('data-widget'), option.getAttribute('data-name')),
542 unique = true;
543
544 section.querySelectorAll(query).forEach(function(sibling) {
545 if (sibling === option)
546 return;
547
548 var input = sibling.querySelector('[data-type]'),
549 values = input ? (input.getAttribute('data-is-list') ? input.value.match(/[^ \t]+/g) : [ input.value ]) : null;
550
551 if (values !== null && values.indexOf(ctx.value) !== -1)
552 unique = false;
553 });
554
555 if (!unique)
556 return this.assert(false, _('unique value'));
557
558 if (typeof(subvalidator) === 'function')
559 return this.apply(subvalidator, null, subargs);
560
561 return this.assert(true);
562 },
563
564 hexstring: function() {
565 return this.assert(this.value.match(/^([a-f0-9][a-f0-9]|[A-F0-9][A-F0-9])+$/),
566 _('hexadecimal encoded value'));
567 },
568
569 string: function() {
570 return true;
571 }
572 }
573 });
574
575 return ValidatorFactory;