2 # -*- coding: utf-8 -*-
4 # protocol.py - decode binary messages received from WeeChat/relay
6 # Copyright (C) 2011-2014 Sébastien Helleu <flashcode@flashtux.org>
8 # This file is part of QWeeChat, a Qt remote GUI for WeeChat.
10 # QWeeChat is free software; you can redistribute it and/or modify
11 # it under the terms of the GNU General Public License as published by
12 # the Free Software Foundation; either version 3 of the License, or
13 # (at your option) any later version.
15 # QWeeChat is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 # GNU General Public License for more details.
20 # You should have received a copy of the GNU General Public License
21 # along with QWeeChat. If not, see <http://www.gnu.org/licenses/>.
25 # For info about protocol and format of messages, please read document
26 # "WeeChat Relay Protocol", available at: http://weechat.org/doc/
30 # 2011-11-23, Sébastien Helleu <flashcode@flashtux.org>:
38 if hasattr(collections
, 'OrderedDict'):
40 class WeechatDict(collections
.OrderedDict
):
42 return '{%s}' % ', '.join(
43 ['%s: %s' % (repr(key
), repr(self
[key
])) for key
in self
])
50 def __init__(self
, objtype
, value
, separator
='\n'):
51 self
.objtype
= objtype
53 self
.separator
= separator
54 self
.indent
= ' ' if separator
== '\n' else ''
55 self
.separator1
= '\n%s' % self
.indent
if separator
== '\n' else ''
57 def _str_value(self
, v
):
58 if type(v
) is str and v
is not None:
62 def _str_value_hdata(self
):
63 lines
= ['%skeys: %s%s%spath: %s' % (self
.separator1
,
64 str(self
.value
['keys']),
67 str(self
.value
['path']))]
68 for i
, item
in enumerate(self
.value
['items']):
69 lines
.append(' item %d:%s%s' % (
70 (i
+ 1), self
.separator
,
72 ['%s%s: %s' % (self
.indent
* 2, key
,
73 self
._str
_value
(value
))
74 for key
, value
in item
.items()])))
75 return '\n'.join(lines
)
77 def _str_value_infolist(self
):
78 lines
= ['%sname: %s' % (self
.separator1
, self
.value
['name'])]
79 for i
, item
in enumerate(self
.value
['items']):
80 lines
.append(' item %d:%s%s' % (
81 (i
+ 1), self
.separator
,
83 ['%s%s: %s' % (self
.indent
* 2, key
,
84 self
._str
_value
(value
))
85 for key
, value
in item
.items()])))
86 return '\n'.join(lines
)
88 def _str_value_other(self
):
89 return self
._str
_value
(self
.value
)
92 self
._obj
_cb
= {'hda': self
._str
_value
_hdata
,
93 'inl': self
._str
_value
_infolist
,
95 return '%s: %s' % (self
.objtype
,
96 self
._obj
_cb
.get(self
.objtype
,
97 self
._str
_value
_other
)())
100 class WeechatObjects(list):
101 def __init__(self
, separator
='\n'):
102 self
.separator
= separator
105 return self
.separator
.join([str(obj
) for obj
in self
])
108 class WeechatMessage
:
109 def __init__(self
, size
, size_uncompressed
, compression
, uncompressed
,
112 self
.size_uncompressed
= size_uncompressed
113 self
.compression
= compression
114 self
.uncompressed
= uncompressed
116 self
.objects
= objects
119 if self
.compression
!= 0:
120 return 'size: %d/%d (%d%%), id=\'%s\', objects:\n%s' % (
121 self
.size
, self
.size_uncompressed
,
122 100 - ((self
.size
* 100) // self
.size_uncompressed
),
123 self
.msgid
, self
.objects
)
125 return 'size: %d, id=\'%s\', objects:\n%s' % (self
.size
,
131 """Decode binary message received from WeeChat/relay."""
134 self
._obj
_cb
= {'chr': self
._obj
_char
,
135 'int': self
._obj
_int
,
136 'lon': self
._obj
_long
,
137 'str': self
._obj
_str
,
138 'buf': self
._obj
_buffer
,
139 'ptr': self
._obj
_ptr
,
140 'tim': self
._obj
_time
,
141 'htb': self
._obj
_hashtable
,
142 'hda': self
._obj
_hdata
,
143 'inf': self
._obj
_info
,
144 'inl': self
._obj
_infolist
,
145 'arr': self
._obj
_array
,
149 """Read type in data (3 chars)."""
150 if len(self
.data
) < 3:
153 objtype
= str(self
.data
[0:3])
154 self
.data
= self
.data
[3:]
157 def _obj_len_data(self
, length_size
):
158 """Read length (1 or 4 bytes), then value with this length."""
159 if len(self
.data
) < length_size
:
163 length
= struct
.unpack('B', self
.data
[0:1])[0]
164 self
.data
= self
.data
[1:]
166 length
= self
._obj
_int
()
170 value
= self
.data
[0:length
]
171 self
.data
= self
.data
[length
:]
177 """Read a char in data."""
178 if len(self
.data
) < 1:
180 value
= struct
.unpack('b', self
.data
[0:1])[0]
181 self
.data
= self
.data
[1:]
185 """Read an integer in data (4 bytes)."""
186 if len(self
.data
) < 4:
189 value
= struct
.unpack('>i', self
.data
[0:4])[0]
190 self
.data
= self
.data
[4:]
194 """Read a long integer in data (length on 1 byte + value as string)."""
195 value
= self
._obj
_len
_data
(1)
198 return int(str(value
))
201 """Read a string in data (length on 4 bytes + content)."""
202 value
= self
._obj
_len
_data
(4)
207 def _obj_buffer(self
):
208 """Read a buffer in data (length on 4 bytes + data)."""
209 return self
._obj
_len
_data
(4)
212 """Read a pointer in data (length on 1 byte + value as string)."""
213 value
= self
._obj
_len
_data
(1)
216 return '0x%s' % str(value
)
219 """Read a time in data (length on 1 byte + value as string)."""
220 value
= self
._obj
_len
_data
(1)
223 return int(str(value
))
225 def _obj_hashtable(self
):
227 Read a hashtable in data
228 (type for keys + type for values + count + items).
230 type_keys
= self
._obj
_type
()
231 type_values
= self
._obj
_type
()
232 count
= self
._obj
_int
()
233 hashtable
= WeechatDict()
234 for i
in range(0, count
):
235 key
= self
._obj
_cb
[type_keys
]()
236 value
= self
._obj
_cb
[type_values
]()
237 hashtable
[key
] = value
240 def _obj_hdata(self
):
241 """Read a hdata in data."""
242 path
= self
._obj
_str
()
243 keys
= self
._obj
_str
()
244 count
= self
._obj
_int
()
245 list_path
= path
.split('/')
246 list_keys
= keys
.split(',')
248 dict_keys
= WeechatDict()
249 for key
in list_keys
:
250 items
= key
.split(':')
251 keys_types
.append(items
)
252 dict_keys
[items
[0]] = items
[1]
254 for i
in range(0, count
):
258 for p
in range(0, len(list_path
)):
259 pointers
.append(self
._obj
_ptr
())
260 for key
, objtype
in keys_types
:
261 item
[key
] = self
._obj
_cb
[objtype
]()
262 item
['__path'] = pointers
264 return {'path': list_path
,
271 """Read an info in data."""
272 name
= self
._obj
_str
()
273 value
= self
._obj
_str
()
276 def _obj_infolist(self
):
277 """Read an infolist in data."""
278 name
= self
._obj
_str
()
279 count_items
= self
._obj
_int
()
281 for i
in range(0, count_items
):
282 count_vars
= self
._obj
_int
()
283 variables
= WeechatDict()
284 for v
in range(0, count_vars
):
285 var_name
= self
._obj
_str
()
286 var_type
= self
._obj
_type
()
287 var_value
= self
._obj
_cb
[var_type
]()
288 variables
[var_name
] = var_value
289 items
.append(variables
)
290 return {'name': name, 'items': items}
292 def _obj_array(self
):
293 """Read an array of values in data."""
294 type_values
= self
._obj
_type
()
295 count_values
= self
._obj
_int
()
297 for i
in range(0, count_values
):
298 values
.append(self
._obj
_cb
[type_values
]())
301 def decode(self
, data
, separator
='\n'):
302 """Decode binary data and return list of objects."""
304 size
= len(self
.data
)
305 size_uncompressed
= size
307 # uncompress data (if it is compressed)
308 compression
= struct
.unpack('b', self
.data
[4:5])[0]
310 uncompressed
= zlib
.decompress(self
.data
[5:])
311 size_uncompressed
= len(uncompressed
) + 5
312 uncompressed
= '%s%s%s' % (struct
.pack('>i', size_uncompressed
),
313 struct
.pack('b', 0), uncompressed
)
314 self
.data
= uncompressed
316 uncompressed
= self
.data
[:]
317 # skip length and compression flag
318 self
.data
= self
.data
[5:]
320 msgid
= self
._obj
_str
()
324 objects
= WeechatObjects(separator
=separator
)
325 while len(self
.data
) > 0:
326 objtype
= self
._obj
_type
()
327 value
= self
._obj
_cb
[objtype
]()
328 objects
.append(WeechatObject(objtype
, value
, separator
=separator
))
329 return WeechatMessage(size
, size_uncompressed
, compression
,
330 uncompressed
, msgid
, objects
)
333 def hex_and_ascii(data
, bytes_per_line
=10):
334 """Convert a QByteArray to hex + ascii output."""
335 num_lines
= ((len(data
) - 1) // bytes_per_line
) + 1
339 for i
in range(0, num_lines
):
342 for char
in data
[i
*bytes_per_line
:(i
*bytes_per_line
)+bytes_per_line
]:
343 byte
= struct
.unpack('B', char
)[0]
344 str_hex
.append('%02X' % int(byte
))
345 if byte
>= 32 and byte
<= 127:
346 str_ascii
.append(char
)
348 str_ascii
.append('.')
349 fmt
= '%%-%ds %%s' % ((bytes_per_line
* 3) - 1)
350 lines
.append(fmt
% (' '.join(str_hex
), ''.join(str_ascii
)))
351 return '\n'.join(lines
)