2012-08-21 14:21:11 +09:00
|
|
|
# Copyright (C) 2012 Nippon Telegraph and Telephone Corporation.
|
|
|
|
#
|
|
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
# you may not use this file except in compliance with the License.
|
|
|
|
# You may obtain a copy of the License at
|
|
|
|
#
|
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
#
|
|
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
|
|
# implied.
|
|
|
|
# See the License for the specific language governing permissions and
|
|
|
|
# limitations under the License.
|
|
|
|
|
|
|
|
import struct
|
2013-03-29 12:50:58 +09:00
|
|
|
|
2012-08-21 14:21:11 +09:00
|
|
|
from . import packet_base
|
2012-08-27 11:37:29 +09:00
|
|
|
from . import packet_utils
|
|
|
|
import ipv4
|
2012-08-21 14:21:11 +09:00
|
|
|
|
|
|
|
|
|
|
|
class udp(packet_base.PacketBase):
|
|
|
|
_PACK_STR = '!HHHH'
|
2012-08-28 08:13:50 +09:00
|
|
|
_MIN_LEN = struct.calcsize(_PACK_STR)
|
2012-08-21 14:21:11 +09:00
|
|
|
|
2012-10-11 17:19:57 +09:00
|
|
|
def __init__(self, src_port, dst_port, total_length=0, csum=0):
|
2012-08-21 14:21:11 +09:00
|
|
|
super(udp, self).__init__()
|
|
|
|
self.src_port = src_port
|
|
|
|
self.dst_port = dst_port
|
2012-10-11 17:19:57 +09:00
|
|
|
self.total_length = total_length
|
2012-08-21 14:21:11 +09:00
|
|
|
self.csum = csum
|
2012-10-11 17:19:57 +09:00
|
|
|
self.length = udp._MIN_LEN
|
2012-08-21 14:21:11 +09:00
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def parser(cls, buf):
|
2012-10-11 17:19:57 +09:00
|
|
|
(src_port, dst_port, total_length, csum) = struct.unpack_from(
|
|
|
|
cls._PACK_STR, buf)
|
|
|
|
msg = cls(src_port, dst_port, total_length, csum)
|
2012-08-21 14:21:11 +09:00
|
|
|
return msg, None
|
|
|
|
|
2012-08-27 11:37:24 +09:00
|
|
|
def serialize(self, payload, prev):
|
2012-10-11 17:19:57 +09:00
|
|
|
if self.total_length == 0:
|
|
|
|
self.total_length = udp._MIN_LEN + len(payload)
|
2012-08-27 11:37:29 +09:00
|
|
|
h = struct.pack(udp._PACK_STR, self.src_port, self.dst_port,
|
2012-10-11 17:19:57 +09:00
|
|
|
self.total_length, self.csum)
|
2012-08-27 11:37:29 +09:00
|
|
|
if self.csum == 0:
|
2012-10-11 17:19:57 +09:00
|
|
|
ph = struct.pack('!IIBBH', prev.src, prev.dst, 0, 17,
|
|
|
|
self.total_length)
|
2012-08-27 11:37:29 +09:00
|
|
|
f = ph + h + payload
|
2013-03-29 12:50:58 +09:00
|
|
|
self.csum = packet_utils.checksum(f)
|
2012-08-27 11:37:29 +09:00
|
|
|
h = struct.pack(udp._PACK_STR, self.src_port, self.dst_port,
|
2012-10-11 17:19:57 +09:00
|
|
|
self.total_length, self.csum)
|
2012-08-27 11:37:29 +09:00
|
|
|
return h
|