1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
|
#!/usr/bin/env python3
########################################################################
# File name: log-to-scs.py
# This file is part of: aioxmpp
#
# LICENSE
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
########################################################################
import ast
import enum
import re
import lxml.etree as etree
import aioxmpp
_client_prefix = r"^aioxmpp\.e2etest\.provision\.client(?P<client_id>[0-9]+)"
SENT_LINE = re.compile(
_client_prefix + r"\.XMLStream:\ DEBUG:\ SENT\ (?P<bytes>b.+)$",
re.VERBOSE
)
RECV_LINE = re.compile(
_client_prefix + r"\.XMLStream:\ DEBUG:\ RECV\ (?P<bytes>b.+)$",
re.VERBOSE
)
JID_LINE = re.compile(
_client_prefix + r":\ INFO:\ bound\ to\ jid:\ (?P<jid>.+)",
re.VERBOSE,
)
def _parse_stream_bytes(b):
FOOTER = b"</stream:stream>"
b = ast.literal_eval(b)
# stream header, ignore
if b.startswith(b"<?xml"):
return
if b.startswith(FOOTER):
return
if b.endswith(FOOTER):
b = b[:-len(FOOTER)]
if not b.strip():
return
try:
tree = etree.fromstring(b"<root xmlns:stream='http://etherx.jabber.org/streams'>"+b+b"</root>")
except:
print(b)
raise
yield from tree
def _wrap_bytes(match, wrapper_name):
client_id = int(match["client_id"])
for piece in _parse_stream_bytes(match["bytes"]):
yield {
"client_id": client_id,
wrapper_name: {
"xml": piece
}
}
def parse_sent_line(match):
yield from _wrap_bytes(match, "sent")
def parse_recv_line(match):
yield from _wrap_bytes(match, "recv")
def parse_jid_line(match):
yield {
"client_id": int(match["client_id"]),
"bound": {
"jid": aioxmpp.JID.fromstr(match["jid"]),
}
}
line_parsers = [
(SENT_LINE, parse_sent_line),
(RECV_LINE, parse_recv_line),
(JID_LINE, parse_jid_line),
]
def parse_line(l):
for rx, parser in line_parsers:
match = rx.match(l)
if match is None:
continue
yield from parser(match.groupdict())
def parse_lines(ls):
for line in ls:
parsed = parse_line(line)
if parsed is not None:
yield from parsed
def xmllines(tree):
serialised = etree.tostring(tree, encoding="utf-8", pretty_print=True)
lines = serialised.decode("utf-8").split("\n")
return [line for line in lines if line.strip()]
def filter_sessions(actions):
ids_to_drop = set()
for action in actions:
xml = action.get("sent", action.get("recv", {})).get("xml")
if xml is None:
yield action
continue
id_ = xml.get("id")
key = (action["client_id"], id_)
if key in ids_to_drop:
ids_to_drop.discard(key)
continue
if xml.tag == "iq" and len(xml) > 0:
# IQ with payload
if xml[0].tag == "{urn:ietf:params:xml:ns:xmpp-session}session":
# drop!
ids_to_drop.add(key)
continue
yield action
def filter_serverdisco(actions):
ids_to_drop = set()
client_jids = {}
for action in actions:
try:
jid = action["bound"]["jid"]
except KeyError:
pass
else:
client_jids[action["client_id"]] = jid
xml = action.get("sent", action.get("recv", {})).get("xml")
if xml is None:
yield action
continue
id_ = xml.get("id")
key = (action["client_id"], id_)
if key in ids_to_drop:
ids_to_drop.discard(key)
continue
try:
client_jid = client_jids[action["client_id"]]
except KeyError:
yield action
continue
if (xml.tag == "iq" and len(xml) > 0 and
xml.get("to") == client_jid.domain and
xml[0].tag == "{http://jabber.org/protocol/disco#info}query"):
# drop!
ids_to_drop.add(key)
continue
yield action
class FinalAction(enum.Enum):
CONNECT = "connects"
SEND = "sends"
RECEIVE = "receives"
def generate(actions, out, characters=[], remove_clients=[]):
client_names = characters or [
"Juliet",
"Romeo",
]
clients = {}
result_actions = []
def bind_client(client_id, jid):
try:
name = client_names.pop(0)
except IndexError:
name = client_id
clients[client_id] = {
"id": client_id,
"name": name,
"jid": jid,
}
result_actions.append(
(client_id, (FinalAction.CONNECT, None))
)
for action in actions:
try:
client = clients[action["client_id"]]
except KeyError:
if "bound" in action and action["client_id"] not in remove_clients:
bind_client(action["client_id"], action["bound"]["jid"])
continue
if "sent" in action:
result_actions.append(
(client["id"], (FinalAction.SEND, action["sent"]["xml"]))
)
elif "recv" in action:
result_actions.append(
(client["id"], (FinalAction.RECEIVE, action["recv"]["xml"]))
)
else:
raise RuntimeError("unknown action: {}".format(action))
for client in sorted(clients.values(), key=lambda x: x["id"]):
print(
"[Client] {name}\n\tjid: {jid}\n\tpassword: password\n".format(
**client,
),
file=out,
)
print("---------\n")
for client_id, (action, xml) in result_actions:
client = clients[client_id]
print(
"{client[name]} {action.value}".format(
client=client, action=action
),
end="",
file=out
)
if xml is not None:
print(":\n\t{}".format("\n\t".join(xmllines(xml))), file=out)
else:
print(file=out)
print(file=out)
if __name__ == "__main__":
import argparse
import sys
parser = argparse.ArgumentParser()
parser.add_argument(
"--characters",
nargs="+",
dest="characters",
default=[],
)
parser.add_argument(
"--strip-serverdisco",
action="append_const",
dest="add_filters",
default=[],
const=filter_serverdisco,
)
parser.add_argument(
"--no-strip-sessions",
action="append_const",
dest="remove_filters",
default=[],
const=filter_sessions,
)
parser.add_argument(
"--remove-client",
action="append",
dest="remove_clients",
default=[],
type=int,
)
parser.add_argument(
"-o", "--output",
default=sys.stdout,
type=argparse.FileType("w"),
)
parser.add_argument(
"input",
nargs="?",
default=sys.stdin,
type=argparse.FileType("r"),
)
args = parser.parse_args()
filters = [filter_sessions]
for to_add in args.add_filters:
filters.append(to_add)
for to_remove in args.remove_filters:
try:
filters.remove(to_remove)
except ValueError:
pass
with args.input as f:
actions = list(parse_lines(f))
for filter_func in filters:
actions = filter_func(actions)
with args.output as f:
generate(actions, f, characters=list(args.characters),
remove_clients=args.remove_clients)
|