| 1 |
# Copyright 2018 Nitin Kumar |
| 2 |
|
| 3 |
# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
# you may not use this file except in compliance with the License. |
| 5 |
# You may obtain a copy of the License at |
| 6 |
# |
| 7 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
# |
| 9 |
# Unless required by applicable law or agreed to in writing, software |
| 10 |
# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
# See the License for the specific language governing permissions and |
| 13 |
# limitations under the License. |
| 14 |
|
| 15 |
|
| 16 |
import os |
| 17 |
import sys |
| 18 |
import re |
| 19 |
|
| 20 |
try: |
| 21 |
import selectors |
| 22 |
except ImportError: |
| 23 |
import selectors2 as selectors |
| 24 |
|
| 25 |
from io import BytesIO as StringIO |
| 26 |
from xml.sax.handler import ContentHandler |
| 27 |
|
| 28 |
from ncclient.transport.errors import NetconfFramingError |
| 29 |
from ncclient.transport.session import NetconfBase |
| 30 |
from ncclient.logging_ import SessionLoggerAdapter |
| 31 |
from ncclient.operations.errors import OperationError |
| 32 |
from ncclient.transport import SessionListener |
| 33 |
|
| 34 |
import logging |
| 35 |
logger = logging.getLogger("ncclient.transport.parser") |
| 36 |
|
| 37 |
|
| 38 |
PORT_NETCONF_DEFAULT = 830 |
| 39 |
PORT_SSH_DEFAULT = 22 |
| 40 |
|
| 41 |
BUF_SIZE = 4096 |
| 42 |
# v1.0: RFC 4742 |
| 43 |
MSG_DELIM = "]]>]]>" |
| 44 |
MSG_DELIM_LEN = len(MSG_DELIM) |
| 45 |
# v1.1: RFC 6242 |
| 46 |
END_DELIM = '\n##\n' |
| 47 |
|
| 48 |
TICK = 0.1 |
| 49 |
|
| 50 |
# |
| 51 |
# Define delimiters for chunks and messages for netconf 1.1 chunk enoding. |
| 52 |
# When matched: |
| 53 |
# |
| 54 |
# * result.group(0) will contain whole matched string |
| 55 |
# * result.group(1) will contain the digit string for a chunk |
| 56 |
# * result.group(2) will be defined if '##' found |
| 57 |
# |
| 58 |
RE_NC11_DELIM = re.compile(r'\n(?:#([0-9]+)|(##))\n') |
| 59 |
|
| 60 |
def textify(buf): |
| 61 |
return buf.decode('UTF-8') |
| 62 |
|
| 63 |
|
| 64 |
class SAXParserHandler(SessionListener): |
| 65 |
|
| 66 |
def __init__(self, session): |
| 67 |
self._session = session |
| 68 |
|
| 69 |
def callback(self, root, raw): |
| 70 |
if type(self._session.parser) == DefaultXMLParser: |
| 71 |
self._session.parser = self._session._device_handler.get_xml_parser(self._session) |
| 72 |
|
| 73 |
def errback(self, _): |
| 74 |
pass |
| 75 |
|
| 76 |
|
| 77 |
class SAXFilterXMLNotFoundError(OperationError): |
| 78 |
def __init__(self, rpc_listener): |
| 79 |
self._listener = rpc_listener |
| 80 |
|
| 81 |
def __str__(self): |
| 82 |
return "SAX filter input xml not provided for listener: %s" % self._listener |
| 83 |
|
| 84 |
|
| 85 |
class DefaultXMLParser: |
| 86 |
|
| 87 |
def __init__(self, session): |
| 88 |
""" |
| 89 |
DOM Parser |
| 90 |
|
| 91 |
:param session: ssh session object |
| 92 |
""" |
| 93 |
self._session = session |
| 94 |
self._parsing_pos10 = 0 |
| 95 |
self.logger = SessionLoggerAdapter(logger, {'session': self._session}) |
| 96 |
|
| 97 |
def parse(self, data): |
| 98 |
""" |
| 99 |
parse incoming RPC response from networking device. |
| 100 |
|
| 101 |
:param data: incoming RPC data from device |
| 102 |
:return: None |
| 103 |
""" |
| 104 |
if data: |
| 105 |
self._session._buffer.seek(0, os.SEEK_END) |
| 106 |
self._session._buffer.write(data) |
| 107 |
if self._session._base == NetconfBase.BASE_11: |
| 108 |
self._parse11() |
| 109 |
else: |
| 110 |
self._parse10() |
| 111 |
|
| 112 |
def _parse10(self): |
| 113 |
|
| 114 |
"""Messages are delimited by MSG_DELIM. The buffer could have grown by |
| 115 |
a maximum of BUF_SIZE bytes everytime this method is called. Retains |
| 116 |
state across method calls and if a chunk has been read it will not be |
| 117 |
considered again.""" |
| 118 |
|
| 119 |
self.logger.debug("parsing netconf v1.0") |
| 120 |
buf = self._session._buffer |
| 121 |
buf.seek(self._parsing_pos10) |
| 122 |
if MSG_DELIM in buf.read().decode('UTF-8'): |
| 123 |
buf.seek(0) |
| 124 |
msg, _, remaining = buf.read().decode('UTF-8').partition(MSG_DELIM) |
| 125 |
msg = msg.strip() |
| 126 |
self._session._dispatch_message(msg) |
| 127 |
self._session._buffer = StringIO() |
| 128 |
self._parsing_pos10 = 0 |
| 129 |
if len(remaining.strip()) > 0: |
| 130 |
# There could be another entire message in the |
| 131 |
# buffer, so we should try to parse again. |
| 132 |
if type(self._session.parser) != DefaultXMLParser: |
| 133 |
self.logger.debug('send remaining data to SAX parser') |
| 134 |
self._session.parser.parse(remaining.encode()) |
| 135 |
else: |
| 136 |
self.logger.debug('Trying another round of parsing since there is still data') |
| 137 |
self._session._buffer.write(remaining.encode()) |
| 138 |
self._parse10() |
| 139 |
else: |
| 140 |
# handle case that MSG_DELIM is split over two chunks |
| 141 |
self._parsing_pos10 = buf.tell() - MSG_DELIM_LEN |
| 142 |
if self._parsing_pos10 < 0: |
| 143 |
self._parsing_pos10 = 0 |
| 144 |
|
| 145 |
def _parse11(self): |
| 146 |
|
| 147 |
"""Messages are split into chunks. Chunks and messages are delimited |
| 148 |
by the regex #RE_NC11_DELIM defined earlier in this file. Each |
| 149 |
time we get called here either a chunk delimiter or an |
| 150 |
end-of-message delimiter should be found iff there is enough |
| 151 |
data. If there is not enough data, we will wait for more. If a |
| 152 |
delimiter is found in the wrong place, a #NetconfFramingError |
| 153 |
will be raised.""" |
| 154 |
|
| 155 |
self.logger.debug("_parse11: starting") |
| 156 |
|
| 157 |
# suck in whole string that we have (this is what we will work on in |
| 158 |
# this function) and initialize a couple of useful values |
| 159 |
self._session._buffer.seek(0, os.SEEK_SET) |
| 160 |
data = self._session._buffer.getvalue() |
| 161 |
data_len = len(data) |
| 162 |
start = 0 |
| 163 |
self.logger.debug('_parse11: working with buffer of %d bytes', data_len) |
| 164 |
while True and start < data_len: |
| 165 |
# match to see if we found at least some kind of delimiter |
| 166 |
self.logger.debug('_parse11: matching from %d bytes from start of buffer', start) |
| 167 |
re_result = RE_NC11_DELIM.match(data[start:].decode('utf-8', errors='ignore')) |
| 168 |
if not re_result: |
| 169 |
|
| 170 |
# not found any kind of delimiter just break; this should only |
| 171 |
# ever happen if we just have the first few characters of a |
| 172 |
# message such that we don't yet have a full delimiter |
| 173 |
self.logger.debug('_parse11: no delimiter found, buffer="%s"', data[start:].decode()) |
| 174 |
break |
| 175 |
|
| 176 |
# save useful variables for reuse |
| 177 |
re_start = re_result.start() |
| 178 |
re_end = re_result.end() |
| 179 |
self.logger.debug('_parse11: regular expression start=%d, end=%d', re_start, re_end) |
| 180 |
|
| 181 |
# If the regex doesn't start at the beginning of the buffer, |
| 182 |
# we're in trouble, so throw an error |
| 183 |
if re_start != 0: |
| 184 |
raise NetconfFramingError('_parse11: delimiter not at start of match buffer', data[start:]) |
| 185 |
|
| 186 |
if re_result.group(2): |
| 187 |
# we've found the end of the message, need to form up |
| 188 |
# whole message, save back remainder (if any) to buffer |
| 189 |
# and dispatch the message |
| 190 |
start += re_end |
| 191 |
message = ''.join(self._session._message_list) |
| 192 |
self._session._message_list = [] |
| 193 |
self.logger.debug('_parse11: found end of message delimiter') |
| 194 |
self._session._dispatch_message(message) |
| 195 |
break |
| 196 |
|
| 197 |
elif re_result.group(1): |
| 198 |
# we've found a chunk delimiter, and group(1) is the digit |
| 199 |
# string that will tell us how many bytes past the end of |
| 200 |
# where it was found that we need to have available to |
| 201 |
# save the next chunk off |
| 202 |
self.logger.debug('_parse11: found chunk delimiter') |
| 203 |
digits = int(re_result.group(1)) |
| 204 |
self.logger.debug('_parse11: chunk size %d bytes', digits) |
| 205 |
if (data_len-start) >= (re_end + digits): |
| 206 |
# we have enough data for the chunk |
| 207 |
fragment = textify(data[start+re_end:start+re_end+digits]) |
| 208 |
self._session._message_list.append(fragment) |
| 209 |
start += re_end + digits |
| 210 |
self.logger.debug('_parse11: appending %d bytes', digits) |
| 211 |
self.logger.debug('_parse11: fragment = "%s"', fragment) |
| 212 |
else: |
| 213 |
# we don't have enough bytes, just break out for now |
| 214 |
# after updating start pointer to start of new chunk |
| 215 |
start += re_start |
| 216 |
self.logger.debug('_parse11: not enough data for chunk yet') |
| 217 |
self.logger.debug('_parse11: setting start to %d', start) |
| 218 |
break |
| 219 |
|
| 220 |
# Now out of the loop, need to see if we need to save back any content |
| 221 |
if start > 0: |
| 222 |
self.logger.debug( |
| 223 |
'_parse11: saving back rest of message after %d bytes, original size %d', |
| 224 |
start, data_len) |
| 225 |
self._session._buffer = StringIO(data[start:]) |
| 226 |
if start < data_len: |
| 227 |
self.logger.debug('_parse11: still have data, may have another full message!') |
| 228 |
self._parse11() |
| 229 |
self.logger.debug('_parse11: ending') |