chiark / gitweb /
copyright notices
[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 # This program is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU Affero General Public License as
10 # published by the Free Software Foundation, either version 3 of the
11 # License, or (at your option) any later version, with the "CAF Login
12 # Exception" as published by Ian Jackson (version 2, or at your option
13 # any later version) as an Additional Permission.
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 Affero General Public License for more details.
19 #
20 # You should have received a copy of the GNU Affero General Public
21 # License and the CAF Login Exception along with this program, in the
22 # file AGPLv3+CAFv2.  If not, email Ian Jackson
23 # <ijackson@chiark.greenend.org.uk>.
24
25
26 end = b'\300'
27 esc = b'\333'
28 esc_end = b'\334'
29 esc_esc = b'\335'
30 delimiter = end
31
32 def encode(packet):
33   return (packet
34           .replace(esc, esc + esc_esc)
35           .replace(end, esc + esc_end))
36
37 def decode(data, keep_tail=False):
38   #print('DECODE ', repr(data))
39   out = []
40   inp = data.split(end)
41   tail = []
42   if keep_tail:
43     tail.append(inp.pop())
44   for packet in inp:
45     pdata = b''
46     while True:
47       eix = packet.find(esc)
48       if eix == -1:
49         pdata += packet
50         break
51       #print('ESC ', repr((pdata, packet, eix)))
52       pdata += packet[0 : eix]
53       ck = packet[eix+1]
54       #print('ESC... %o' % ck)
55       if   ck == esc_esc[0]: pdata += esc
56       elif ck == esc_end[0]: pdata += end
57       else: raise ValueError('invalid SLIP escape 0%o %#x' % (ck, ck))
58       packet = packet[eix+2 : ]
59     out.append(pdata)
60   #print('DECODED ', repr(out))
61   out += tail
62   return out
63 # -*- python -*-
64