def __init__(self, io, spec): self.codec = codec.Codec(io, spec) self.spec = spec self.FRAME_END = self.spec.constants.byname["frame_end"].id self.write = getattr(self, "write_%s_%s" % (self.spec.major, self.spec.minor)) self.read = getattr(self, "read_%s_%s" % (self.spec.major, self.spec.minor)) self.io = io
def read_8_0(self): c = self.codec tid = c.decode_octet() try: type = self.spec.constants.byid[tid].name except KeyError: if tid == ord('A') and c.unpack("!3s") == "MQP": _, _, major, minor = c.unpack("4B") raise VersionError("client: %s-%s, server: %s-%s" % (self.spec.major, self.spec.minor, major, minor)) else: raise FramingError("unknown frame type: %s" % tid) try: channel = c.decode_short() body = c.decode_longstr() dec = codec.Codec(StringIO(body), self.spec) frame = Frame.DECODERS[type].decode(self.spec, dec, len(body)) frame.channel = channel end = c.decode_octet() if end != self.FRAME_END: garbage = "" while end != self.FRAME_END: garbage += chr(end) end = c.decode_octet() raise FramingError("frame error: expected %r, got %r" % (self.FRAME_END, garbage)) return frame except EOF: # An EOF caught here can indicate an error decoding the frame, # rather than that a disconnection occurred,so it's worth logging it. log.exception("Error occurred when reading frame with tid %s" % tid) raise
def decode(spec, dec): c = codec.Codec(StringIO(dec.decode_longstr())) klass = spec.classes.byid[c.decode_short()] weight = c.decode_short() size = c.decode_longlong() # property flags bits = [] while True: flags = c.decode_short() for i in range(15, 0, -1): if flags >> i & 0x1 != 0: bits.append(True) else: bits.append(False) if flags & 0x1 == 0: break # properties properties = {} for b, f in zip(bits, klass.fields): if b: # Note: decode returns a unicode u'' string but only # plain '' strings can be used as keywords so we need to # stringify the names. properties[str(f.name)] = c.decode(f.type) return Header(klass, weight, size, **properties)
def decode(spec, dec): enc = dec.decode_longstr() c = codec.Codec(StringIO(enc)) klass = spec.classes.byid[c.decode_short()] meth = klass.methods.byid[c.decode_short()] args = tuple([c.decode(f.type) for f in meth.fields]) return Method(meth, *args)
def encode(self, enc): buf = StringIO() c = codec.Codec(buf) c.encode_short(self.klass.id) c.encode_short(self.weight) c.encode_longlong(self.size) # property flags nprops = len(self.klass.fields) flags = 0 for i in range(nprops): f = self.klass.fields.items[i] flags <<= 1 if self.properties.get(f.name) != None: flags |= 1 # the last bit indicates more flags if i > 0 and (i % 15) == 0: flags <<= 1 if nprops > (i + 1): flags |= 1 c.encode_short(flags) flags = 0 flags <<= ((16 - (nprops % 15)) % 16) c.encode_short(flags) # properties for f in self.klass.fields: v = self.properties.get(f.name) if v != None: c.encode(f.type, v) c.flush() enc.encode_longstr(buf.getvalue())
def read_8_0(self): c = self.codec tid = c.decode_octet() try: type = self.spec.constants.byid[tid].name except KeyError: if tid == ord('A') and c.unpack("!3s") == "MQP": _, _, major, minor = c.unpack("4B") raise VersionError( "client: %s-%s, server: %s-%s" % (self.spec.major, self.spec.minor, major, minor)) else: raise FramingError("unknown frame type: %s" % tid) channel = c.decode_short() body = c.decode_longstr() dec = codec.Codec(StringIO(body), self.spec) frame = Frame.DECODERS[type].decode(self.spec, dec, len(body)) frame.channel = channel end = c.decode_octet() if end != self.FRAME_END: garbage = "" while end != self.FRAME_END: garbage += chr(end) end = c.decode_octet() raise "frame error: expected %r, got %r" % (self.FRAME_END, garbage) return frame
def read_0_10(self): c = self.codec flags = c.decode_octet() # TODO: currently ignoring flags framing_version = (flags & 0xc0) >> 6 if framing_version != 0: raise FramingError("frame error: unknown framing version") type = self.spec.constants.byid[c.decode_octet()].name frame_size = c.decode_short() if frame_size < 12: # TODO: Magic number (frame header size) raise FramingError("frame error: frame size too small") reserved1 = c.decode_octet() field = c.decode_octet() subchannel = field & 0x0f channel = c.decode_short() reserved2 = c.decode_long() # TODO: reserved maybe need to ensure 0 if (flags & 0x30) != 0 or reserved1 != 0 or (field & 0xf0) != 0: raise FramingError("frame error: reserved bits not all zero") body_size = frame_size - 12 # TODO: Magic number (frame header size) body = c.read(body_size) dec = codec.Codec(StringIO(body), self.spec) try: frame = Frame.DECODERS[type].decode(self.spec, dec, len(body)) except EOF: raise FramingError("truncated frame body: %r" % body) frame.channel = channel frame.subchannel = subchannel end = c.decode_octet() if end != self.FRAME_END: garbage = "" while end != self.FRAME_END: garbage += chr(end) end = c.decode_octet() raise FramingError("frame error: expected %r, got %r" % (self.FRAME_END, garbage)) return frame
def translateLine(self, forTrans, tEn, oEn): coder = codec.Codec() tran = translator.Translator(self.opArg) decodedStr = coder.decodeString(forTrans, tEn) translated = tran.translateString(decodedStr) codedStr = coder.codeTranslated(translated, oEn) return codedStr
def encode(self, enc): buf = StringIO() c = codec.Codec(buf) c.encode_short(self.method.klass.id) c.encode_short(self.method.id) for field, arg in zip(self.method.fields, self.args): c.encode(field.type, arg) c.flush() enc.encode_longstr(buf.getvalue())
def write_8_0(self, frame): c = self.codec c.encode_octet(self.spec.constants.byname[frame.type].id) c.encode_short(frame.channel) body = StringIO() enc = codec.Codec(body, self.spec) frame.encode(enc) enc.flush() c.encode_longstr(body.getvalue()) c.encode_octet(self.FRAME_END)
def __init__(self, parent, address): """ """ self.parent = parent self.address = address self.id = None self.buf = '' # init the HTTP encoder/decoder self.httpCodec = codec.Codec( parent=self, octetStreamSupport=self.parent.cfg['http_octet_stream_support'], manStreamSupport=self.parent.cfg['http_man_stream_support'], truncateBody=self.parent.cfg['http_truncate_body'], strictMode=self.parent.cfg['http_strict_mode'], websocketMode=self.parent.cfg['http_websocket_mode'])
def readNext(self): coder = codec.Codec() output = {'type': None, 'value': None} forTrans = ' ' line = self.file.readline() if line.isspace(): return {'type': 'empty'} if len(line) == 0: return False if re.search(r"^#.*", line) is not None: output['type'] = 'comment' output['value'] = line return output pos = re.search(r"[=]", line) if pos is not None: befEqStr = line[0:pos.end()] aftEqStr = coder.elimBackslash( line[pos.end():-1]) # DO -1 zbog novih redova output['type'] = 'property' output['value'] = {'property': befEqStr, 'string': ' '} forTrans = '' forTrans += aftEqStr while True: line = self.file.readline() if len(line) == 0: output['value']['string'] = forTrans return output if line.isspace(): output['value']['string'] = forTrans return output noSpaces = coder.eliminatewhitespaces(line) forTrans += coder.elimBackslash(noSpaces)
def write_0_10(self, frame): c = self.codec flags = 0 if frame.bof: flags |= 0x08 if frame.eof: flags |= 0x04 if frame.bos: flags |= 0x02 if frame.eos: flags |= 0x01 c.encode_octet(flags) # TODO: currently fixed at ver=0, B=E=b=e=1 c.encode_octet(self.spec.constants.byname[frame.type].id) body = StringIO() enc = codec.Codec(body, self.spec) frame.encode(enc) enc.flush() frame_size = len(body.getvalue()) + 12 # TODO: Magic number (frame header size) c.encode_short(frame_size) c.encode_octet(0) # Reserved c.encode_octet(frame.subchannel & 0x0f) c.encode_short(frame.channel) c.encode_long(0) # Reserved c.write(body.getvalue()) c.encode_octet(self.FRAME_END)
def convertFile(self, en1, en2): #Napravi da bude modularno kao i translate con = convertor.Convertor(self.opArg) coder = codec.Codec() for line in self.tFile: self.countLine() if re.search(r"^#.*", line) is not None: self.oFile.write( line) # Uklanja razmak izmedju 2 linije istog komentara continue pos = re.search(r"[=]", line) if pos is not None: befEqStr = line[0:pos.end()] aftEqStr = line[pos.end():-1] self.oFile.write(befEqStr) decStri = coder.decodeString( aftEqStr, en1 ) # STRING -> DEKODIRANJE -> KONVERTOVANJE -> KODIRANJE -> ZAPIS conStri = con.convLine(decStri, True) codedStri = coder.codeString(conStri, en2) self.oFile.write(codedStri) self.oFile.write('\n') else: decStri = coder.decodeString(line, en1) # PRETRVORI U JEDNU FUNKCIJU conStri = con.convLine(decStri, False) codedStri = coder.codeString(conStri, en2) self.oFile.write(codedStri) self.oFile.close()
def test(): d = 2 c = c_codec.Codec(d, './librs.so') py = py_codec.Codec(d) n = 10 r = random.Random(0) for i in range(1000): x = [r.getrandbits(8) for i in range(n)] y_c = c.encode(x) y_py = py.encode(x) assert y_c == y_py z_py = py.decode(y_py) assert z_py == x z_c = c.decode(y_c) assert z_c == x return for _ in range(c.distance // 2): i = r.randrange(len(y)) err = r.getrandbits(8) y[i] = err z = c.decode(y) assert list(z) == list(x)
def __init__(self, parent, debug=False, name=None, senderIp=None, logEventSent=True, logEventReceived=True, hideOperations=False, cacheEnabled=True, agentSupport=False, agent=None, shared=False): """ This class enables to send/receive ARP packet. The lower layer is based on the Ethernet adapter. Cache support and dynamically updated. @param parent: parent testcase @type parent: testcase @param name: adapter name used with from origin/to destination (default=None) @type name: string/none @param senderIp: sender ip (default=None) @type senderIp: string/none @param hideOperations: hide all operations (default=False) @type hideOperations: boolean @param cacheEnabled: cache mechanism enabled (default=True) @type cacheEnabled: boolean @param debug: active debug mode (default=False) @type debug: boolean @param agentSupport: agent support to use a remote socket (default=False) @type agentSupport: boolean @param agent: agent to use when this mode is activated @type agent: string/None @param shared: shared adapter (default=False) @type shared: boolean """ # init adapter TestAdapterLib.Adapter.__init__(self, name=__NAME__, parent=parent, debug=debug, shared=shared, realname=name, agentSupport=agentSupport, agent=agent, caller=TestAdapterLib.caller(), agentType=AGENT_TYPE_EXPECTED) self.logEventSent = logEventSent self.logEventReceived = logEventReceived self.ether = AdapterEthernet.Sniffer( parent=parent, debug=debug, macResolution=True, logEventSent=False, logEventReceived=False, protocol2sniff=AdapterEthernet.ARP, parentName=__NAME__, agentSupport=agentSupport, agent=agent, shared=shared, name=name) # wrappers self.ether.onReceiving = self.onReceiving self.startListening = self.ether.startListening self.stopListening = self.ether.stopListening self.isSniffing = self.ether.isSniffing self.isSniffingFailed = self.ether.isSniffingFailed self.isStopped = self.ether.isStopped self.senderIp = senderIp # codec arp self.arpCodec = codec.Codec(parent=self) self.cfg = {} self.cfg['hide-operations'] = hideOperations self.cfg['cache-enabled'] = cacheEnabled self.cfg['agent-support'] = agentSupport if agentSupport: self.cfg['agent'] = agent self.cfg['agent-name'] = agent['name'] # used to recognize the response self.__sender_mac = '' self.__sender_ip = '' # cache self.cache = {} self.__checkConfig()
def __init__ (self, parent, bindIp = '', bindPort=0, destIp='127.0.0.1', destPort=23, destHost='', socketTimeout=10.0, socketFamily=AdapterIP.IPv4, doEcho=True, name=None, proxyType=AdapterTCP.PROXY_SOCKS4, proxyUserID='xtc', proxyIp='', proxyPort=3128, proxyHost='', proxyEnabled=False, debug=False, logEventSent=True, logEventReceived=True, parentName=None , agentSupport=False, agent=None, shared=False, saveContent=False): """ This class enable to use TELNET (rfc854) as client only, lower network layer (IP, Ethernet) are not controlable. @param parent: parent testcase @type parent: testcase @param name: adapter name used with from origin/to destination (default=None) @type name: string/none @param bindIp: bind on ip (source ip) @type bindIp: string @param bindPort: bind on port (source port) @type bindPort: integer @param destIp: destination ip @type destIp: string @param destPort: destination port @type destPort: integer @param destHost: destination host (automatic dns resolution) @type destHost: string @param proxyType: SutAdapters.TCP.PROXY_SOCKS4 | SutAdapters.TCP.PROXY_SOCKS5 (default=PROXY_SOCKS4) @type proxyType: strconstant @param proxyUserID: user id with socks (default=xtc) @type proxyUserID: string @param proxyIp: proxy ip @type proxyIp: string @param proxyPort: proxy port @type proxyPort: integer @param proxyHost: proxy host (automatic dns resolution) @type proxyHost: string @param proxyEnabled: True to support proxy (default=False) @type proxyEnabled: boolean @param socketFamily: SutAdapters.IP.IPv4 (default) | SutAdapters.IP.IPv6 @type socketFamily: intconstant @param socketTimeout: timeout to connect in second (default=1s) @type socketTimeout: float @param doEcho: send do echo command on True @type doEcho: boolean @param debug: True to activate debug mode (default=False) @type debug: boolean @param agentSupport: agent support to use a remote socket (default=False) @type agentSupport: boolean @param agent: agent to use when this mode is activated @type agent: string/None @param shared: shared adapter (default=False) @type shared: boolean @param saveContent: save content in the private storage (default=False) @type saveContent: boolean """ # check agent if agentSupport and agent is None: raise TestAdapterLib.ValueException(TestAdapterLib.caller(), "Agent cannot be undefined!" ) if agentSupport: if not isinstance(agent, dict) : raise TestAdapterLib.ValueException(TestAdapterLib.caller(), "agent argument is not a dict (%s)" % type(agent) ) if not len(agent['name']): raise TestAdapterLib.ValueException(TestAdapterLib.caller(), "agent name cannot be empty" ) if unicode(agent['type']) != unicode(AGENT_TYPE_EXPECTED): raise TestAdapterLib.ValueException(TestAdapterLib.caller(), 'Bad agent type: %s, expected: %s' % (agent['type'], unicode(AGENT_TYPE_EXPECTED)) ) if not isinstance(bindPort, int): raise TestAdapterLib.ValueException(TestAdapterLib.caller(), "bindPort argument is not a integer (%s)" % type(bindPort) ) if not isinstance(destPort, int): raise TestAdapterLib.ValueException(TestAdapterLib.caller(), "destPort argument is not a integer (%s)" % type(destPort) ) if not isinstance(proxyPort, int): raise TestAdapterLib.ValueException(TestAdapterLib.caller(), "proxyPort argument is not a integer (%s)" % type(proxyPort) ) # init adapter TestAdapterLib.Adapter.__init__(self, name = __NAME__, parent = parent, realname=name, shared=shared, debug=debug, agentSupport=agentSupport, agent=agent) if parentName is not None: TestAdapterLib.Adapter.setName(self, name="%s>%s" % (parentName,__NAME__) ) self.logEventSent = logEventSent self.logEventReceived = logEventReceived # prepare tcp adapter self.tcp = AdapterTCP.Client(parent=parent, bindIp = bindIp, bindPort=bindPort, destinationIp=destIp, destinationPort=destPort, destinationHost=destHost, socketTimeout=socketTimeout, socketFamily=socketFamily, inactivityTimeout=0, proxyType=proxyType, proxyUserID=proxyUserID, proxyIp=proxyIp, proxyPort=proxyPort, proxyHost=proxyHost, proxyEnabled=proxyEnabled, separatorDisabled=True, sslSupport=False, name=name, debug=debug, logEventSent=False, logEventReceived=False, shared=shared, parentName=__NAME__, agentSupport=agentSupport, agent=agent) # callback tcp self.tcp.handleIncomingData = self.onIncomingData self.tcp.handleNoMoreData = self.onNoMoreData # telnet options self.cfg = {} # proxy self.cfg['proxy-enabled'] = proxyEnabled # option to sent self.cfg['do-echo'] = doEcho # ip layer self.cfg['telnet-source-ip'] = bindIp self.cfg['telnet-source-port'] = int(bindPort) self.cfg['telnet-destination-ip'] = destIp self.cfg['telnet-destination-port'] = int(destPort) # options self.cfg['telnet-remote-opts'] = [] self.cfg['telnet-save-content'] = saveContent # agent self.cfg['agent-support'] = agentSupport if self.cfg['agent-support'] : self.cfg['agent'] = agent self.cfg['agent-name'] = agent['name'] self.doEchoSent = False self.buf = '' # init the telnet encoder/decoder self.telnetCodec = codec.Codec(parent=self) if self.cfg['telnet-save-content']: self.warning("TELNET AdapterID=%s" % self.getAdapterId() )
def __init__(self, parent, name=None, debug=False, shared=False, agentSupport=False, agent=None, bindIp='', bindPort=0): """ This class enables to send NTP request. @param parent: parent testcase @type parent: testcase @param name: adapter name used with from origin/to destination (default=None) @type name: string/none @param debug: active debug mode (default=False) @type debug: boolean @param shared: shared adapter (default=False) @type shared: boolean @param agentSupport: agent support (default=False) @type agentSupport: boolean @param agent: agent to use (default=None) @type agent: string/none @param bindIp: bind on ip (source ip) @type bindIp: string @param bindPort: bind on port (source port) @type bindPort: integer """ TestAdapter.Adapter.__init__(self, name=__NAME__, parent=parent, debug=debug, realname=name, agentSupport=agentSupport, agent=agent, shared=shared, caller=TestAdapter.caller(), agentType=AGENT_TYPE_EXPECTED) self.parent = parent self.codecX2D = Xml2Dict.Xml2Dict() self.codecD2X = Dict2Xml.Dict2Xml(coding=None) self.ntpCodec = codec.Codec(parent=self) # init udp layer self.ADP_UDP = AdapterUDP.Client(parent=parent, debug=debug, name=name, bindIp=bindIp, bindPort=bindPort, destinationIp='', destinationPort=0, destinationHost='', socketFamily=AdapterIP.IPv4, separatorDisabled=True, inactivityTimeout=0, logEventSent=False, logEventReceived=False, parentName=__NAME__, agentSupport=agentSupport, agent=agent, shared=shared) # callback udp self.ADP_UDP.handleIncomingData = self.onIncomingData self.cfg = {} self.cfg['agent-support'] = agentSupport if agentSupport: self.cfg['agent'] = agent self.cfg['agent-name'] = agent['name'] self.__checkConfig()
def __init__(self, parent, debug=False, logEventSent=True, logEventReceived=True, name=None, ipVersion=AdapterIP.IPv4, port2sniff=codec.ALL, parentName=None, inactivityTimeout=0.0, separatorIn='0x00', separatorOut='0x00', separatorDisabled=True, agentSupport=False, agent=None, shared=False): """ This class enables to send/receive TCP data. The lower layer is based on the IP adapter. Support data separator for upper application, tcp options supported. @param parent: parent testcase @type parent: testcase @param name: adapter name used with from origin/to destination (default=None) @type name: string/none @param debug: active debug mode (default=False) @type debug: boolean @param separatorIn: data separator (default=0x00) @type separatorIn: string @param port2sniff: udp port to sniff @type port2sniff: integer @param separatorOut: data separator (default=0x00) @type separatorOut: string @param separatorDisabled: disable the separator feature, if this feature is enabled then data are buffered until the detection of the separator (default=False) @type separatorDisabled: boolean @param inactivityTimeout: feature disabled by default (value=0.0) @type inactivityTimeout: float @param agentSupport: agent support to use a remote socket (default=False) @type agentSupport: boolean @param agent: agent to use when this mode is activated @type agent: string/None @param shared: shared adapter (default=False) @type shared: boolean """ # init adapter TestAdapterLib.Adapter.__init__(self, name = client.__NAME__, parent = parent, debug=debug, realname=name, shared=shared, agentSupport=agentSupport, agent=agent, caller=TestAdapterLib.caller(), agentType=AGENT_TYPE_EXPECTED) self.logEventSent = logEventSent self.logEventReceived = logEventReceived # tcp codec self.tcpCodec = codec.Codec(parent=self, testcase=parent, debug=debug, srcPort=port2sniff) # ip layer self.ip = AdapterIP.SnifferV4(parent=parent, debug=debug, protocol2sniff=AdapterIP.TCP, logEventSent=False, logEventReceived=False, parentName=client.__NAME__, agentSupport=agentSupport, agent=agent, shared=shared) if parentName is not None: self.ip.setname(name="%s>%s" % (parentName,client.__NAME__)) self.ip.onReceiving = self.onDecodeData self.cfg = {} self.cfg['port-to-sniff'] = port2sniff self.cfg['ip-version'] = ipVersion self.cfg['sep-in'] = separatorIn self.cfg['sep-out'] = separatorOut self.cfg['sep-disabled'] = separatorDisabled self.cfg['inactivity-timeout'] = inactivityTimeout self.cfg['agent-support'] = agentSupport if agentSupport: self.cfg['agent'] = agent self.cfg['agent-name'] = agent['name'] self.__checkConfig() self.buf = {}
def __init__(self, parent, debug=False, logEventSent=True, logEventReceived=True, ipVersion=AdapterIP.IPv4, port2sniff=codec.ALL, name=None, separatorIn='0x00', separatorOut='0x00', separatorDisabled=True, inactivityTimeout=0.0, parentName=None, agentSupport=False, agent=None, shared=False): """ This class enables to send/receive UDP data. The lower layer is based on the IP adapter. Support data separator for upper application and inactivity detection. @param parent: parent testcase @type parent: testcase @param name: adapter name used with from origin/to destination (default=None) @type name: string/none @param debug: active debug mode (default=False) @type debug: boolean @param separatorIn: data separator (default=0x00) @type separatorIn: string @param port2sniff: udp port to sniff @type port2sniff: integer @param separatorOut: data separator (default=0x00) @type separatorOut: string @param separatorDisabled: disable the separator feature, if this feature is enabled then data are buffered until the detection of the separator (default=False) @type separatorDisabled: boolean @param inactivityTimeout: feature disabled by default (value=0.0) @type inactivityTimeout: float @param agentSupport: agent support to use a remote socket (default=False) @type agentSupport: boolean @param agent: agent to use when this mode is activated @type agent: string/None @param shared: shared adapter (default=False) @type shared: boolean """ # check agent if agentSupport and agent is None: raise TestAdapterLib.ValueException(TestAdapterLib.caller(), "Agent cannot be undefined!") if agentSupport: if not isinstance(agent, dict): raise TestAdapterLib.ValueException( TestAdapterLib.caller(), "agent argument is not a dict (%s)" % type(agent)) if not len(agent['name']): raise TestAdapterLib.ValueException( TestAdapterLib.caller(), "agent name cannot be empty") if unicode(agent['type']) != unicode(AGENT_TYPE_EXPECTED): raise TestAdapterLib.ValueException( TestAdapterLib.caller(), 'Bad agent type: %s, expected: %s' % (agent['type'], unicode(AGENT_TYPE_EXPECTED))) # init adapter TestAdapterLib.Adapter.__init__(self, name=client.__NAME__, parent=parent, debug=debug, shared=shared, realname=name, agentSupport=agentSupport, agent=agent) self.logEventSent = logEventSent self.logEventReceived = logEventReceived self.port2sniff = port2sniff # udp codec self.udpCodec = codec.Codec(parent=self, testcase=parent, debug=debug, srcPort=port2sniff) # init ip layer ## TODO: version IP self.ip = AdapterIP.SnifferV4(parent=parent, debug=debug, protocol2sniff=AdapterIP.UDP, logEventSent=False, logEventReceived=False, parentName=client.__NAME__, agentSupport=agentSupport, agent=agent, name=name, shared=shared) if parentName is not None: self.ip.setname(name="%s>%s" % (parentName, client.__NAME__)) self.ip.onReceiving = self.onDecodeData self.icmp = AdapterICMP.SnifferV4(parent=parent, debug=debug, lowerIpVersion=4, errorsOnly=True, logEventSent=False, logEventReceived=False, agentSupport=agentSupport, agent=agent, name=name, shared=shared) self.icmp.onIcmpError = self.onIcmpError self.cfg = {} self.cfg['ip-version'] = ipVersion self.cfg['sep-in'] = separatorIn self.cfg['sep-out'] = separatorOut self.cfg['sep-disabled'] = separatorDisabled self.cfg['inactivity-timeout'] = inactivityTimeout self.cfg['agent-support'] = agentSupport if agentSupport: self.cfg['agent'] = agent self.cfg['agent-name'] = agent['name'] self.__checkConfig() self.buf = {}
def __init__(self, parent, debug=False, macResolution=True, padding=True, logEventSent=True, logEventReceived=True, name=None, protocol2sniff=codec.ALL, parentName=None, agentSupport=False, agent=None, shared=False): """ This class enables to send/receive Ethernet II frame. @param parent: parent testcase @type parent: testcase @param name: adapter name used with from origin/to destination (default=None) @type name: string/none @param macResolution: mac address resolution (default=True) @type macResolution: boolean @param protocol2sniff: SutAdapters.Ethernet.ALL (default) | SutAdapters.Ethernet.IPv4 | SutAdapters.Ethernet.IPv6 | SutAdapters.Ethernet.ARP | SutAdapters.Ethernet.RARP | SutAdapters.Ethernet.DOT1Q | SutAdapters.Ethernet.SNMP @type protocol2sniff: strconstant @param padding: the data padding is necessary to avoid collisions. (default=True) @type padding: boolean @param debug: active debug mode (default=False) @type debug: boolean @param agentSupport: agent support to use a remote socket (default=False) @type agentSupport: boolean @param agent: agent to use when this mode is activated @type agent: string/None @param shared: shared adapter (default=False) @type shared: boolean """ # check agent if agentSupport and agent is None: raise TestAdapterLib.ValueException(TestAdapterLib.caller(), "Agent cannot be undefined!") if agentSupport: if not isinstance(agent, dict): raise TestAdapterLib.ValueException( TestAdapterLib.caller(), "agent argument is not a dict (%s)" % type(agent)) if not len(agent['name']): raise TestAdapterLib.ValueException( TestAdapterLib.caller(), "agent name cannot be empty") if unicode(agent['type']) != unicode(AGENT_TYPE_EXPECTED): raise TestAdapterLib.ValueException( TestAdapterLib.caller(), 'Bad agent type: %s, expected: %s' % (agent['type'], unicode(AGENT_TYPE_EXPECTED))) # init adapter TestAdapterLib.Adapter.__init__(self, name=__NAME__, parent=parent, debug=debug, shared=shared, realname=name, agentSupport=agentSupport, agent=agent) if parentName is not None: TestAdapterLib.Adapter.setName(self, name="%s>%s" % (parentName, __NAME__)) self.logEventSent = logEventSent self.logEventReceived = logEventReceived self.__mutex__ = threading.RLock() self.__mutex2__ = threading.RLock() self.parent = parent self.protocol2sniff = protocol2sniff self.sniffing = False self.socket = None self.src_mac = None self.mac_resolution = macResolution self.padding = padding self.etherCodec = codec.Codec(parent=self, macResolution=macResolution) self.cfg = {} self.cfg['src-eth'] = None # agent support self.cfg['agent-support'] = agentSupport if agentSupport: self.cfg['agent'] = agent self.cfg['agent-name'] = agent['name'] self.TIMER_ALIVE_AGT = TestAdapterLib.Timer(parent=self, duration=20, name="keepalive-agent", callback=self.aliveAgent, logEvent=False, enabled=True) self.__checkConfig() # initialize the agent with no data if agentSupport: self.prepareAgent(data={'shared': shared}) if self.agentIsReady(timeout=30) is None: raise TestAdapterLib.ValueException( TestAdapterLib.caller(), "Agent %s is not ready" % self.cfg['agent-name']) self.TIMER_ALIVE_AGT.start()
def __init__(self, parent, bindIp='', bindPort=0, destinationIp='127.0.0.1', proxyIp='', proxyPort=3128, proxyHost='', proxyEnabled=False, destinationPort=80, destinationHost='', name=None, debug=False, sslSupport=False, sslVersion=AdapterSSL.SSLv23, agentSupport=False, agent=None, shared=False, logEventSent=True, logEventReceived=True): """ Adapter for the websocket protocol according to the rfc 6455 Ssl and proxy support @param parent: parent testcase @type parent: testcase @param bindIp: source ip (default='') @type bindIp: string @param bindPort: source port (default=0) @type bindPort: integer @param destinationIp: destination ip @type destinationIp: string @param destinationPort: destination port (default: port 80) @type destinationPort: integer @param destinationHost: destination host (dns resolution) @type destinationHost: string @param proxyIp: proxy ip @type proxyIp: string @param proxyPort: proxy port @type proxyPort: integer @param proxyHost: proxy host (automatic dns resolution) @type proxyHost: string @param proxyEnabled: True to support proxy (default=False) @type proxyEnabled: boolean @param sslSupport: activate SSL channel (default=False) @type sslSupport: boolean @param sslVersion: SutAdapters.SSL.SSLv2 | SutAdapters.SSL.SSLv23 (default) | SutAdapters.SSL.SSLv3 | SutAdapters.SSL.TLSv1 | SutAdapters.SSL.TLSv11 | SutAdapters.SSL.TLSv12 @type sslVersion: strconstant @param name: adapter name used with from origin/to destination (default=None) @type name: string/none @param debug: active debug mode (default=False) @type debug: boolean @param agentSupport: agent support to use a remote socket (default=False) @type agentSupport: boolean @param agent: agent to use when this mode is activated @type agent: string/None @param shared: shared adapter (default=False) @type shared: boolean """ # init adapter TestAdapterLib.Adapter.__init__(self, name=__NAME__, parent=parent, debug=debug, realname=name, agentSupport=agentSupport, agent=agent, caller=TestAdapterLib.caller(), agentType=AGENT_TYPE_EXPECTED) self.codecX2D = Xml2Dict.Xml2Dict() self.codecD2X = Dict2Xml.Dict2Xml(coding=None) self.logEventSent = logEventSent self.logEventReceived = logEventReceived self.wsKey = None self.wsHanshakeSuccess = False self.wsMaxPayloadSize = codec.WEBSOCKET_MAX_BASIC_DATA1024 self.buf = '' self.cfg = {} self.cfg['dest-ip'] = destinationIp self.cfg['dest-port'] = destinationPort self.cfg['ssl-support'] = sslSupport # agent support self.cfg['agent-support'] = agentSupport if agentSupport: self.cfg['agent'] = agent self.cfg['agent-name'] = agent['name'] self.__checkConfig() self.ADP_HTTP = AdapterHTTP.Client(parent=parent, bindIp=bindIp, bindPort=bindPort, name=name, destinationIp=destinationIp, destinationPort=destinationPort, destinationHost=destinationHost, proxyIp=proxyIp, proxyPort=proxyPort, proxyHost=proxyHost, proxyEnabled=proxyEnabled, socketTimeout=300.0, socketFamily=4, websocketMode=True, saveContent=False, httpVersion='HTTP/1.1', httpAgent='ExtensiveTesting', httpConnection='close', httpChunckedData=False, sslSupport=sslSupport, sslVersion=sslVersion, checkCert='No', debug=debug, logEventSent=False, logEventReceived=False, truncateBody=False, agentSupport=agentSupport, agent=agent, shared=shared, strictMode=False) self.ADP_HTTP.handleIncomingResponse = self.handleIncomingHttpResponse self.ADP_HTTP.onWebsocketIncomingData = self.onWebsocketIncomingData self.wsCodec = codec.Codec(parent=self)
def __init__(self, parent, debug=False, name=None, bindIp='0.0.0.0', bindPort=0, destinationIp='', destinationHost='', destinationPort=0, socketFamily=AdapterIP.IPv4, logHighLevelEvents=True, logLowLevelEvents=False, recordRcvSound=False, recordSndSound=False, payloadType=SutLibraries.Codecs.A_G711U, defaultSound=SOUND_SINE_1K, rtpVersion=2, initialSeqNumber=None, ssrcValue=None, inactivityTimeout=2.0, sessionId=None, agentSupport=False, agent=None, shared=False): """ Raw RTP client. This class inherit from the UDP adapter. @param parent: parent testcase @type parent: testcase @param name: adapter name used with from origin/to destination (default=None) @type name: string/none @param bindIp: bind on ip @type bindIp: string @param bindPort: bind on port @type bindPort: integer @param destinationIp: destination ip @type destinationIp: string @param destinationPort: destination port @type destinationPort: integer @param destinationHost: destination host @type destinationHost: string @param logHighLevelEvents: log high level events (default=True) @type logHighLevelEvents: boolean @param logLowLevelEvents: log low level events (default=False) @type logLowLevelEvents: boolean @param recordRcvSound: bufferize the sound received and save the RTP flow in a rtp file. If the codec is supported then the flow is saved in a wave file. @type recordRcvSound: boolean @param recordSndSound: bufferize the sound sent and save the RTP flow in a rtp file. If the codec is supported then the flow is saved in a wave file. @type recordSndSound: boolean @param payloadType: SutLibraries.Codecs.A_G711U (default) | SutLibraries.Codecs.A_G711A @type payloadType: intconstant @param defaultSound: SutAdapters.RTP.SOUND_SINE_1K (default) | SutAdapters.RTP.SOUND_WHITE_NOISE | SutAdapters.RTP.SOUND_SILENCE @type defaultSound: intconstant @param rtpVersion: rtp version (default=2) @type rtpVersion: integer @param initialSeqNumber: initial sequence number @type initialSeqNumber: integer/none @param ssrcValue: ssrc @type ssrcValue: integer/none @param socketFamily: socket family @type socketFamily: string @param sessionId: session identifier for high level events @type sessionId: string/none @param debug: active debug mode (default=False) @type debug: boolean @param agentSupport: agent support to use a remote socket (default=False) @type agentSupport: boolean @param agent: agent to use when this mode is activated @type agent: string/None @param shared: shared adapter (default=False) @type shared: boolean """ # check agent if agentSupport and agent is None: raise TestAdapterLib.ValueException(TestAdapterLib.caller(), "Agent cannot be undefined!") if agentSupport: if not isinstance(agent, dict): raise TestAdapterLib.ValueException( TestAdapterLib.caller(), "agent argument is not a dict (%s)" % type(agent)) if not len(agent['name']): raise TestAdapterLib.ValueException( TestAdapterLib.caller(), "agent name cannot be empty") if unicode(agent['type']) != unicode(AGENT_TYPE_EXPECTED): raise TestAdapterLib.ValueException( TestAdapterLib.caller(), 'Bad agent type: %s, expected: %s' % (agent['type'], unicode(AGENT_TYPE_EXPECTED))) # init adapter TestAdapterLib.Adapter.__init__(self, name=__NAME__, parent=parent, debug=debug, shared=shared, realname=name, agentSupport=agentSupport, agent=agent) self.logHighLevelEvents = logHighLevelEvents self.logLowLevelEvents = logLowLevelEvents self.__testcase = parent self.__debugmode = debug # init udp layer self.udp = AdapterUDP.Client(parent=parent, debug=debug, name=name, bindIp=bindIp, bindPort=bindPort, destinationIp=destinationIp, destinationPort=destinationPort, destinationHost=destinationHost, socketFamily=socketFamily, separatorDisabled=True, inactivityTimeout=inactivityTimeout, logEventSent=False, logEventReceived=False, parentName=__NAME__, agentSupport=agentSupport, agent=agent, shared=shared) # callback udp self.udp.handleIncomingData = self.onIncomingData self.udp.preStopListening = self.stopSending self.udp.onInactivity = self.onInactivity # inherent udp functions self.startListening = self.udp.startListening self.sendData = self.udp.sendData self.isStopped = self.udp.isStopped self.isListening = self.udp.isListening self.hasReceivedData = self.udp.hasReceivedData self.setDestination = self.udp.setDestination self.setSource = self.udp.setSource # rtp options self.cfg = {} self.cfg['version-rtp'] = rtpVersion self.cfg['record-rcv-rtp'] = recordRcvSound self.cfg['record-snd-rtp'] = recordSndSound self.cfg['payload-type'] = payloadType self.cfg['default-sound'] = defaultSound self.cfg['framing-interval'] = float(0) self.cfg['initial-seq'] = initialSeqNumber self.cfg['ssrc-chosen'] = ssrcValue self.cfg['session-id'] = sessionId # agent self.cfg['agent-support'] = agentSupport if agentSupport: self.cfg['agent-name'] = agent['name'] # init the RTP encoder/decoder self.rtpCodec = codec.Codec(parent=self) self.bufIn = '' self.bufOut = '' self.buf_AudioET = None # audio encoding type # sending thread init self.rtpStreamer = streamer.Streamer() self.defaultPayloads = defaultpayloads.DefaultPayloads(parent=parent, debug=debug) self.sendingThread = SendingThread(parent=self) self.sendingThread.start() # high events self.last_pkt_sent = None self.last_pkt_recv = None # check config self.__checkConfig()