1 # -*- coding: utf-8 -*-
3 # protocol.py - decode binary messages received from WeeChat/relay
5 # Copyright (C) 2011-2014 Sébastien Helleu <flashcode@flashtux.org>
7 # This file is part of QWeeChat, a Qt remote GUI for WeeChat.
9 # QWeeChat is free software; you can redistribute it and/or modify
10 # it under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 3 of the License, or
12 # (at your option) any later version.
14 # QWeeChat is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
19 # You should have received a copy of the GNU General Public License
20 # along with QWeeChat. If not, see <http://www.gnu.org/licenses/>.
24 # For info about protocol and format of messages, please read document
25 # "WeeChat Relay Protocol", available at: http://weechat.org/doc/
29 # 2011-11-23, Sébastien Helleu <flashcode@flashtux.org>:
37 if hasattr(collections
, 'OrderedDict'):
39 class WeechatDict(collections
.OrderedDict
):
41 return '{%s}' % ', '.join(
42 ['%s: %s' % (repr(key
), repr(self
[key
])) for key
in self
])
49 def __init__(self
, objtype
, value
, separator
='\n'):
50 self
.objtype
= objtype
52 self
.separator
= separator
53 self
.indent
= ' ' if separator
== '\n' else ''
54 self
.separator1
= '\n%s' % self
.indent
if separator
== '\n' else ''
56 def _str_value(self
, v
):
57 if type(v
) is str and v
is not None:
61 def _str_value_hdata(self
):
62 lines
= ['%skeys: %s%s%spath: %s' % (self
.separator1
,
63 str(self
.value
['keys']),
66 str(self
.value
['path']))]
67 for i
, item
in enumerate(self
.value
['items']):
68 lines
.append(' item %d:%s%s' % (
69 (i
+ 1), self
.separator
,
71 ['%s%s: %s' % (self
.indent
* 2, key
,
72 self
._str
_value
(value
))
73 for key
, value
in item
.items()])))
74 return '\n'.join(lines
)
76 def _str_value_infolist(self
):
77 lines
= ['%sname: %s' % (self
.separator1
, self
.value
['name'])]
78 for i
, item
in enumerate(self
.value
['items']):
79 lines
.append(' item %d:%s%s' % (
80 (i
+ 1), self
.separator
,
82 ['%s%s: %s' % (self
.indent
* 2, key
,
83 self
._str
_value
(value
))
84 for key
, value
in item
.items()])))
85 return '\n'.join(lines
)
87 def _str_value_other(self
):
88 return self
._str
_value
(self
.value
)
91 self
._obj
_cb
= {'hda': self
._str
_value
_hdata
,
92 'inl': self
._str
_value
_infolist
,
94 return '%s: %s' % (self
.objtype
,
95 self
._obj
_cb
.get(self
.objtype
,
96 self
._str
_value
_other
)())
99 class WeechatObjects(list):
100 def __init__(self
, separator
='\n'):
101 self
.separator
= separator
104 return self
.separator
.join([str(obj
) for obj
in self
])
107 class WeechatMessage
:
108 def __init__(self
, size
, size_uncompressed
, compression
, uncompressed
,
111 self
.size_uncompressed
= size_uncompressed
112 self
.compression
= compression
113 self
.uncompressed
= uncompressed
115 self
.objects
= objects
118 if self
.compression
!= 0:
119 return 'size: %d/%d (%d%%), id=\'%s\', objects:\n%s' % (
120 self
.size
, self
.size_uncompressed
,
121 100 - ((self
.size
* 100) // self
.size_uncompressed
),
122 self
.msgid
, self
.objects
)
124 return 'size: %d, id=\'%s\', objects:\n%s' % (self
.size
,
130 """Decode binary message received from WeeChat/relay."""
133 self
._obj
_cb
= {'chr': self
._obj
_char
,
134 'int': self
._obj
_int
,
135 'lon': self
._obj
_long
,
136 'str': self
._obj
_str
,
137 'buf': self
._obj
_buffer
,
138 'ptr': self
._obj
_ptr
,
139 'tim': self
._obj
_time
,
140 'htb': self
._obj
_hashtable
,
141 'hda': self
._obj
_hdata
,
142 'inf': self
._obj
_info
,
143 'inl': self
._obj
_infolist
,
144 'arr': self
._obj
_array
,
148 """Read type in data (3 chars)."""
149 if len(self
.data
) < 3:
152 objtype
= str(self
.data
[0:3])
153 self
.data
= self
.data
[3:]
156 def _obj_len_data(self
, length_size
):
157 """Read length (1 or 4 bytes), then value with this length."""
158 if len(self
.data
) < length_size
:
162 length
= struct
.unpack('B', self
.data
[0:1])[0]
163 self
.data
= self
.data
[1:]
165 length
= self
._obj
_int
()
169 value
= self
.data
[0:length
]
170 self
.data
= self
.data
[length
:]
176 """Read a char in data."""
177 if len(self
.data
) < 1:
179 value
= struct
.unpack('b', self
.data
[0:1])[0]
180 self
.data
= self
.data
[1:]
184 """Read an integer in data (4 bytes)."""
185 if len(self
.data
) < 4:
188 value
= struct
.unpack('>i', self
.data
[0:4])[0]
189 self
.data
= self
.data
[4:]
193 """Read a long integer in data (length on 1 byte + value as string)."""
194 value
= self
._obj
_len
_data
(1)
197 return int(str(value
))
200 """Read a string in data (length on 4 bytes + content)."""
201 value
= self
._obj
_len
_data
(4)
206 def _obj_buffer(self
):
207 """Read a buffer in data (length on 4 bytes + data)."""
208 return self
._obj
_len
_data
(4)
211 """Read a pointer in data (length on 1 byte + value as string)."""
212 value
= self
._obj
_len
_data
(1)
215 return '0x%s' % str(value
)
218 """Read a time in data (length on 1 byte + value as string)."""
219 value
= self
._obj
_len
_data
(1)
222 return int(str(value
))
224 def _obj_hashtable(self
):
226 Read a hashtable in data
227 (type for keys + type for values + count + items).
229 type_keys
= self
._obj
_type
()
230 type_values
= self
._obj
_type
()
231 count
= self
._obj
_int
()
232 hashtable
= WeechatDict()
233 for i
in range(0, count
):
234 key
= self
._obj
_cb
[type_keys
]()
235 value
= self
._obj
_cb
[type_values
]()
236 hashtable
[key
] = value
239 def _obj_hdata(self
):
240 """Read a hdata in data."""
241 path
= self
._obj
_str
()
242 keys
= self
._obj
_str
()
243 count
= self
._obj
_int
()
244 list_path
= path
.split('/')
245 list_keys
= keys
.split(',')
247 dict_keys
= WeechatDict()
248 for key
in list_keys
:
249 items
= key
.split(':')
250 keys_types
.append(items
)
251 dict_keys
[items
[0]] = items
[1]
253 for i
in range(0, count
):
257 for p
in range(0, len(list_path
)):
258 pointers
.append(self
._obj
_ptr
())
259 for key
, objtype
in keys_types
:
260 item
[key
] = self
._obj
_cb
[objtype
]()
261 item
['__path'] = pointers
263 return {'path': list_path
,
270 """Read an info in data."""
271 name
= self
._obj
_str
()
272 value
= self
._obj
_str
()
275 def _obj_infolist(self
):
276 """Read an infolist in data."""
277 name
= self
._obj
_str
()
278 count_items
= self
._obj
_int
()
280 for i
in range(0, count_items
):
281 count_vars
= self
._obj
_int
()
282 variables
= WeechatDict()
283 for v
in range(0, count_vars
):
284 var_name
= self
._obj
_str
()
285 var_type
= self
._obj
_type
()
286 var_value
= self
._obj
_cb
[var_type
]()
287 variables
[var_name
] = var_value
288 items
.append(variables
)
289 return {'name': name, 'items': items}
291 def _obj_array(self
):
292 """Read an array of values in data."""
293 type_values
= self
._obj
_type
()
294 count_values
= self
._obj
_int
()
296 for i
in range(0, count_values
):
297 values
.append(self
._obj
_cb
[type_values
]())
300 def decode(self
, data
, separator
='\n'):
301 """Decode binary data and return list of objects."""
303 size
= len(self
.data
)
304 size_uncompressed
= size
306 # uncompress data (if it is compressed)
307 compression
= struct
.unpack('b', self
.data
[4:5])[0]
309 uncompressed
= zlib
.decompress(self
.data
[5:])
310 size_uncompressed
= len(uncompressed
) + 5
311 uncompressed
= '%s%s%s' % (struct
.pack('>i', size_uncompressed
),
312 struct
.pack('b', 0), uncompressed
)
313 self
.data
= uncompressed
315 uncompressed
= self
.data
[:]
316 # skip length and compression flag
317 self
.data
= self
.data
[5:]
319 msgid
= self
._obj
_str
()
323 objects
= WeechatObjects(separator
=separator
)
324 while len(self
.data
) > 0:
325 objtype
= self
._obj
_type
()
326 value
= self
._obj
_cb
[objtype
]()
327 objects
.append(WeechatObject(objtype
, value
, separator
=separator
))
328 return WeechatMessage(size
, size_uncompressed
, compression
,
329 uncompressed
, msgid
, objects
)
332 def hex_and_ascii(data
, bytes_per_line
=10):
333 """Convert a QByteArray to hex + ascii output."""
334 num_lines
= ((len(data
) - 1) // bytes_per_line
) + 1
338 for i
in range(0, num_lines
):
341 for char
in data
[i
*bytes_per_line
:(i
*bytes_per_line
)+bytes_per_line
]:
342 byte
= struct
.unpack('B', char
)[0]
343 str_hex
.append('%02X' % int(byte
))
344 if byte
>= 32 and byte
<= 127:
345 str_ascii
.append(char
)
347 str_ascii
.append('.')
348 fmt
= '%%-%ds %%s' % ((bytes_per_line
* 3) - 1)
349 lines
.append(fmt
% (' '.join(str_hex
), ''.join(str_ascii
)))
350 return '\n'.join(lines
)