licence: make client GPLv3+, not AGPLv3+exception
[hippotat] / hippotatlib / slip.py
CommitLineData
0256fc10
IJ
1# -*- python -*-
2#
3# Hippotat - Asinine IP Over HTTP program
4# hippotatlib/slip.py - SLIP handling
5#
6# Copyright 2017 Ian Jackson
7#
f85d143f 8# GPLv3+
0256fc10 9#
f85d143f
IJ
10# This program 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.
0256fc10 14#
f85d143f
IJ
15# This program 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.
19#
20# You should have received a copy of the GNU General Public License
21# along with this program, in the file GPLv3. If not,
22# see <http://www.gnu.org/licenses/>.
0256fc10 23
b0cfbfce
IJ
24
25end = b'\300'
26esc = b'\333'
27esc_end = b'\334'
28esc_esc = b'\335'
29delimiter = end
30
31def encode(packet):
32 return (packet
33 .replace(esc, esc + esc_esc)
34 .replace(end, esc + esc_end))
35
7fa9c132 36def decode(data, keep_tail=False):
6f387df3 37 #print('DECODE ', repr(data))
b0cfbfce 38 out = []
7fa9c132
IJ
39 inp = data.split(end)
40 tail = []
41 if keep_tail:
42 tail.append(inp.pop())
43 for packet in inp:
b0cfbfce
IJ
44 pdata = b''
45 while True:
46 eix = packet.find(esc)
47 if eix == -1:
48 pdata += packet
49 break
50 #print('ESC ', repr((pdata, packet, eix)))
51 pdata += packet[0 : eix]
52 ck = packet[eix+1]
53 #print('ESC... %o' % ck)
54 if ck == esc_esc[0]: pdata += esc
55 elif ck == esc_end[0]: pdata += end
e8fcf3b7 56 else: raise ValueError('invalid SLIP escape 0%o %#x' % (ck, ck))
b0cfbfce
IJ
57 packet = packet[eix+2 : ]
58 out.append(pdata)
b68c0739 59 #print('DECODED ', repr(out))
7fa9c132 60 out += tail
b0cfbfce
IJ
61 return out
62# -*- python -*-
63