from codec import DNSCodec
from codec import DNSRequestType
from codec import DNSResponseType

import struct

class DNSPacketFactory:
	request_factory = DNSRequestType
	response_factory = DNSResponseType

	def __init__(self, definitions):
		self.codec = DNSCodec(definitions)

	def serializeRequest(self, request, extended=False):
		encoded = self.codec.encodeRequest(request)
		if extended:
			encoded = struct.pack('>Hs', len(encoded), encoded)

		return encoded

	def normalizeRequest(self, request_s, extended=False):
		if extended:
			length, request_s = struct.unpack('>Hs', request_s)
			if length != len(request_s):
				request_s = ''

		return self.codec.decodeRequest(request_s)

	def createRequestString(self, identifier, request_type, request_name, extended=False):
		request = self.request_factory(identifier)
		request.addQuestion(request_type, request_name)

		encoded = self.codec.encodeRequest(request)
		if extended:
			encoded = struct.pack('>Hs', len(encoded), encoded)

		return encoded

	def serializeResponse(self, response, extended=False):
		encoded = self.codec.encodeResponse(response)
		if extended:
			encoded = struct.pack('>Hs', len(encoded), encoded)

		return encoded

	def normalizeResponse(self, response_s, extended=False):
		if extended:
			length, request_s = struct.unpack('>Hs', response_s)
			if length != len(response_s):
				request_s = ''

		return self.codec.decodeResponse(response_s)

@@ -405,33 +405,32 @@
  struct.pack('%3EH
-s
 ', len(encoded),
@@ -424,33 +424,35 @@
 len(encoded)
-,
+) +
  encoded
 )%0A%0A%09%09return 
@@ -431,33 +431,32 @@
 oded)) + encoded
-)
 %0A%0A%09%09return encod
@@ -533,33 +533,25 @@
 ded:%0A%09%09%09
+(
 length,
- request_s
+)
  = struc
@@ -562,20 +562,20 @@
 pack('%3EH
-s
 ', 
+(
 request_
@@ -575,17 +575,61 @@
 equest_s
-)
+ + '%5C0%5C0')%5B:2%5D)%0A%09%09%09request_s = request_s%5B2:%5D%0A
 %0A%09%09%09if l
@@ -984,33 +984,32 @@
  struct.pack('%3EH
-s
 ', len(encoded),
@@ -1003,33 +1003,35 @@
 len(encoded)
-,
+) +
  encoded
 )%0A%0A%09%09return 
@@ -1010,33 +1010,32 @@
 oded)) + encoded
-)
 %0A%0A%09%09return encod
@@ -1185,17 +1185,16 @@
 pack('%3EH
-s
 ', len(e
@@ -1204,17 +1204,19 @@
 ded)
-,
+) +
  encoded
 )%0A%0A%09
@@ -1211,17 +1211,16 @@
  encoded
-)
 %0A%0A%09%09retu
@@ -1311,25 +1311,17 @@
 %0A%09%09%09
+(
 length,
- request_s
+)
  = s
@@ -1340,12 +1340,12 @@
 ('%3EH
-s
 ', 
+(
 resp
@@ -1350,17 +1350,63 @@
 sponse_s
-)
+ + '%5C0%5C0')%5B:2%5D)%0A%09%09%09response_s = response_s%5B2:%5D%0A
 %0A%09%09%09if l

Fix use of pack and unpack