chiark / gitweb /
Revert "Fix publish version"
[hippotat.git] / hippotatlib / slip.py
1 # -*- python -*-
2 #
3 # Hippotat - Asinine IP Over HTTP program
4 # hippotatlib/slip.py - SLIP handling
5 #
6 # Copyright 2017 Ian Jackson
7 #
8 # GPLv3+
9 #
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.
14 #
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/>.
23
24
25 end = b'\300'
26 esc = b'\333'
27 esc_end = b'\334'
28 esc_esc = b'\335'
29 delimiter = end
30
31 def encode(packet):
32   return (packet
33           .replace(esc, esc + esc_esc)
34           .replace(end, esc + esc_end))
35
36 def decode(data, keep_tail=False):
37   #print('DECODE ', repr(data))
38   out = []
39   inp = data.split(end)
40   tail = []
41   if keep_tail:
42     tail.append(inp.pop())
43   for packet in inp:
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
56       else: raise ValueError('invalid SLIP escape 0%o %#x' % (ck, ck))
57       packet = packet[eix+2 : ]
58     out.append(pdata)
59   #print('DECODED ', repr(out))
60   out += tail
61   return out
62 # -*- python -*-
63