Package dpkt :: Module ppp
[hide private]
[frames] | no frames]

Source Code for Module dpkt.ppp

  1  # $Id: ppp.py 65 2010-03-26 02:53:51Z dugsong $ 
  2  # -*- coding: utf-8 -*- 
  3  """Point-to-Point Protocol.""" 
  4  from __future__ import absolute_import 
  5   
  6  import struct 
  7   
  8  from . import dpkt 
  9   
 10  # XXX - finish later 
 11   
 12  # http://www.iana.org/assignments/ppp-numbers 
 13  PPP_IP = 0x21  # Internet Protocol 
 14  PPP_IP6 = 0x57  # Internet Protocol v6 
 15   
 16  # Protocol field compression 
 17  PFC_BIT = 0x01 
18 19 20 -class PPP(dpkt.Packet):
21 # Note: This class is subclassed in PPPoE 22 """Point-to-Point Protocol. 23 24 TODO: Longer class information.... 25 26 Attributes: 27 __hdr__: Header fields of PPP. 28 TODO. 29 """ 30 31 __hdr__ = ( 32 ('addr', 'B', 0xff), 33 ('cntrl', 'B', 3), 34 ('p', 'B', PPP_IP), 35 ) 36 _protosw = {} 37 38 @classmethod
39 - def set_p(cls, p, pktclass):
40 cls._protosw[p] = pktclass
41 42 @classmethod
43 - def get_p(cls, p):
44 return cls._protosw[p]
45
46 - def unpack(self, buf):
47 dpkt.Packet.unpack(self, buf) 48 if self.p & PFC_BIT == 0: 49 try: 50 self.p = struct.unpack('>H', buf[2:4])[0] 51 except struct.error: 52 raise dpkt.NeedData 53 self.data = self.data[1:] 54 try: 55 self.data = self._protosw[self.p](self.data) 56 setattr(self, self.data.__class__.__name__.lower(), self.data) 57 except (KeyError, struct.error, dpkt.UnpackError): 58 pass
59
60 - def pack_hdr(self):
61 try: 62 if self.p > 0xff: 63 return struct.pack('>BBH', self.addr, self.cntrl, self.p) 64 return dpkt.Packet.pack_hdr(self) 65 except struct.error as e: 66 raise dpkt.PackError(str(e))
67
68 69 -def __load_protos():
70 g = globals() 71 for k, v in g.items(): 72 if k.startswith('PPP_'): 73 name = k[4:] 74 modname = name.lower() 75 try: 76 mod = __import__(modname, g, level=1) 77 PPP.set_p(v, getattr(mod, name)) 78 except (ImportError, AttributeError): 79 continue
80
81 82 -def _mod_init():
83 """Post-initialization called when all dpkt modules are fully loaded""" 84 if not PPP._protosw: 85 __load_protos()
86
87 88 -def test_ppp():
89 # Test protocol compression 90 s = b"\xff\x03\x21" 91 p = PPP(s) 92 assert p.p == 0x21 93 94 s = b"\xff\x03\x00\x21" 95 p = PPP(s) 96 assert p.p == 0x21
97
98 99 -def test_ppp_short():
100 s = b"\xff\x03\x00" 101 102 import pytest 103 pytest.raises(dpkt.NeedData, PPP, s)
104
105 106 -def test_packing():
107 p = PPP() 108 assert p.pack_hdr() == b"\xff\x03\x21" 109 110 p.p = 0xc021 # LCP 111 assert p.pack_hdr() == b"\xff\x03\xc0\x21"
112 113 114 if __name__ == '__main__': 115 # Runs all the test associated with this class/file 116 test_ppp() 117