Debian Codegraph @

ncclient/transport/third_party/junos/parser.py

raw
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 import os
16
17 from threading import Lock
18
19 import difflib
20
21 from xml.sax.handler import ContentHandler
22 from lxml import etree
23 from lxml.builder import E
24 from xml.sax._exceptions import SAXParseException
25 from xml.sax import make_parser
26
27 from ncclient.transport.parser import DefaultXMLParser
28 from ncclient.operations import rpc
29 from ncclient.transport.parser import SAXFilterXMLNotFoundError
30 from ncclient.transport.parser import MSG_DELIM, MSG_DELIM_LEN
31 from ncclient.operations.errors import OperationError
32
33 import logging
34 logger = logging.getLogger("ncclient.transport.third_party.junos.parser")
35
36 from ncclient.xml_ import BASE_NS_1_0
37
38 RPC_REPLY_END_TAG = "</rpc-reply>"
39 RFC_RPC_REPLY_END_TAG = "</nc:rpc-reply>"
40
41
42 class JunosXMLParser(DefaultXMLParser):
43 def __init__(self, session):
44 super(JunosXMLParser, self).__init__(session)
45 self._session = session
46 self.sax_parser = make_parser()
47 self.sax_parser.setContentHandler(SAXParser(session))
48
49 def parse(self, data):
50 try:
51 self.sax_parser.feed(data)
52 except SAXParseException:
53 self._delimiter_check(data)
54 except SAXFilterXMLNotFoundError:
55 self.logger.debug('Missing SAX filter_xml. Switching from sax to dom parsing')
56 self._session.parser = DefaultXMLParser(self._session)
57 if not isinstance(data, bytes):
58 data = str.encode(data)
59 self._session._buffer.write(data)
60 finally:
61 self._parse10()
62
63 def _delimiter_check(self, data):
64 """
65 SAX parser throws SAXParseException exception, if there is extra data
66 after MSG_DELIM
67
68 :param data: content read by select loop
69 :return: None
70 """
71 data = data.decode('UTF-8')
72 if MSG_DELIM in data:
73 # need to feed extra data after MSG_DELIM
74 msg, delim, remaining = data.partition(MSG_DELIM)
75 self._session._buffer.seek(0, os.SEEK_END)
76 self._session._buffer.write(delim.encode())
77 if remaining.strip() != '':
78 self._session._buffer.write(remaining.encode())
79 # we need to renew parser, as old parser is gone.
80 self.sax_parser = make_parser()
81 self.sax_parser.setContentHandler(SAXParser(self._session))
82 elif RPC_REPLY_END_TAG in data or RFC_RPC_REPLY_END_TAG in data:
83 tag = RPC_REPLY_END_TAG if RPC_REPLY_END_TAG in data else \
84 RFC_RPC_REPLY_END_TAG
85 logger.warning("Check for rpc reply end tag within data received: %s" % data)
86 msg, delim, remaining = data.partition(tag)
87 self._session._buffer.seek(0, os.SEEK_END)
88 self._session._buffer.write(remaining.encode())
89 else:
90 logger.warning("Check if end delimiter is split within data received: %s" % data)
91 # When data is "-reply/>]]>" or "]]>"
92 # Data is not full MSG_DELIM, So check if last rpc reply is complete.
93 # if then, wait for next iteration of data and do a recursive call to
94 # _delimiter_check for MSG_DELIM check
95 buf = self._session._buffer
96 buf.seek(buf.tell() - len(RFC_RPC_REPLY_END_TAG) - MSG_DELIM_LEN)
97 rpc_response_last_msg = buf.read().decode('UTF-8').replace('\n', '')
98 if RPC_REPLY_END_TAG in rpc_response_last_msg or \
99 RFC_RPC_REPLY_END_TAG in rpc_response_last_msg:
100 tag = RPC_REPLY_END_TAG if RPC_REPLY_END_TAG in \
101 rpc_response_last_msg else \
102 RFC_RPC_REPLY_END_TAG
103 # rpc_response_last_msg and data can be overlapping
104 match_obj = difflib.SequenceMatcher(None, rpc_response_last_msg,
105 data).get_matching_blocks()
106 if match_obj:
107 # 0 means second string match start from beginning, hence
108 # there is a overlap
109 if match_obj[0].b == 0:
110 # matching char are of match_obj[0].size
111 self._delimiter_check((rpc_response_last_msg +
112 data[match_obj[0].size:]).encode())
113 else:
114 data = rpc_response_last_msg+data
115 if MSG_DELIM in data:
116 # there can be residual end delimiter chars in buffer.
117 # as first if condition will add full delimiter, so clean
118 # it off
119 clean_up = len(rpc_response_last_msg) - (
120 rpc_response_last_msg.find(tag) + len(tag))
121 self._session._buffer.truncate(buf.tell() - clean_up)
122 self._delimiter_check(data.encode())
123 else:
124 self._delimiter_check((rpc_response_last_msg + data).encode())
125
126
127 def __dict_replace(s, d):
128 """Replace substrings of a string using a dictionary."""
129 for key, value in d.items():
130 s = s.replace(key, value)
131 return s
132
133
134 def _get_sax_parser_root(xml):
135 """
136 This function does some validation and rule check of xmlstring
137 :param xml: string or object to be used in parsing reply
138 :return: lxml object
139 """
140 if isinstance(xml, etree._Element):
141 root = xml
142 else:
143 root = etree.fromstring(xml)
144 return root
145
146
147 def escape(data, entities={}):
148 """Escape &, <, and > in a string of data.
149
150 You can escape other strings of data by passing a dictionary as
151 the optional entities parameter. The keys and values must all be
152 strings; each key will be replaced with its corresponding value.
153 """
154
155 # must do ampersand first
156 data = data.replace("&", "&amp;")
157 data = data.replace(">", "&gt;")
158 data = data.replace("<", "&lt;")
159 if entities:
160 data = __dict_replace(data, entities)
161 return data
162
163
164 def quoteattr(data, entities={}):
165 """Escape and quote an attribute value.
166
167 Escape &, <, and > in a string of data, then quote it for use as
168 an attribute value. The \" character will be escaped as well, if
169 necessary.
170
171 You can escape other strings of data by passing a dictionary as
172 the optional entities parameter. The keys and values must all be
173 strings; each key will be replaced with its corresponding value.
174 """
175 # entities = entities.copy()
176 entities.update({'\n': '&#10;', '\r': '&#13;', '\t':'&#9;'})
177 data = escape(data, entities)
178 if '"' in data:
179 if "'" in data:
180 data = '"%s"' % data.replace('"', "&quot;")
181 else:
182 data = "'%s'" % data
183 else:
184 data = '"%s"' % data
185 return data
186
187
188 class SAXParser(ContentHandler):
189 def __init__(self, session):
190 ContentHandler.__init__(self)
191 self._currenttag = None
192 self._ignoretag = None
193 self._defaulttags = []
194 self._session = session
195 self._validate_reply_and_sax_tag = False
196 self._lock = Lock()
197 self.nc_namespace = None
198
199 def startElement(self, tag, attributes):
200 if tag in ['rpc-reply', 'nc:rpc-reply']:
201 if tag == 'nc:rpc-reply':
202 self.nc_namespace = BASE_NS_1_0
203 # in case last rpc called used sax parsing and error'd out
204 # without resetting use_filer in endElement rpc-reply check
205 with self._lock:
206 listeners = list(self._session._listeners)
207 rpc_reply_listener = [i for i in listeners if
208 isinstance(i, rpc.RPCReplyListener)]
209 rpc_msg_id = attributes._attrs['message-id']
210 if rpc_msg_id in rpc_reply_listener[0]._id2rpc:
211 rpc_reply_handler = rpc_reply_listener[0]._id2rpc[rpc_msg_id]
212 if hasattr(rpc_reply_handler, '_filter_xml') and \
213 rpc_reply_handler._filter_xml is not None:
214 self._cur = self._root = _get_sax_parser_root(
215 rpc_reply_handler._filter_xml)
216 else:
217 raise SAXFilterXMLNotFoundError(rpc_reply_handler)
218 else:
219 raise OperationError("Unknown 'message-id': %s" % rpc_msg_id)
220 if self._ignoretag is not None:
221 return
222
223 if self._cur == self._root and self._cur.tag == tag:
224 node = self._root
225 else:
226 node = self._cur.find(tag, namespaces={"nc": self.nc_namespace})
227
228 if self._validate_reply_and_sax_tag:
229 if tag != self._root.tag:
230 self._write_buffer(tag, format_str='<{}>\n')
231 self._cur = E(tag, self._cur)
232 else:
233 self._write_buffer(tag, format_str='<{}{}>', **attributes)
234 self._cur = node
235 self._currenttag = tag
236 self._validate_reply_and_sax_tag = False
237 self._defaulttags.append(tag)
238 elif node is not None:
239 self._write_buffer(tag, format_str='<{}{}>', **attributes)
240 self._cur = node
241 self._currenttag = tag
242 elif tag in ['rpc-reply', 'nc:rpc-reply']:
243 self._write_buffer(tag, format_str='<{}{}>', **attributes)
244 self._defaulttags.append(tag)
245 self._validate_reply_and_sax_tag = True
246 else:
247 self._currenttag = None
248 self._ignoretag = tag
249
250 def endElement(self, tag):
251 if self._ignoretag == tag:
252 self._ignoretag = None
253
254 if tag in self._defaulttags:
255 self._write_buffer(tag, format_str='</{}>\n')
256 elif self._cur.tag == tag:
257 self._write_buffer(tag, format_str='</{}>\n')
258 self._cur = self._cur.getparent()
259
260 self._currenttag = None
261
262 def characters(self, content):
263 if self._currenttag is not None:
264 self._write_buffer(content, format_str='{}')
265
266 def _write_buffer(self, content, format_str, **kwargs):
267 # print(content, format_str, kwargs)
268 self._session._buffer.seek(0, os.SEEK_END)
269 attrs = ''
270 for (name, value) in kwargs.items():
271 attr = ' {}={}'.format(name, quoteattr(value))
272 attrs = attrs + attr
273 data = format_str.format(escape(content), attrs)
274 self._session._buffer.write(str.encode(data))