| 1 |
# (c) 2014 James Cammarata, <[email protected]> |
| 2 |
# |
| 3 |
# This file is part of Ansible |
| 4 |
# |
| 5 |
# Ansible is free software: you can redistribute it and/or modify |
| 6 |
# it under the terms of the GNU General Public License as published by |
| 7 |
# the Free Software Foundation, either version 3 of the License, or |
| 8 |
# (at your option) any later version. |
| 9 |
# |
| 10 |
# Ansible is distributed in the hope that it will be useful, |
| 11 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 13 |
# GNU General Public License for more details. |
| 14 |
# |
| 15 |
# You should have received a copy of the GNU General Public License |
| 16 |
# along with Ansible. If not, see <http://www.gnu.org/licenses/>. |
| 17 |
|
| 18 |
from __future__ import annotations |
| 19 |
|
| 20 |
import codecs |
| 21 |
import re |
| 22 |
|
| 23 |
from ansible.errors import AnsibleParserError |
| 24 |
from ansible.module_utils.common.text.converters import to_text |
| 25 |
from ansible.module_utils._internal._datatag import AnsibleTagHelper |
| 26 |
from ansible._internal._datatag._tags import Origin, TrustedAsTemplate |
| 27 |
from ansible.parsing.quoting import unquote |
| 28 |
|
| 29 |
|
| 30 |
# Decode escapes adapted from rspeer's answer here: |
| 31 |
# http://stackoverflow.com/questions/4020539/process-escape-sequences-in-a-string-in-python |
| 32 |
_HEXCHAR = '[a-fA-F0-9]' |
| 33 |
_ESCAPE_SEQUENCE_RE = re.compile(r""" |
| 34 |
( \\U{0} # 8-digit hex escapes |
| 35 |
| \\u{1} # 4-digit hex escapes |
| 36 |
| \\x{2} # 2-digit hex escapes |
| 37 |
| \\N\{{[^}}]+\}} # Unicode characters by name |
| 38 |
| \\[\\'"abfnrtv] # Single-character escapes |
| 39 |
)""".format(_HEXCHAR * 8, _HEXCHAR * 4, _HEXCHAR * 2), re.UNICODE | re.VERBOSE) |
| 40 |
|
| 41 |
|
| 42 |
def _decode_escapes(s): |
| 43 |
def decode_match(match): |
| 44 |
return codecs.decode(match.group(0), 'unicode-escape') |
| 45 |
|
| 46 |
return _ESCAPE_SEQUENCE_RE.sub(decode_match, s) |
| 47 |
|
| 48 |
|
| 49 |
def parse_kv(args, check_raw=False): |
| 50 |
""" |
| 51 |
Convert a string of key/value items to a dict. If any free-form params |
| 52 |
are found and the check_raw option is set to True, they will be added |
| 53 |
to a new parameter called '_raw_params'. If check_raw is not enabled, |
| 54 |
they will simply be ignored. |
| 55 |
""" |
| 56 |
|
| 57 |
tags = [] |
| 58 |
if origin_tag := Origin.get_tag(args): |
| 59 |
# NB: adjusting the column number is left as an exercise for the reader |
| 60 |
tags.append(origin_tag) |
| 61 |
if trusted_tag := TrustedAsTemplate.get_tag(args): |
| 62 |
tags.append(trusted_tag) |
| 63 |
|
| 64 |
args = to_text(args, nonstring='passthru') |
| 65 |
|
| 66 |
options = {} |
| 67 |
if args is not None: |
| 68 |
vargs = split_args(args) |
| 69 |
|
| 70 |
raw_params = [] |
| 71 |
for orig_x in vargs: |
| 72 |
x = _decode_escapes(orig_x) |
| 73 |
if "=" in x: |
| 74 |
pos = 0 |
| 75 |
try: |
| 76 |
while True: |
| 77 |
pos = x.index('=', pos + 1) |
| 78 |
if pos > 0 and x[pos - 1] != '\\': |
| 79 |
break |
| 80 |
except ValueError: |
| 81 |
# ran out of string, but we must have some escaped equals, |
| 82 |
# so replace those and append this to the list of raw params |
| 83 |
raw_params.append(x.replace('\\=', '=')) |
| 84 |
continue |
| 85 |
|
| 86 |
k = x[:pos] |
| 87 |
v = x[pos + 1:] |
| 88 |
|
| 89 |
# FIXME: make the retrieval of this list of shell/command options a function, so the list is centralized |
| 90 |
if check_raw and k not in ('creates', 'removes', 'chdir', 'executable', 'warn', 'stdin', 'stdin_add_newline', 'strip_empty_ends'): |
| 91 |
raw_params.append(orig_x) |
| 92 |
else: |
| 93 |
options[k.strip()] = unquote(v.strip()) |
| 94 |
else: |
| 95 |
raw_params.append(orig_x) |
| 96 |
|
| 97 |
# recombine the free-form params, if any were found, and assign |
| 98 |
# them to a special option for use later by the shell/command module |
| 99 |
if len(raw_params) > 0: |
| 100 |
options[u'_raw_params'] = join_args(raw_params) |
| 101 |
|
| 102 |
if tags: |
| 103 |
options = {AnsibleTagHelper.tag(k, tags): AnsibleTagHelper.tag(v, tags) for k, v in options.items()} |
| 104 |
|
| 105 |
if origin_tag: |
| 106 |
options = origin_tag.tag(options) |
| 107 |
|
| 108 |
return options |
| 109 |
|
| 110 |
|
| 111 |
def _get_quote_state(token, quote_char): |
| 112 |
""" |
| 113 |
the goal of this block is to determine if the quoted string |
| 114 |
is unterminated in which case it needs to be put back together |
| 115 |
""" |
| 116 |
# the char before the current one, used to see if |
| 117 |
# the current character is escaped |
| 118 |
prev_char = None |
| 119 |
for idx, cur_char in enumerate(token): |
| 120 |
if idx > 0: |
| 121 |
prev_char = token[idx - 1] |
| 122 |
if cur_char in '"\'' and prev_char != '\\': |
| 123 |
if quote_char: |
| 124 |
if cur_char == quote_char: |
| 125 |
quote_char = None |
| 126 |
else: |
| 127 |
quote_char = cur_char |
| 128 |
return quote_char |
| 129 |
|
| 130 |
|
| 131 |
def _count_jinja2_blocks(token, cur_depth, open_token, close_token): |
| 132 |
""" |
| 133 |
this function counts the number of opening/closing blocks for a |
| 134 |
given opening/closing type and adjusts the current depth for that |
| 135 |
block based on the difference |
| 136 |
""" |
| 137 |
num_open = token.count(open_token) |
| 138 |
num_close = token.count(close_token) |
| 139 |
if num_open != num_close: |
| 140 |
cur_depth += (num_open - num_close) |
| 141 |
if cur_depth < 0: |
| 142 |
cur_depth = 0 |
| 143 |
return cur_depth |
| 144 |
|
| 145 |
|
| 146 |
def join_args(s): |
| 147 |
""" |
| 148 |
Join the original cmd based on manipulations by split_args(). |
| 149 |
This retains the original newlines and whitespaces. |
| 150 |
""" |
| 151 |
result = '' |
| 152 |
for p in s: |
| 153 |
if len(result) == 0 or result.endswith('\n'): |
| 154 |
result += p |
| 155 |
else: |
| 156 |
result += ' ' + p |
| 157 |
return result |
| 158 |
|
| 159 |
|
| 160 |
def split_args(args): |
| 161 |
""" |
| 162 |
Splits args on whitespace, but intelligently reassembles |
| 163 |
those that may have been split over a jinja2 block or quotes. |
| 164 |
|
| 165 |
When used in a remote module, we won't ever have to be concerned about |
| 166 |
jinja2 blocks, however this function is/will be used in the |
| 167 |
core portions as well before the args are templated. |
| 168 |
|
| 169 |
example input: a=b c="foo bar" |
| 170 |
example output: ['a=b', 'c="foo bar"'] |
| 171 |
|
| 172 |
Basically this is a variation shlex that has some more intelligence for |
| 173 |
how Ansible needs to use it. |
| 174 |
""" |
| 175 |
|
| 176 |
if not args: |
| 177 |
return [] |
| 178 |
|
| 179 |
# the list of params parsed out of the arg string |
| 180 |
# this is going to be the result value when we are done |
| 181 |
params = [] |
| 182 |
|
| 183 |
# Initial split on newlines |
| 184 |
items = args.split('\n') |
| 185 |
|
| 186 |
# iterate over the tokens, and reassemble any that may have been |
| 187 |
# split on a space inside a jinja2 block. |
| 188 |
# ex if tokens are "{{", "foo", "}}" these go together |
| 189 |
|
| 190 |
# These variables are used |
| 191 |
# to keep track of the state of the parsing, since blocks and quotes |
| 192 |
# may be nested within each other. |
| 193 |
|
| 194 |
quote_char = None |
| 195 |
inside_quotes = False |
| 196 |
print_depth = 0 # used to count nested jinja2 {{ }} blocks |
| 197 |
block_depth = 0 # used to count nested jinja2 {% %} blocks |
| 198 |
comment_depth = 0 # used to count nested jinja2 {# #} blocks |
| 199 |
|
| 200 |
# now we loop over each split chunk, coalescing tokens if the white space |
| 201 |
# split occurred within quotes or a jinja2 block of some kind |
| 202 |
for (itemidx, item) in enumerate(items): |
| 203 |
|
| 204 |
# we split on spaces and newlines separately, so that we |
| 205 |
# can tell which character we split on for reassembly |
| 206 |
# inside quotation characters |
| 207 |
tokens = item.split(' ') |
| 208 |
|
| 209 |
line_continuation = False |
| 210 |
for (idx, token) in enumerate(tokens): |
| 211 |
|
| 212 |
# Empty entries means we have subsequent spaces |
| 213 |
# We want to hold onto them so we can reconstruct them later |
| 214 |
if len(token) == 0 and idx != 0: |
| 215 |
# Make sure there is a params item to store result in. |
| 216 |
if not params: |
| 217 |
params.append('') |
| 218 |
|
| 219 |
params[-1] += ' ' |
| 220 |
continue |
| 221 |
|
| 222 |
# if we hit a line continuation character, but |
| 223 |
# we're not inside quotes, ignore it and continue |
| 224 |
# on to the next token while setting a flag |
| 225 |
if token == '\\' and not inside_quotes: |
| 226 |
line_continuation = True |
| 227 |
continue |
| 228 |
|
| 229 |
# store the previous quoting state for checking later |
| 230 |
was_inside_quotes = inside_quotes |
| 231 |
quote_char = _get_quote_state(token, quote_char) |
| 232 |
inside_quotes = quote_char is not None |
| 233 |
|
| 234 |
# multiple conditions may append a token to the list of params, |
| 235 |
# so we keep track with this flag to make sure it only happens once |
| 236 |
# append means add to the end of the list, don't append means concatenate |
| 237 |
# it to the end of the last token |
| 238 |
appended = False |
| 239 |
|
| 240 |
# if we're inside quotes now, but weren't before, append the token |
| 241 |
# to the end of the list, since we'll tack on more to it later |
| 242 |
# otherwise, if we're inside any jinja2 block, inside quotes, or we were |
| 243 |
# inside quotes (but aren't now) concat this token to the last param |
| 244 |
if inside_quotes and not was_inside_quotes and not (print_depth or block_depth or comment_depth): |
| 245 |
params.append(token) |
| 246 |
appended = True |
| 247 |
elif print_depth or block_depth or comment_depth or inside_quotes or was_inside_quotes: |
| 248 |
if idx == 0 and was_inside_quotes: |
| 249 |
params[-1] = "%s%s" % (params[-1], token) |
| 250 |
else: |
| 251 |
spacer = '' |
| 252 |
if idx > 0: |
| 253 |
spacer = ' ' |
| 254 |
params[-1] = "%s%s%s" % (params[-1], spacer, token) |
| 255 |
appended = True |
| 256 |
|
| 257 |
# if the number of paired block tags is not the same, the depth has changed, so we calculate that here |
| 258 |
# and may append the current token to the params (if we haven't previously done so) |
| 259 |
prev_print_depth = print_depth |
| 260 |
print_depth = _count_jinja2_blocks(token, print_depth, "{{", "}}") |
| 261 |
if print_depth != prev_print_depth and not appended: |
| 262 |
params.append(token) |
| 263 |
appended = True |
| 264 |
|
| 265 |
prev_block_depth = block_depth |
| 266 |
block_depth = _count_jinja2_blocks(token, block_depth, "{%", "%}") |
| 267 |
if block_depth != prev_block_depth and not appended: |
| 268 |
params.append(token) |
| 269 |
appended = True |
| 270 |
|
| 271 |
prev_comment_depth = comment_depth |
| 272 |
comment_depth = _count_jinja2_blocks(token, comment_depth, "{#", "#}") |
| 273 |
if comment_depth != prev_comment_depth and not appended: |
| 274 |
params.append(token) |
| 275 |
appended = True |
| 276 |
|
| 277 |
# finally, if we're at zero depth for all blocks and not inside quotes, and have not |
| 278 |
# yet appended anything to the list of params, we do so now |
| 279 |
if not (print_depth or block_depth or comment_depth) and not inside_quotes and not appended and token != '': |
| 280 |
params.append(token) |
| 281 |
|
| 282 |
# if this was the last token in the list, and we have more than |
| 283 |
# one item (meaning we split on newlines), add a newline back here |
| 284 |
# to preserve the original structure |
| 285 |
if len(items) > 1 and itemidx != len(items) - 1 and not line_continuation: |
| 286 |
# Make sure there is a params item to store result in. |
| 287 |
if not params: |
| 288 |
params.append('') |
| 289 |
|
| 290 |
params[-1] += '\n' |
| 291 |
|
| 292 |
# If we're done and things are not at zero depth or we're still inside quotes, |
| 293 |
# raise an error to indicate that the args were unbalanced |
| 294 |
if print_depth or block_depth or comment_depth or inside_quotes: |
| 295 |
raise AnsibleParserError(u"failed at splitting arguments, either an unbalanced jinja2 block or quotes: {0}".format(args)) |
| 296 |
|
| 297 |
return params |