1#!/usr/bin/env python
2#coding=utf-8
3
4#
5# Copyright (c) 2023-2024 Huawei Device Co., Ltd.
6# Licensed under the Apache License, Version 2.0 (the "License");
7# you may not use this file except in compliance with the License.
8# You may obtain a copy of the License at
9#
10#     http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS,
14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17#
18
19from .base_rule import BaseRule
20
21
22class SystemParameterRule(BaseRule):
23    RULE_NAME = "NO-Config-SystemParameter-In-INIT"
24    CONFIG_DAC_MAX_NUM = 200
25
26    def __check__(self):
27        return self._check_param_in_init()
28
29    def _check_param_name(self, param_name, empty_flag):
30        # len: (0, 96]
31        # Only allow alphanumeric, plus '.', '-', '@', ':', or '_'/
32        # Don't allow ".." to appear in a param name
33        if len(param_name) > 96 or len(param_name) < 1 or param_name[0] == '.' or '..' in param_name:
34            return False
35
36        if empty_flag is False:
37            if param_name[-1] == '.':
38                return False
39
40        if param_name == "#":
41            return True
42
43        for char_value in param_name:
44            if char_value in '._-@:':
45                continue
46
47            if char_value.isalnum():
48                continue
49            return False
50        return True
51
52    def _check_param_in_init(self):
53        passed = True
54        value_empty_flag = True
55        white_list = self.get_white_lists()
56        parser = self.get_mgr().get_parser_by_name('system_parameter_parser')
57        counts = 0
58        for key, item in parser._parameters.items():
59            if (item.get("dacMode") != 0):
60                counts += 1
61            if str(item)[-1] == "=":
62                value_empty_flag = True
63            else:
64                value_empty_flag = False
65
66            if not self._check_param_name(key, value_empty_flag):
67                self.error("Invalid param: %s" % key)
68                continue
69            if key in white_list:
70                continue
71        if counts > SystemParameterRule.CONFIG_DAC_MAX_NUM:
72            self.error("DAC overallocated memory")
73            passed = False
74        return passed
75