]> jfr.im git - irc/weechat/qweechat.git/blame - qweechat/weechat/protocol.py
Remove python shebangs
[irc/weechat/qweechat.git] / qweechat / weechat / protocol.py
CommitLineData
7dcf23b1
SH
1# -*- coding: utf-8 -*-
2#
e836cfb0
SH
3# protocol.py - decode binary messages received from WeeChat/relay
4#
da74afdb 5# Copyright (C) 2011-2014 Sébastien Helleu <flashcode@flashtux.org>
7dcf23b1
SH
6#
7# This file is part of QWeeChat, a Qt remote GUI for WeeChat.
8#
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.
13#
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.
18#
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/>.
21#
22
23#
e836cfb0 24# For info about protocol and format of messages, please read document
da74afdb 25# "WeeChat Relay Protocol", available at: http://weechat.org/doc/
7dcf23b1
SH
26#
27# History:
28#
da74afdb 29# 2011-11-23, Sébastien Helleu <flashcode@flashtux.org>:
7dcf23b1
SH
30# start dev
31#
32
77df9d06
SH
33import collections
34import struct
35import zlib
be3c1eda
SH
36
37if hasattr(collections, 'OrderedDict'):
38 # python >= 2.7
39 class WeechatDict(collections.OrderedDict):
40 def __str__(self):
77df9d06
SH
41 return '{%s}' % ', '.join(
42 ['%s: %s' % (repr(key), repr(self[key])) for key in self])
be3c1eda
SH
43else:
44 # python <= 2.6
45 WeechatDict = dict
7dcf23b1 46
77df9d06 47
7dcf23b1 48class WeechatObject:
7b4aefb2 49 def __init__(self, objtype, value, separator='\n'):
77df9d06 50 self.objtype = objtype
7dcf23b1 51 self.value = value
7b4aefb2
SH
52 self.separator = separator
53 self.indent = ' ' if separator == '\n' else ''
54 self.separator1 = '\n%s' % self.indent if separator == '\n' else ''
7dcf23b1
SH
55
56 def _str_value(self, v):
baa01601 57 if type(v) is str and v is not None:
7dcf23b1
SH
58 return '\'%s\'' % v
59 return str(v)
60
61 def _str_value_hdata(self):
77df9d06
SH
62 lines = ['%skeys: %s%s%spath: %s' % (self.separator1,
63 str(self.value['keys']),
64 self.separator,
65 self.indent,
66 str(self.value['path']))]
7dcf23b1 67 for i, item in enumerate(self.value['items']):
77df9d06
SH
68 lines.append(' item %d:%s%s' % (
69 (i + 1), self.separator,
70 self.separator.join(
71 ['%s%s: %s' % (self.indent * 2, key,
72 self._str_value(value))
73 for key, value in item.items()])))
7dcf23b1
SH
74 return '\n'.join(lines)
75
76 def _str_value_infolist(self):
7b4aefb2 77 lines = ['%sname: %s' % (self.separator1, self.value['name'])]
7dcf23b1 78 for i, item in enumerate(self.value['items']):
77df9d06
SH
79 lines.append(' item %d:%s%s' % (
80 (i + 1), self.separator,
81 self.separator.join(
82 ['%s%s: %s' % (self.indent * 2, key,
83 self._str_value(value))
84 for key, value in item.items()])))
7dcf23b1
SH
85 return '\n'.join(lines)
86
87 def _str_value_other(self):
88 return self._str_value(self.value)
89
90 def __str__(self):
91 self._obj_cb = {'hda': self._str_value_hdata,
c738936b 92 'inl': self._str_value_infolist,
7dcf23b1 93 }
77df9d06
SH
94 return '%s: %s' % (self.objtype,
95 self._obj_cb.get(self.objtype,
96 self._str_value_other)())
7dcf23b1
SH
97
98
99class WeechatObjects(list):
7b4aefb2
SH
100 def __init__(self, separator='\n'):
101 self.separator = separator
102
7dcf23b1 103 def __str__(self):
7b4aefb2 104 return self.separator.join([str(obj) for obj in self])
7dcf23b1
SH
105
106
107class WeechatMessage:
77df9d06
SH
108 def __init__(self, size, size_uncompressed, compression, uncompressed,
109 msgid, objects):
7dcf23b1
SH
110 self.size = size
111 self.size_uncompressed = size_uncompressed
112 self.compression = compression
113 self.uncompressed = uncompressed
114 self.msgid = msgid
115 self.objects = objects
116
117 def __str__(self):
118 if self.compression != 0:
119 return 'size: %d/%d (%d%%), id=\'%s\', objects:\n%s' % (
120 self.size, self.size_uncompressed,
141c8d30 121 100 - ((self.size * 100) // self.size_uncompressed),
7dcf23b1
SH
122 self.msgid, self.objects)
123 else:
77df9d06
SH
124 return 'size: %d, id=\'%s\', objects:\n%s' % (self.size,
125 self.msgid,
126 self.objects)
7dcf23b1
SH
127
128
129class Protocol:
130 """Decode binary message received from WeeChat/relay."""
131
132 def __init__(self):
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,
c738936b 140 'htb': self._obj_hashtable,
7dcf23b1
SH
141 'hda': self._obj_hdata,
142 'inf': self._obj_info,
c738936b 143 'inl': self._obj_infolist,
4b44d000 144 'arr': self._obj_array,
7dcf23b1
SH
145 }
146
c738936b
SH
147 def _obj_type(self):
148 """Read type in data (3 chars)."""
149 if len(self.data) < 3:
150 self.data = ''
151 return ''
152 objtype = str(self.data[0:3])
153 self.data = self.data[3:]
154 return objtype
155
7dcf23b1
SH
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:
159 self.data = ''
160 return None
161 if length_size == 1:
162 length = struct.unpack('B', self.data[0:1])[0]
163 self.data = self.data[1:]
164 else:
165 length = self._obj_int()
166 if length < 0:
167 return None
168 if length > 0:
169 value = self.data[0:length]
170 self.data = self.data[length:]
171 else:
172 value = ''
173 return value
174
175 def _obj_char(self):
176 """Read a char in data."""
177 if len(self.data) < 1:
178 return 0
179 value = struct.unpack('b', self.data[0:1])[0]
180 self.data = self.data[1:]
181 return value
182
183 def _obj_int(self):
184 """Read an integer in data (4 bytes)."""
185 if len(self.data) < 4:
186 self.data = ''
187 return 0
188 value = struct.unpack('>i', self.data[0:4])[0]
189 self.data = self.data[4:]
190 return value
191
192 def _obj_long(self):
193 """Read a long integer in data (length on 1 byte + value as string)."""
194 value = self._obj_len_data(1)
195 if value is None:
196 return None
197 return int(str(value))
198
199 def _obj_str(self):
200 """Read a string in data (length on 4 bytes + content)."""
201 value = self._obj_len_data(4)
202 if value is None:
203 return None
204 return str(value)
205
206 def _obj_buffer(self):
207 """Read a buffer in data (length on 4 bytes + data)."""
208 return self._obj_len_data(4)
209
210 def _obj_ptr(self):
211 """Read a pointer in data (length on 1 byte + value as string)."""
212 value = self._obj_len_data(1)
213 if value is None:
214 return None
215 return '0x%s' % str(value)
216
217 def _obj_time(self):
218 """Read a time in data (length on 1 byte + value as string)."""
219 value = self._obj_len_data(1)
220 if value is None:
221 return None
f8bbe7b6 222 return int(str(value))
7dcf23b1 223
c738936b 224 def _obj_hashtable(self):
77df9d06
SH
225 """
226 Read a hashtable in data
227 (type for keys + type for values + count + items).
228 """
c738936b
SH
229 type_keys = self._obj_type()
230 type_values = self._obj_type()
231 count = self._obj_int()
be3c1eda 232 hashtable = WeechatDict()
15380bce 233 for i in range(0, count):
c738936b
SH
234 key = self._obj_cb[type_keys]()
235 value = self._obj_cb[type_values]()
236 hashtable[key] = value
237 return hashtable
238
7dcf23b1
SH
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(',')
246 keys_types = []
be3c1eda 247 dict_keys = WeechatDict()
7dcf23b1
SH
248 for key in list_keys:
249 items = key.split(':')
250 keys_types.append(items)
251 dict_keys[items[0]] = items[1]
252 items = []
15380bce 253 for i in range(0, count):
be3c1eda
SH
254 item = WeechatDict()
255 item['__path'] = []
7dcf23b1 256 pointers = []
15380bce 257 for p in range(0, len(list_path)):
7dcf23b1
SH
258 pointers.append(self._obj_ptr())
259 for key, objtype in keys_types:
260 item[key] = self._obj_cb[objtype]()
261 item['__path'] = pointers
262 items.append(item)
263 return {'path': list_path,
264 'keys': dict_keys,
265 'count': count,
266 'items': items,
267 }
268
269 def _obj_info(self):
270 """Read an info in data."""
271 name = self._obj_str()
272 value = self._obj_str()
273 return (name, value)
274
275 def _obj_infolist(self):
276 """Read an infolist in data."""
277 name = self._obj_str()
278 count_items = self._obj_int()
279 items = []
15380bce 280 for i in range(0, count_items):
7dcf23b1 281 count_vars = self._obj_int()
be3c1eda 282 variables = WeechatDict()
15380bce 283 for v in range(0, count_vars):
7dcf23b1
SH
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}
290
4b44d000
SH
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()
295 values = []
296 for i in range(0, count_values):
297 values.append(self._obj_cb[type_values]())
298 return values
299
7b4aefb2 300 def decode(self, data, separator='\n'):
7dcf23b1
SH
301 """Decode binary data and return list of objects."""
302 self.data = data
303 size = len(self.data)
304 size_uncompressed = size
305 uncompressed = None
306 # uncompress data (if it is compressed)
307 compression = struct.unpack('b', self.data[4:5])[0]
308 if compression:
309 uncompressed = zlib.decompress(self.data[5:])
310 size_uncompressed = len(uncompressed) + 5
77df9d06
SH
311 uncompressed = '%s%s%s' % (struct.pack('>i', size_uncompressed),
312 struct.pack('b', 0), uncompressed)
7dcf23b1 313 self.data = uncompressed
9587cb0a
SH
314 else:
315 uncompressed = self.data[:]
7dcf23b1
SH
316 # skip length and compression flag
317 self.data = self.data[5:]
318 # read id
319 msgid = self._obj_str()
320 if msgid is None:
321 msgid = ''
322 # read objects
7b4aefb2 323 objects = WeechatObjects(separator=separator)
7dcf23b1
SH
324 while len(self.data) > 0:
325 objtype = self._obj_type()
326 value = self._obj_cb[objtype]()
7b4aefb2 327 objects.append(WeechatObject(objtype, value, separator=separator))
77df9d06
SH
328 return WeechatMessage(size, size_uncompressed, compression,
329 uncompressed, msgid, objects)
7dcf23b1
SH
330
331
332def hex_and_ascii(data, bytes_per_line=10):
333 """Convert a QByteArray to hex + ascii output."""
141c8d30 334 num_lines = ((len(data) - 1) // bytes_per_line) + 1
7dcf23b1
SH
335 if num_lines == 0:
336 return ''
337 lines = []
15380bce 338 for i in range(0, num_lines):
7dcf23b1
SH
339 str_hex = []
340 str_ascii = []
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)
346 else:
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)