copyright notices
[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#
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
b0cfbfce
IJ
25
26end = b'\300'
27esc = b'\333'
28esc_end = b'\334'
29esc_esc = b'\335'
30delimiter = end
31
32def encode(packet):
33 return (packet
34 .replace(esc, esc + esc_esc)
35 .replace(end, esc + esc_end))
36
7fa9c132 37def decode(data, keep_tail=False):
6f387df3 38 #print('DECODE ', repr(data))
b0cfbfce 39 out = []
7fa9c132
IJ
40 inp = data.split(end)
41 tail = []
42 if keep_tail:
43 tail.append(inp.pop())
44 for packet in inp:
b0cfbfce
IJ
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
e8fcf3b7 57 else: raise ValueError('invalid SLIP escape 0%o %#x' % (ck, ck))
b0cfbfce
IJ
58 packet = packet[eix+2 : ]
59 out.append(pdata)
b68c0739 60 #print('DECODED ', repr(out))
7fa9c132 61 out += tail
b0cfbfce
IJ
62 return out
63# -*- python -*-
64