Example #1
0
    def serialize(self):
        # doc = implementation.createDocument(self.namespace, None, None)
        doc = Document()
        ipsec_element = doc.createElementNS(self.namespace, "ipsec")
        sad_element = doc.createElementNS(self.namespace, "sad")
        spd_element = doc.createElementNS(self.namespace, "spd")
        ipsec_element.appendChild(sad_element)
        ipsec_element.appendChild(spd_element)
        doc.appendChild(ipsec_element)
        if self.SAs:
            for sa in self.SAs:
                saNode = sa.serialize(doc, self.namespace)
                sad_element.appendChild(saNode)
        else:
            print "No SAD entries."

        if self.SPs:
            for sp in self.SPs:
                spNode = sp.serialize(doc, self.namespace)
                spd_element.appendChild(spNode)
        else:
            print "No SPD entries."

        # print doc.toprettyxml()
        return doc
def serach_E(n):
    for i in elements:
        if i.name==n:
            if i.data.hasChildNodes()==False:
                xmlfile = Document()
                temp1=xmlfile.createElementNS('xs','complexType')
                temp1.setAttribute('mixed','true')
                i.data.appendChild(temp1)
                temp2=xmlfile.createElementNS('xs','sequence')
                temp1.appendChild(temp2)
            return i.data.getElementsByTagName('complexType')[0].getElementsByTagName('sequence')[0]
    return None
def get_XSD_r(conf):
    xmlfile = Document()
    
    information = xmlfile.createElementNS('xs','schema')
    information.setAttributeNS('xmlns','xs','http://www.w3.org/2001/XMLSchema')
    information.setAttribute("targetNamespace",'http://www.w3school.com.cn')
    information.setAttribute('xmlns','http://www.w3school.com.cn')
    xmlfile.appendChild(information)
    conffile=open(conf)
    father=None

    while len(elements):
        elements.pop()
    for line in conffile.readlines():
        temp=line.split('=')
        for j in range(len(temp)):
            temp[j]=temp[j].strip()
        te = xmlfile.createElementNS('xs','element')
        te.setAttribute('name',temp[0])
        elements.append(XMLE(temp[0],te))
        if len(temp)>1:
            temp[0]=temp[1].split(';')
            for j in temp[0]:
                j=j.strip()
                if j == '':
                    continue
                j=j.split(':')
                if j[0]=='type':
                    if j[1]=='str':
                        te.setAttribute('type','xs:string')
                    elif j[1]=='int':
                        te.setAttribute('type','xs:positiveInteger')
                elif j[0]=='fix':
                    te.setAttribute('fixed',j[1])
                elif j[0]=='word'or j[0]=='contain' or j[0]=='maxo' or j[0]=='mino':
                    te.setAttribute(j[0],j[1])
                elif j[0]=='father':
                    father=serach_E(j[1])
                    if father == None:
                        te.setAttribute('error','no father node named :%s' % j[1])
            
            if father == None:
                information.appendChild(te)
            else:
                father.appendChild(te)
                father=None
    conffile.close()
    
    temp = conf.split('\\')            
    f=open('%s.xsdr' % temp[-1].split('.')[0] ,'w')
    xmlfile.writexml(f, "\t", "\t", "\n", "gbk")
    f.close()
Example #4
0
def createRequestXML(service, action, arguments=None):
    from xml.dom.minidom import Document

    doc = Document()

    # create the envelope element and set its attributes
    envelope = doc.createElementNS('', 's:Envelope')
    envelope.setAttribute('xmlns:s', 'http://schemas.xmlsoap.org/soap/envelope/')
    envelope.setAttribute('s:encodingStyle', 'http://schemas.xmlsoap.org/soap/encoding/')

    # create the body element
    body = doc.createElementNS('', 's:Body')

    # create the function element and set its attribute
    fn = doc.createElementNS('', 'u:%s' % action)
    fn.setAttribute('xmlns:u', 'urn:schemas-upnp-org:service:%s' % service)

    # setup the argument element names and values
    # using a list of tuples to preserve order

    # container for created nodes
    argument_list = []

    # iterate over arguments, create nodes, create text nodes,
    # append text nodes to nodes, and finally add the ready product
    # to argument_list
    if arguments is not None:
        for k, v in arguments:
            tmp_node = doc.createElement(k)
            tmp_text_node = doc.createTextNode(v)
            tmp_node.appendChild(tmp_text_node)
            argument_list.append(tmp_node)

    # append the prepared argument nodes to the function element
    for arg in argument_list:
        fn.appendChild(arg)

    # append function element to the body element
    body.appendChild(fn)

    # append body element to envelope element
    envelope.appendChild(body)

    # append envelope element to document, making it the root element
    doc.appendChild(envelope)

    # our tree is ready, conver it to a string
    return doc.toxml()
Example #5
0
 def _buildbasicXMLdoc(self):
     doc = Document()
     root_element = doc.createElementNS('http://api.uclassify.com/1/RequestSchema', 'uclassify')
     root_element.setAttribute("version", "1.01")
     root_element.setAttribute("xmlns", "http://api.uclassify.com/1/server/RequestSchema")
     doc.appendChild(root_element)
     return doc,root_element
Example #6
0
def export_alignment_table_as_tei(table, indent=None):
    d = Document()
    root = d.createElementNS("http://interedition.eu/collatex/ns/1.0", "cx:apparatus") # fake namespace declarations
    root.setAttribute("xmlns:cx", "http://interedition.eu/collatex/ns/1.0")
    root.setAttribute("xmlns", "http://www.tei-c.org/ns/1.0")
    d.appendChild(root)
    for column in table.columns:
        value_dict = defaultdict(list)
        ws_flag = False
        for key, value in sorted(column.tokens_per_witness.items()):
            # value_dict key is reading, value is list of witnesses
            t_readings = "".join(item.token_data["t"] for item in value)
            if ws_flag == False and t_readings.endswith((" ", r"\u0009", r"\000a")): # space, tab, lf
                ws_flag = True
            value_dict[t_readings.strip()].append(key)

        # REVIEW [RHD]: Isn't there a method on table that can be used instead of this len(next(iter() etc?
        # otherwise I think there should be. Not sure what len(next(iter(etc))) represents.
        #
        # See https://stackoverflow.com/questions/4002874/non-destructive-version-of-pop-for-a-dictionary
        # It returns the number of witnesses that attest the one reading in the dictionary, that is, it peeks
        #   nondestructively at the value of the single dictionary item, which is a list, and counts the members
        #   of the list
        if len(value_dict) == 1 and len(next(iter(value_dict.values()))) == len(table.rows):
            # len(table.rows) is total number of witnesses; guards against nulls, which aren't in table
            key, value = value_dict.popitem() # there's just one item
            text_node = d.createTextNode(key)
            root.appendChild(text_node)
        else:
            # variation is either more than one reading, or one reading plus nulls
            app = d.createElementNS("http://www.tei-c.org/ns/1.0", "app")
            root.appendChild(app)
            for key, value in value_dict.items():
                # key is reading (with trailing whitespace stripped), value is list of witnesses
                rdg = d.createElementNS("http://www.tei-c.org/ns/1.0", "rdg")
                rdg.setAttribute("wit", " ".join(["#" + item for item in value_dict[key]]))
                text_node = d.createTextNode(key)
                rdg.appendChild(text_node)
                app.appendChild(rdg)
        if ws_flag:
            text_node = d.createTextNode(" ")
            root.appendChild(text_node)
    if indent:
        result = d.toprettyxml()
    else:
        result = d.toxml()
    return result
    def toWorkspaceXml(self, quantity=1, data=None):

        launchData = {}
        if self.data != None:
            for key in self.data:
                launchData[key] = self.data[key]
        if data != None:
            for key in data:
                launchData[key] = data[key]

        # why did I think this was a good idea?

        doc = Document()
        cluster = doc.createElementNS("http://www.globus.org/2008/06/workspace/metadata/logistics", "cluster")

        workspace = doc.createElement("workspace");
        cluster.appendChild(workspace)

        name = doc.createElement("name")
        name.appendChild(doc.createTextNode(self.name))
        workspace.appendChild(name)

        image = doc.createElement("image")
        image.appendChild(doc.createTextNode(self.ami))
        workspace.appendChild(image)

        quantityNode = doc.createElement("quantity")
        quantityNode.appendChild(doc.createTextNode(str(quantity)))
        workspace.appendChild(quantityNode)

        nic = doc.createElement("nic")
        nic.setAttribute("wantlogin","true")
        nic.appendChild(doc.createTextNode("public"))
        workspace.appendChild(nic)

        ctx = doc.createElement("ctx")
        workspace.appendChild(ctx)

        provides = doc.createElement("provides")
        provides.appendChild(doc.createElement("identity"))
        ctx.appendChild(provides)

        role = doc.createElement("role")
        role.setAttribute("hostname","true")
        role.setAttribute("pubkey","true")
        role.appendChild(doc.createTextNode(self.name))
        provides.appendChild(role)

        requires = doc.createElement("requires")
        requires.appendChild(doc.createElement("identity"))
        ctx.appendChild(requires)

        for key in launchData:
            dataNode = doc.createElement("data")
            dataNode.setAttribute("name", key)
            dataNode.appendChild(doc.createCDATASection(launchData[key]))
            requires.appendChild(dataNode)
        
        return cluster.toxml()
Example #8
0
def _testElementReprAndStrUnicodeNS():
    dom = Document()
    el = dom.appendChild(
        dom.createElementNS(u"http://www.slashdot.org", u"slash:abc"))
    string1 = repr(el)
    string2 = str(el)
    confirm(string1 == string2)
    confirm(string1.find("slash:abc") != -1)
    dom.unlink()
 def to_xml(self):
     document = Document()
     remover = document.createElementNS(XMLDOC_NAMESPACE, STOP_RECORDING_ROOT_NODE)
     remover.setAttribute(XMLDOC_XMLNS_ATTRIBUTE, XMLDOC_NAMESPACE)
     document.appendChild(remover)
     # object id
     id_node = document.createElement(STOP_RECORDING_ID_NODE)
     remover.appendChild(id_node)
     id_node.appendChild(document.createTextNode(self.object_id_))
     return document.toxml(encoding=XMLDOC_CODEPAGE)
Example #10
0
 def _buildbasicXMLdoc(self):
     doc = Document()
     root_element = doc.createElementNS('http://api.uclassify.com/1/RequestSchema', 'uclassify')
     root_element.setAttribute("version", "1.01")
     root_element.setAttribute("xmlns", "http://api.uclassify.com/1/RequestSchema")
     doc.appendChild(root_element)
     #texts = doc.createElement("texts")
     #root_element.appendChild(texts)
     #print(doc.toprettyxml())
     return doc,root_element
def testRemoveAttrNS():
    dom = Document()
    child = dom.appendChild(
            dom.createElementNS("http://www.python.org", "python:abc"))
    child.setAttributeNS("http://www.w3.org", "xmlns:python",
                                            "http://www.python.org")
    child.setAttributeNS("http://www.python.org", "python:abcattr", "foo")
    confirm(len(child.attributes) == 2)
    child.removeAttributeNS("http://www.python.org", "abcattr")
    confirm(len(child.attributes) == 1)

    dom.unlink()
def init( metadata ):
	global doc
	if metadata is None:
		doc = Document()
		root = doc.createElementNS( NAMESPACES[ 'kml' ].uri, 'kml' )
		root.setAttribute( 'xmlns', NAMESPACES[ 'kml' ].uri )
		root.setAttribute( 'xmlns:' + NAMESPACES[ 'foaf' ].prefix, NAMESPACES[ 'foaf' ].uri )
		root.setAttribute( 'xmlns:' + NAMESPACES[ 'dc' ].prefix, NAMESPACES[ 'dc' ].uri )
		root.setAttribute( 'xmlns:' + NAMESPACES[ 'xml' ].prefix, NAMESPACES[ 'xml' ].uri )
		doc.appendChild( root )
	else:	
		doc = parseString( metadata )
Example #13
0
def createFeed(examples):
    doc = Document()
    feed = doc.createElementNS("http://www.w3.org/2005/Atom", "feed")
    feed.setAttribute("xmlns", "http://www.w3.org/2005/Atom") #ug, is this for real??
    for example in examples:
        s = os.stat("../examples/" + example["example"])
        example["modified"] = s.st_mtime
    
    examples.sort(key=lambda x:x["modified"])
    for example in sorted(examples, key=lambda x:x["modified"], reverse=True):
        entry = doc.createElementNS("http://www.w3.org/2005/Atom", "entry")
        
        title = doc.createElementNS("http://www.w3.org/2005/Atom", "title")
        title.appendChild(doc.createTextNode(example["title"] or example["example"]))
        entry.appendChild(title)
        
        link = doc.createElementNS("http://www.w3.org/2005/Atom", "link")
        link.setAttribute("href", example["example"])
        entry.appendChild(link)
    
        summary = doc.createElementNS("http://www.w3.org/2005/Atom", "summary")
        summary.appendChild(doc.createTextNode(example["shortdesc"] or example["example"]))
        entry.appendChild(summary)
        
        updated = doc.createElementNS("http://www.w3.org/2005/Atom", "updated")
        updated.appendChild(doc.createTextNode(
            time.strftime("%Y-%m-%dT%I:%M:%SZ",time.gmtime(example["modified"]))))
        entry.appendChild(updated)
        
        feed.appendChild(entry)

    doc.appendChild(feed)
    return doc
Example #14
0
 def to_xml(self):
     document = Document()
     stop_stream = document.createElementNS(XMLDOC_NAMESPACE, STREAMER_STOP_ROOT_NODE)
     stop_stream.setAttribute(XMLDOC_XMLNS_ATTRIBUTE, XMLDOC_NAMESPACE)
     document.appendChild(stop_stream)
     
     if self.channel_handle_ != None:
         channel_handle = document.createElement(STREAMER_CHANNEL_HANDLE_NODE)
         stop_stream.appendChild(channel_handle)
         channel_handle.appendChild(document.createTextNode(str(self.channel_handle_)))
     elif self.client_id_ != None:
         client_id = document.createElement(STREAMER_CLIENT_ID_NODE)
         stop_stream.appendChild(client_id)
         client_id.appendChild(document.createTextNode(str(self.client_id_)))
     return document.toxml(encoding=XMLDOC_CODEPAGE)
 def to_xml(self):
     document = Document()
     epg_searcher = document.createElementNS(XMLDOC_NAMESPACE, SEARCHING_ROOT_NODE)
     epg_searcher.setAttribute(XMLDOC_XMLNS_ATTRIBUTE, XMLDOC_NAMESPACE)
     document.appendChild(epg_searcher)        
     if self.is_epg_short_:
         epg_short = document.createElement(SEARCHING_EPG_SHORT_NODE)
         epg_searcher.appendChild(epg_short)
         epg_short.appendChild(document.createTextNode(XMLNODE_VALUE_TRUE))                    
     
     start_time = document.createElement(SEARCHING_START_TIME_NODE)
     epg_searcher.appendChild(start_time)
     start_time.appendChild(document.createTextNode(str(self.start_time_)))
     
     requested_count = document.createElement(SEARCHING_COUNT_NODE)
     epg_searcher.appendChild(requested_count)
     requested_count.appendChild(document.createTextNode(str(self.requested_count_)))
     
     end_time = document.createElement(SEARCHING_END_TIME_NODE)
     epg_searcher.appendChild(end_time)
     end_time.appendChild(document.createTextNode(str(self.end_time_)))
     
     if self.program_id_ != None:
         program_id = document.createElement(SEARCHING_PROGRAM_ID_NODE)
         epg_searcher.appendChild(program_id)
         program_id.appendChild(document.createTextNode(str(self.program_id_)))
         
     if self.keywords_ != None:
         keywords = document.createElement(SEARCHING_KEYWORDS_NODE)
         epg_searcher.appendChild(keywords)
         keywords.appendChild(document.createTextNode(self.keywords_.decode(XMLDOC_CODEPAGE)))
     
     if self.genre_mask_ != None:
         genre_mask = document.createElement(SEARCHING_GENRE_MASK_NODE)
         epg_searcher.appendChild(genre_mask)
         genre_mask.appendChild(document.createTextNode(str(self.genre_mask_)))
         
     if self.channels_ids_:
         channels_ids = document.createElement(SEARCHING_CHANNELS_IDS_NODE)
         epg_searcher.appendChild(channels_ids)
         for id in self.channels_ids_:
             id_node = document.createElement(SEARCHING_CHANNEL_ID_NODE)
             channels_ids.appendChild(id_node)
             id_node.appendChild(document.createTextNode(id))               
     return document.toxml(encoding=XMLDOC_CODEPAGE)
Example #16
0
    def append(self, extensionElement):
        """
        Creates an Tag for each attribute and adds them to the given DOM Element 'extensionElement'
        """
        doc = Document()

        for x in self._attributes:
            if self._attributes[x]["enabled"]:
                attribute = doc.createElementNS("urn:oasis:names:tc:SAML:2.0:assertion", "saml2:Attribute")
                # Namespaces
                attribute.setAttribute("xmlns:saml2", "urn:oasis:names:tc:SAML:2.0:assertion")
                attribute.setAttribute("xmlns:eCH-0113", "http://www.ech.ch/xmlns/eCH-0113/1")

                # Attribute
                attribute.setAttribute("Name", self._attributes[x]["id"])
                attribute.setAttribute("eCH-0113:required", "true")

                extensionElement.appendChild(attribute)
Example #17
0
class WPSException(Exception):
    """WPSException should be base class for all exceptions
    """
    code = "NoApplicableCode"
    value = None
    locator = None

    def _make_xml(self):
        # formulate XML
        self.document = Document()
        self.ExceptionReport = self.document.createElementNS("http://www.opengis.net/ows","ExceptionReport")
        self.ExceptionReport.setAttribute("xmlns","http://www.opengis.net/ows/1.1")
        self.ExceptionReport.setAttribute("xmlns:xsi","http://www.w3.org/2001/XMLSchema-instance")
        self.ExceptionReport.setAttribute("xsi:schemaLocation","http://www.opengis.net/ows/1.1 http://schemas.opengis.net/ows/1.1.0/owsExceptionReport.xsd")
        self.ExceptionReport.setAttribute("version","1.0.0")
        self.document.appendChild(self.ExceptionReport)

        # make exception

        self.Exception = self.document.createElement("Exception")
        self.Exception.setAttribute("exceptionCode",self.code)

        if self.locator:
            self.Exception.setAttribute("locator",self.locator)

        self.ExceptionReport.appendChild(self.Exception)
        #self.value = None

    def getResponse(self):
        return self.document.toprettyxml(indent='\t', newl='\n', encoding="utf-8")
        # Not sure what this code is doing here - but we could do with SOAP
        # handling at some point, so I'll leave it here. - JD 9/12/12
#        if pywps.Soap.soap == True:
#            soapCls = SOAP()
#            response = soapCls.getResponse(response)

    def __str__(self):
        error = "PyWPS %s: Locator: %s; Value: %s\n" % (self.code, self.locator, self.value)
        try:
            logFile.write(error) #@UndefinedVariable
        except:
            sys.stderr.write(error)

        return self.document.toprettyxml(indent='\t', newl='\n', encoding="utf-8")
 def to_xml(self):
     document = Document()
     parental_lock = document.createElementNS(XMLDOC_NAMESPACE, PARENTAL_LOCK_ROOT_NODE)
     parental_lock.setAttribute(XMLDOC_XMLNS_ATTRIBUTE, XMLDOC_NAMESPACE)
     document.appendChild(parental_lock)        
     if self.is_enable_:
         is_enable = document.createElement(PARENTAL_LOCK_IS_ENABLE_NODE)
         parental_lock.appendChild(is_enable)
         is_enable.appendChild(document.createTextNode(XMLNODE_VALUE_TRUE))
     
     if self.lock_code_ != None:
         lock_code = document.createElement(PARENTAL_LOCK_CODE_NODE)
         parental_lock.appendChild(lock_code)
         lock_code.appendChild(document.createTextNode(self.lock_code_.decode(XMLDOC_CODEPAGE)))
         
     if self.client_id_ != None:
         client_id = document.createElement(PARENTAL_LOCK_CLIENT_ID_NODE)
         parental_lock.appendChild(client_id)
         client_id.appendChild(document.createTextNode(self.client_id_))
     
     return document.toxml(encoding=XMLDOC_CODEPAGE)
Example #19
0
    def to_xml(self):
        document = Document()
        stream_info = document.createElementNS(XMLDOC_NAMESPACE, STREAM_INFO_ROOT_NODE)
        stream_info.setAttribute(XMLDOC_XMLNS_ATTRIBUTE, XMLDOC_NAMESPACE)
        document.appendChild(stream_info)        

        address_node = document.createElement(STREAM_INFO_SERVER_ADDRESS_NODE)
        stream_info.appendChild(address_node)
        address_node.appendChild(document.createTextNode(self.address_))                    
        
        client_id_node = document.createElement(STREAM_INFO_CLIENT_ID_NODE)
        stream_info.appendChild(client_id_node)
        client_id_node.appendChild(document.createTextNode(self.client_id_))
   
        channels_ids = document.createElement(STREAM_INFO_CHANNELS_IDS_NODE)
        stream_info.appendChild(channels_ids)
        for id in self.channels_ids_:
            id_node = document.createElement(STREAM_INFO_CHANNEL_ID_NODE)
            channels_ids.appendChild(id_node)
            id_node.appendChild(document.createTextNode(str(id)))
        return document.toxml(encoding=XMLDOC_CODEPAGE)
Example #20
0
 def to_xml(self):
     document = Document()
     request_stream = document.createElementNS(XMLDOC_NAMESPACE, STREAMER_ROOT_NODE)
     request_stream.setAttribute(XMLDOC_XMLNS_ATTRIBUTE, XMLDOC_NAMESPACE)
     document.appendChild(request_stream)
     
     if self.channel_dvblink_id_ != None:
         channel_id = document.createElement(STREAMER_CHANNEL_ID_NODE)
         request_stream.appendChild(channel_id)
         channel_id.appendChild(document.createTextNode(str(self.channel_dvblink_id_)))
     if self.client_id_ != None:
         client_id = document.createElement(STREAMER_CLIENT_ID_NODE)
         request_stream.appendChild(client_id)
         client_id.appendChild(document.createTextNode(str(self.client_id_)))
     if self.server_address_ != None:
         address = document.createElement(STREAMER_SERVER_ADDRESS_NODE)
         request_stream.appendChild(address)
         address.appendChild(document.createTextNode(str(self.server_address_)))
     if self.stream_type_ != None:
         stream_type = document.createElement(STREAMER_STREAM_TYPE_NODE)
         request_stream.appendChild(stream_type)
         stream_type.appendChild(document.createTextNode(str(self.stream_type_)))
     return document.toxml(encoding=XMLDOC_CODEPAGE)
Example #21
0
 def to_xml(self):
     document = Document()
     object_requester = document.createElementNS(XMLDOC_NAMESPACE, OBJECT_REQUESTER_ROOT_NODE)
     object_requester.setAttribute(XMLDOC_XMLNS_ATTRIBUTE, XMLDOC_NAMESPACE)
     document.appendChild(object_requester)        
     
     object_id = document.createElement(OBJECT_REQUESTER_OBJECT_ID_NODE)
     object_requester.appendChild(object_id)
     object_id.appendChild(document.createTextNode(str(self.object_id_)))                 
     
     if self.server_address_ != None:
         server_address = document.createElement(OBJECT_REQUESTER_SERVER_ADDR_NODE)
         object_requester.appendChild(server_address)
         server_address.appendChild(document.createTextNode(str(self.server_address_)))
         
     object_type = document.createElement(OBJECT_REQUESTER_OBJECT_TYPE_NODE)
     object_requester.appendChild(object_type)
     object_type.appendChild(document.createTextNode(str(self.object_type_)))
     
     item_type = document.createElement(OBJECT_REQUESTER_ITEM_TYPE_NODE)
     object_requester.appendChild(item_type)
     item_type.appendChild(document.createTextNode(str(self.item_type_)))
     
     start_position = document.createElement(OBJECT_REQUESTER_POSITION_NODE)
     object_requester.appendChild(start_position)
     start_position.appendChild(document.createTextNode(str(self.start_position_)))
     
     requested_count = document.createElement(OBJECT_REQUESTER_COUNT_NODE)
     object_requester.appendChild(requested_count)
     requested_count.appendChild(document.createTextNode(str(self.requested_count_)))
         
     if self.is_children_request_:
         is_children_request = document.createElement(OBJECT_REQUESTER_TYPE_NODE)
         object_requester.appendChild(is_children_request)
         is_children_request.appendChild(document.createTextNode(XMLNODE_VALUE_TRUE))
                  
     return document.toxml(encoding=XMLDOC_CODEPAGE)
Example #22
0
class XMLDump(object):
    """
    This class purpose is to dump the data into an xml Format.
    The format of the xml file is described in the scheme file xml/sqlmap.xsd
    """

    def __init__(self):
        self._outputFile = None
        self._outputFP = None
        self.__root = None
        self.__doc = Document()

    def _addToRoot(self, element):
        """
        Adds element to the root element
        """
        self.__root.appendChild(element)

    def __write(self, data, n=True):
        """
        Writes the data into the file
        """
        if n:
            self._outputFP.write("%s\n" % data)
        else:
            self._outputFP.write("%s " % data)

        self._outputFP.flush()

        kb.dataOutputFlag = True

    def _getRootChild(self, elemName):
        """
        Returns the child of the root with the described name
        """
        elements = self.__root.getElementsByTagName(elemName)
        if elements:
            return elements[0]

        return elements

    def _createTextNode(self, data):
        """
        Creates a text node with utf8 data inside.
        The text is escaped to an fit the xml text Format.
        """
        if data is None:
            return self.__doc.createTextNode(u'')
        else:
            escaped_data = saxutils.escape(data, ENTITIES)
            return self.__doc.createTextNode(escaped_data)

    def _createAttribute(self, attrName, attrValue):
        """
        Creates an attribute node with utf8 data inside.
        The text is escaped to an fit the xml text Format.
        """
        attr = self.__doc.createAttribute(attrName)
        if attrValue is None:
            attr.nodeValue = u''
        else:
            attr.nodeValue = getUnicode(attrValue)
        return attr

    def string(self, header, data, sort=True):
        """
        Adds string element to the xml.
        """
        if isinstance(data, (list, tuple, set)):
            self.lister(header, data, sort)
            return

        messagesElem = self._getRootChild(MESSAGES_ELEM_NAME)
        if (not(messagesElem)):
            messagesElem = self.__doc.createElement(MESSAGES_ELEM_NAME)
            self._addToRoot(messagesElem)

        if data:
            data = self._formatString(data)
        else:
            data = ""

        elem = self.__doc.createElement(MESSAGE_ELEM)
        elem.setAttributeNode(self._createAttribute(TYPE_ATTR, header))
        elem.appendChild(self._createTextNode(data))
        messagesElem.appendChild(elem)

    def lister(self, header, elements, sort=True):
        """
        Adds information formatted as list element
        """
        lstElem = self.__doc.createElement(LST_ELEM_NAME)
        lstElem.setAttributeNode(self._createAttribute(TYPE_ATTR, header))
        if elements:
            if sort:
                try:
                    elements = set(elements)
                    elements = list(elements)
                    elements.sort(key=lambda x: x.lower())
                except:
                    pass

            for element in elements:
                memberElem = self.__doc.createElement(MEMBER_ELEM)
                lstElem.appendChild(memberElem)
                if isinstance(element, basestring):
                    memberElem.setAttributeNode(self._createAttribute(TYPE_ATTR, "string"))
                    memberElem.appendChild(self._createTextNode(element))
                elif isinstance(element, (list, tuple, set)):
                    memberElem.setAttributeNode(self._createAttribute(TYPE_ATTR, "list"))
                    for e in element:
                        memberElemStr = self.__doc.createElement(MEMBER_ELEM)
                        memberElemStr.setAttributeNode(self._createAttribute(TYPE_ATTR, "string"))
                        memberElemStr.appendChild(self._createTextNode(getUnicode(e)))
                        memberElem.appendChild(memberElemStr)
        listsElem = self._getRootChild(LSTS_ELEM_NAME)
        if not(listsElem):
            listsElem = self.__doc.createElement(LSTS_ELEM_NAME)
            self._addToRoot(listsElem)
        listsElem.appendChild(lstElem)

    def technic(self, technicType, data):
        """
        Adds information about the technic used to extract data from the db
        """
        technicElem = self.__doc.createElement(TECHNIC_ELEM_NAME)
        technicElem.setAttributeNode(self._createAttribute(TYPE_ATTR, technicType))
        textNode = self._createTextNode(data)
        technicElem.appendChild(textNode)
        technicsElem = self._getRootChild(TECHNICS_ELEM_NAME)
        if not(technicsElem):
            technicsElem = self.__doc.createElement(TECHNICS_ELEM_NAME)
            self._addToRoot(technicsElem)
        technicsElem.appendChild(technicElem)

    def banner(self, data):
        """
        Adds information about the database banner to the xml.
        The banner contains information about the type and the version of the database.
        """
        bannerElem = self.__doc.createElement(BANNER_ELEM_NAME)
        bannerElem.appendChild(self._createTextNode(data))
        self._addToRoot(bannerElem)

    def currentUser(self, data):
        """
        Adds information about the current database user to the xml
        """
        currentUserElem = self.__doc.createElement(CURRENT_USER_ELEM_NAME)
        textNode = self._createTextNode(data)
        currentUserElem.appendChild(textNode)
        self._addToRoot(currentUserElem)

    def currentDb(self, data):
        """
        Adds information about the current database is use to the xml
        """
        currentDBElem = self.__doc.createElement(CURRENT_DB_ELEM_NAME)
        textNode = self._createTextNode(data)
        currentDBElem.appendChild(textNode)
        self._addToRoot(currentDBElem)

    def dba(self, isDBA):
        """
        Adds information to the xml that indicates whether the user has DBA privileges
        """
        isDBAElem = self.__doc.createElement(IS_DBA_ELEM_NAME)
        isDBAElem.setAttributeNode(self._createAttribute(VALUE_ATTR, getUnicode(isDBA)))
        self._addToRoot(isDBAElem)

    def users(self, users):
        """
        Adds a list of the existing users to the xml
        """
        usersElem = self.__doc.createElement(USERS_ELEM_NAME)
        if isinstance(users, basestring):
            users = [users]
        if users:
            for user in users:
                userElem = self.__doc.createElement(DB_USER_ELEM_NAME)
                usersElem.appendChild(userElem)
                userElem.appendChild(self._createTextNode(user))
        self._addToRoot(usersElem)

    def dbs(self, dbs):
        """
        Adds a list of the existing databases to the xml
        """
        dbsElem = self.__doc.createElement(DBS_ELEM_NAME)
        if dbs:
            for db in dbs:
                dbElem = self.__doc.createElement(DB_NAME_ELEM_NAME)
                dbsElem.appendChild(dbElem)
                dbElem.appendChild(self._createTextNode(db))
        self._addToRoot(dbsElem)

    def userSettings(self, header, userSettings, subHeader):
        """
        Adds information about the user's settings to the xml.
        The information can be user's passwords, privileges and etc..
        """
        self._areAdmins = set()
        userSettingsElem = self._getRootChild(USER_SETTINGS_ELEM_NAME)
        if (not(userSettingsElem)):
            userSettingsElem = self.__doc.createElement(USER_SETTINGS_ELEM_NAME)
            self._addToRoot(userSettingsElem)

        userSettingElem = self.__doc.createElement(USER_SETTING_ELEM_NAME)
        userSettingElem.setAttributeNode(self._createAttribute(TYPE_ATTR, header))

        if isinstance(userSettings, (tuple, list, set)):
            self._areAdmins = userSettings[1]
            userSettings = userSettings[0]

        users = userSettings.keys()
        users.sort(key=lambda x: x.lower())

        for user in users:
            userElem = self.__doc.createElement(USER_ELEM_NAME)
            userSettingElem.appendChild(userElem)
            if user in self._areAdmins:
                userElem.setAttributeNode(self._createAttribute(TYPE_ATTR, ADMIN_USER))
            else:
                userElem.setAttributeNode(self._createAttribute(TYPE_ATTR, REGULAR_USER))

            settings = userSettings[user]

            settings.sort()

            for setting in settings:
                settingsElem = self.__doc.createElement(SETTINGS_ELEM_NAME)
                settingsElem.setAttributeNode(self._createAttribute(TYPE_ATTR, subHeader))
                settingTextNode = self._createTextNode(setting)
                settingsElem.appendChild(settingTextNode)
                userElem.appendChild(settingsElem)
        userSettingsElem.appendChild(userSettingElem)

    def dbTables(self, dbTables):
        """
        Adds information of the existing db tables to the xml
        """
        if not isinstance(dbTables, dict):
            self.string(TABLES_ELEM_NAME, dbTables)
            return

        dbTablesElem = self.__doc.createElement(DB_TABLES_ELEM_NAME)

        for db, tables in dbTables.items():
            tables.sort(key=lambda x: x.lower())
            dbElem = self.__doc.createElement(DATABASE_ELEM_NAME)
            dbElem.setAttributeNode(self._createAttribute(NAME_ATTR, db))
            dbTablesElem.appendChild(dbElem)
            for table in tables:
                tableElem = self.__doc.createElement(DB_TABLE_ELEM_NAME)
                tableElem.appendChild(self._createTextNode(table))
                dbElem.appendChild(tableElem)
        self._addToRoot(dbTablesElem)

    def dbTableColumns(self, tableColumns):
        """
        Adds information about the columns of the existing tables to the xml
        """

        columnsElem = self._getRootChild(COLUMNS_ELEM_NAME)
        if not(columnsElem):
            columnsElem = self.__doc.createElement(COLUMNS_ELEM_NAME)

        for db, tables in tableColumns.items():
            if not db:
                db = DEFAULT_DB
            dbElem = self.__doc.createElement(DATABASE_COLUMNS_ELEM)
            dbElem.setAttributeNode(self._createAttribute(NAME_ATTR, db))
            columnsElem.appendChild(dbElem)

            for table, columns in tables.items():
                tableElem = self.__doc.createElement(TABLE_ELEM_NAME)
                tableElem.setAttributeNode(self._createAttribute(NAME_ATTR, table))

                colList = columns.keys()
                colList.sort(key=lambda x: x.lower())

                for column in colList:
                    colType = columns[column]
                    colElem = self.__doc.createElement(COLUMN_ELEM_NAME)
                    if colType is not None:
                        colElem.setAttributeNode(self._createAttribute(TYPE_ATTR, colType))
                    else:
                        colElem.setAttributeNode(self._createAttribute(TYPE_ATTR, UNKNOWN_COLUMN_TYPE))
                    colElem.appendChild(self._createTextNode(column))
                    tableElem.appendChild(colElem)

        self._addToRoot(columnsElem)

    def dbTableValues(self, tableValues):
        """
        Adds the values of specific table to the xml.
        The values are organized according to the relevant row and column.
        """
        tableElem = self.__doc.createElement(DB_TABLE_VALUES_ELEM_NAME)
        if (tableValues is not None):
            db = tableValues["__infos__"]["db"]
            if not db:
                db = "All"
            table = tableValues["__infos__"]["table"]

            count = int(tableValues["__infos__"]["count"])
            columns = tableValues.keys()
            columns.sort(key=lambda x: x.lower())

            tableElem.setAttributeNode(self._createAttribute(DB_ATTR, db))
            tableElem.setAttributeNode(self._createAttribute(NAME_ATTR, table))

            for i in range(count):
                rowElem = self.__doc.createElement(ROW_ELEM_NAME)
                tableElem.appendChild(rowElem)
                for column in columns:
                    if column != "__infos__":
                        info = tableValues[column]
                        value = info["values"][i]

                        if re.search("^[\ *]*$", value):
                            value = "NULL"

                        cellElem = self.__doc.createElement(CELL_ELEM_NAME)
                        cellElem.setAttributeNode(self._createAttribute(COLUMN_ATTR, column))
                        cellElem.appendChild(self._createTextNode(value))
                        rowElem.appendChild(cellElem)

        dbValuesElem = self._getRootChild(DB_VALUES_ELEM)
        if (not(dbValuesElem)):
            dbValuesElem = self.__doc.createElement(DB_VALUES_ELEM)
            self._addToRoot(dbValuesElem)

        dbValuesElem.appendChild(tableElem)

        logger.info("Table '%s.%s' dumped to XML file" % (db, table))

    def dbColumns(self, dbColumns, colConsider, dbs):
        """
        Adds information about the columns
        """
        for column in dbColumns.keys():
            printDbs = {}
            for db, tblData in dbs.items():
                for tbl, colData in tblData.items():
                    for col, dataType in colData.items():
                        if column in col:
                            if db in printDbs:
                                if tbl in printDbs[db]:
                                    printDbs[db][tbl][col] = dataType
                                else:
                                    printDbs[db][tbl] = {col: dataType}
                            else:
                                printDbs[db] = {}
                                printDbs[db][tbl] = {col: dataType}

                            continue

        self.dbTableColumns(printDbs)

    def query(self, query, queryRes):
        """
        Adds details of an executed query to the xml.
        The query details are the query itself and its results.
        """
        queryElem = self.__doc.createElement(QUERY_ELEM_NAME)
        queryElem.setAttributeNode(self._createAttribute(VALUE_ATTR, query))
        queryElem.appendChild(self._createTextNode(queryRes))
        queriesElem = self._getRootChild(QUERIES_ELEM_NAME)
        if (not(queriesElem)):
            queriesElem = self.__doc.createElement(QUERIES_ELEM_NAME)
            self._addToRoot(queriesElem)
        queriesElem.appendChild(queryElem)

    def registerValue(self, registerData):
        """
        Adds information about an extracted registry key to the xml
        """
        registerElem = self.__doc.createElement(REGISTER_DATA_ELEM_NAME)
        registerElem.appendChild(self._createTextNode(registerData))
        registriesElem = self._getRootChild(REGISTERY_ENTRIES_ELEM_NAME)
        if (not(registriesElem)):
            registriesElem = self.__doc.createElement(REGISTERY_ENTRIES_ELEM_NAME)
            self._addToRoot(registriesElem)
        registriesElem.appendChild(registerElem)

    def rFile(self, filePath, data):
        """
        Adds an extracted file's content to the xml
        """
        fileContentElem = self.__doc.createElement(FILE_CONTENT_ELEM_NAME)
        fileContentElem.setAttributeNode(self._createAttribute(NAME_ATTR, filePath))
        fileContentElem.appendChild(self._createTextNode(data))
        self._addToRoot(fileContentElem)

    def setOutputFile(self):
        """
        Initiates the xml file from the configuration.
        """
        if (conf.xmlFile):
            try:
                self._outputFile = conf.xmlFile
                self.__root = None

                if os.path.exists(self._outputFile):
                    try:
                        self.__doc = xml.dom.minidom.parse(self._outputFile)
                        self.__root = self.__doc.childNodes[0]
                    except ExpatError:
                        self.__doc = Document()

                self._outputFP = codecs.open(self._outputFile, "w+", UNICODE_ENCODING)

                if self.__root is None:
                    self.__root = self.__doc.createElementNS(NAME_SPACE_ATTR, RESULTS_ELEM_NAME)
                    self.__root.setAttributeNode(self._createAttribute(XMLNS_ATTR, NAME_SPACE_ATTR))
                    self.__root.setAttributeNode(self._createAttribute(SCHEME_NAME_ATTR, SCHEME_NAME))
                    self.__doc.appendChild(self.__root)
            except IOError:
                raise SqlmapFilePathException("Wrong filename provided for saving the xml file: %s" % conf.xmlFile)

    def getOutputFile(self):
        return self._outputFile

    def finish(self, resultStatus, resultMsg=""):
        """
        Finishes the dumper operation:
        1. Adds the session status to the xml
        2. Writes the xml to the file
        3. Closes the xml file
        """
        if ((self._outputFP is not None) and not(self._outputFP.closed)):
            statusElem = self.__doc.createElement(STATUS_ELEM_NAME)
            statusElem.setAttributeNode(self._createAttribute(SUCESS_ATTR, getUnicode(resultStatus)))

            if not resultStatus:
                errorElem = self.__doc.createElement(ERROR_ELEM_NAME)

                if isinstance(resultMsg, Exception):
                    errorElem.setAttributeNode(self._createAttribute(TYPE_ATTR, type(resultMsg).__name__))
                else:
                    errorElem.setAttributeNode(self._createAttribute(TYPE_ATTR, UNHANDLED_PROBLEM_TYPE))

                errorElem.appendChild(self._createTextNode(getUnicode(resultMsg)))
                statusElem.appendChild(errorElem)

            self._addToRoot(statusElem)
            self.__write(prettyprint.formatXML(self.__doc, encoding=UNICODE_ENCODING))
            self._outputFP.close()
Example #23
0
 def to_xml(self):
     document = Document()
     channels = document.createElementNS(XMLDOC_NAMESPACE, CHANNELS_ROOT_NODE)
     channels.setAttribute(XMLDOC_XMLNS_ATTRIBUTE, XMLDOC_NAMESPACE)
     document.appendChild(channels)      
     return document.toxml(encoding=XMLDOC_CODEPAGE)
Example #24
0
    def __call__(self, *args, **kwargs):
        for i, arg in enumerate(args):
            try:
                kwargs[self.param_names[i]] = arg
            except IndexError:
                for param in self.param_names:
                    print(param)
                raise

        doc = Document()

        envelope = doc.createElementNS('', 's:Envelope')
        envelope.setAttribute('xmlns:s', ENVELOPE_XMLNS)
        envelope.setAttribute('s:encodingStyle',
                              'http://schemas.xmlsoap.org/soap/encoding/')

        body = doc.createElementNS('', 's:Body')

        fn = doc.createElementNS('', self.__name__)
        fn.setAttribute('xmlns:u', self.service)

        for i, param in enumerate(self.params):
            if self.param_names[i] not in kwargs:
                value = param(None)
            else:
                value = param(kwargs[self.param_names[i]])

            tmp_node = doc.createElement(self.param_names[i])
            tmp_text_node = doc.createTextNode(str(value))
            tmp_node.appendChild(tmp_text_node)
            fn.appendChild(tmp_node)

        body.appendChild(fn)
        envelope.appendChild(body)
        doc.appendChild(envelope)
        pure_xml = doc.toxml()

        header = {
            'SOAPAction':
            '"{service}#{method}"'.format(service=self.service,
                                          method=self.__name__),
            'Content-Type':
            'text/xml'
        }
        response = requests.post(self.control_url,
                                 data=pure_xml,
                                 headers=header)
        envelope = etree.fromstring(response.content)
        envelope = strip_xmlns(envelope)

        body = envelope.find('Body')

        return_value = []

        if body is not None:

            response = body.find(self.__name__ + 'Response')
            if response is not None:
                for i, ret_val in enumerate(self.ret_vals):
                    value = response.find(self.ret_val_names[i])
                    if value is None:
                        value = ret_val(None)
                    else:
                        value = ret_val(value.text)

                    return_value += [value]

        if not return_value and self.ret_vals:
            for val in self.ret_vals:
                return_value += [val(None)]

        return return_value
 def to_xml(self):
     document = Document()
     recordings = document.createElementNS(XMLDOC_NAMESPACE, RECORDINGS_ROOT_NODE)
     recordings.setAttribute(XMLDOC_XMLNS_ATTRIBUTE, XMLDOC_NAMESPACE)
     document.appendChild(recordings)      
     return document.toxml(encoding=XMLDOC_CODEPAGE)        
Example #26
0
    def generate_name_id(value,
                         sp_nq,
                         sp_format,
                         cert=None,
                         debug=False,
                         nq=None):
        """
        Generates a nameID.

        :param value: fingerprint
        :type: string

        :param sp_nq: SP Name Qualifier
        :type: string

        :param sp_format: SP Format
        :type: string

        :param cert: IdP Public Cert to encrypt the nameID
        :type: string

        :param debug: Activate the xmlsec debug
        :type: bool

        :param nq: IDP Name Qualifier
        :type: string

        :returns: DOMElement | XMLSec nameID
        :rtype: string
        """
        doc = Document()
        name_id_container = doc.createElementNS(
            OneLogin_Saml2_Constants.NS_SAML, 'container')
        name_id_container.setAttribute("xmlns:saml",
                                       OneLogin_Saml2_Constants.NS_SAML)

        name_id = doc.createElement('saml:NameID')
        if sp_nq is not None:
            name_id.setAttribute('SPNameQualifier', sp_nq)
        if nq is not None:
            name_id.setAttribute('NameQualifier', nq)
        name_id.setAttribute('Format', sp_format)
        name_id.appendChild(doc.createTextNode(value))
        name_id_container.appendChild(name_id)

        if cert is not None:
            xml = name_id_container.toxml()
            elem = fromstring(xml)

            if debug:
                xmlsec.set_error_callback(print_xmlsec_errors)

            # Load the public cert
            mngr = xmlsec.KeysMngr()
            file_cert = OneLogin_Saml2_Utils.write_temp_file(cert)
            key_data = xmlsec.Key.load(file_cert.name,
                                       xmlsec.KeyDataFormatCertPem, None)
            key_data.name = basename(file_cert.name)
            mngr.addKey(key_data)
            file_cert.close()

            # Prepare for encryption
            enc_data = EncData(xmlsec.TransformAes128Cbc,
                               type=xmlsec.TypeEncElement)
            enc_data.ensureCipherValue()
            key_info = enc_data.ensureKeyInfo()
            # enc_key = key_info.addEncryptedKey(xmlsec.TransformRsaPkcs1)
            enc_key = key_info.addEncryptedKey(xmlsec.TransformRsaOaep)
            enc_key.ensureCipherValue()

            # Encrypt!
            enc_ctx = xmlsec.EncCtx(mngr)
            enc_ctx.encKey = xmlsec.Key.generate(xmlsec.KeyDataAes, 128,
                                                 xmlsec.KeyDataTypeSession)

            edata = enc_ctx.encryptXml(enc_data, elem[0])

            newdoc = parseString(
                etree.tostring(edata, encoding='unicode').encode('utf-8'))

            if newdoc.hasChildNodes():
                child = newdoc.firstChild
                child.removeAttribute('xmlns')
                child.removeAttribute('xmlns:saml')
                child.setAttribute('xmlns:xenc',
                                   OneLogin_Saml2_Constants.NS_XENC)
                child.setAttribute('xmlns:dsig',
                                   OneLogin_Saml2_Constants.NS_DS)

            nodes = newdoc.getElementsByTagName("*")
            for node in nodes:
                if node.tagName == 'ns0:KeyInfo':
                    node.tagName = 'dsig:KeyInfo'
                    node.removeAttribute('xmlns:ns0')
                    node.setAttribute('xmlns:dsig',
                                      OneLogin_Saml2_Constants.NS_DS)
                else:
                    node.tagName = 'xenc:' + node.tagName

            encrypted_id = newdoc.createElement('saml:EncryptedID')
            encrypted_data = newdoc.replaceChild(encrypted_id,
                                                 newdoc.firstChild)
            encrypted_id.appendChild(encrypted_data)
            return newdoc.saveXML(encrypted_id)
        else:
            return doc.saveXML(name_id)
Example #27
0
# test for xml.dom.minidom
Example #28
0
class XMLDump:
    '''
    This class purpose is to dump the data into an xml Format.
    The format of the xml file is described in the scheme file xml/sqlmap.xsd
    '''
    def __init__(self):
        self.__outputFile = None
        self.__outputFP = None
        self.__root = None
        self.__doc = Document()

    def __addToRoot(self, element):
        '''
        Adds element to the root element
        '''
        self.__root.appendChild(element)

    def __write(self, data, n=True):
        '''
        Writes the data into the file
        '''
        if n:
            self.__outputFP.write("%s\n" % data)
        else:
            self.__outputFP.write("%s " % data)

        self.__outputFP.flush()

        kb.dataOutputFlag = True

    def __getRootChild(self, elemName):
        '''
        Returns the child of the root with the described name
        '''
        elements = self.__root.getElementsByTagName(elemName)
        if elements:
            return elements[0]

        return elements

    def __createTextNode(self, data):
        '''
        Creates a text node with utf8 data inside.
        The text is escaped to an fit the xml text Format.
        '''
        if data is None:
            return self.__doc.createTextNode(u'')
        else:
            escaped_data = saxutils.escape(data, ENTITIES)
            return self.__doc.createTextNode(escaped_data)

    def __createAttribute(self, attrName, attrValue):
        '''
        Creates an attribute node with utf8 data inside.
        The text is escaped to an fit the xml text Format.
        '''
        attr = self.__doc.createAttribute(attrName)
        if attrValue is None:
            attr.nodeValue = u''
        else:
            attr.nodeValue = getUnicode(attrValue)
        return attr

    def string(self, header, data, sort=True):
        '''
        Adds string element to the xml.
        '''
        if isinstance(data, (list, tuple, set)):
            self.lister(header, data, sort)
            return

        messagesElem = self.__getRootChild(MESSAGES_ELEM_NAME)
        if (not (messagesElem)):
            messagesElem = self.__doc.createElement(MESSAGES_ELEM_NAME)
            self.__addToRoot(messagesElem)

        if data:
            data = self.__formatString(data)
        else:
            data = ""

        elem = self.__doc.createElement(MESSAGE_ELEM)
        elem.setAttributeNode(self.__createAttribute(TYPE_ATTR, header))
        elem.appendChild(self.__createTextNode(data))
        messagesElem.appendChild(elem)

    def lister(self, header, elements, sort=True):
        '''
        Adds information formatted as list element
        '''
        lstElem = self.__doc.createElement(LST_ELEM_NAME)
        lstElem.setAttributeNode(self.__createAttribute(TYPE_ATTR, header))
        if elements:

            if sort:
                try:
                    elements = set(elements)
                    elements = list(elements)
                    elements.sort(key=lambda x: x.lower())
                except:
                    pass

            for element in elements:
                memberElem = self.__doc.createElement(MEMBER_ELEM)
                lstElem.appendChild(memberElem)
                if isinstance(element, basestring):
                    memberElem.setAttributeNode(
                        self.__createAttribute(TYPE_ATTR, "string"))
                    memberElem.appendChild(self.__createTextNode(element))
                elif isinstance(element, (list, tuple, set)):
                    memberElem.setAttributeNode(
                        self.__createAttribute(TYPE_ATTR, "list"))
                    for e in element:
                        memberElemStr = self.__doc.createElement(MEMBER_ELEM)
                        memberElemStr.setAttributeNode(
                            self.__createAttribute(TYPE_ATTR, "string"))
                        memberElemStr.appendChild(
                            self.__createTextNode(getUnicode(e)))
                        memberElem.appendChild(memberElemStr)
        listsElem = self.__getRootChild(LSTS_ELEM_NAME)
        if not (listsElem):
            listsElem = self.__doc.createElement(LSTS_ELEM_NAME)
            self.__addToRoot(listsElem)
        listsElem.appendChild(lstElem)

    def technic(self, technicType, data):
        '''
        Adds information about the technic used to extract data from the db
        '''
        technicElem = self.__doc.createElement(TECHNIC_ELEM_NAME)
        technicElem.setAttributeNode(
            self.__createAttribute(TYPE_ATTR, technicType))
        textNode = self.__createTextNode(data)
        technicElem.appendChild(textNode)
        technicsElem = self.__getRootChild(TECHNICS_ELEM_NAME)
        if not (technicsElem):
            technicsElem = self.__doc.createElement(TECHNICS_ELEM_NAME)
            self.__addToRoot(technicsElem)
        technicsElem.appendChild(technicElem)

    def banner(self, data):
        '''
        Adds information about the database banner to the xml.
        The banner contains information about the type and the version of the database.
        '''
        bannerElem = self.__doc.createElement(BANNER_ELEM_NAME)
        bannerElem.appendChild(self.__createTextNode(data))
        self.__addToRoot(bannerElem)

    def currentUser(self, data):
        '''
        Adds information about the current database user to the xml
        '''
        currentUserElem = self.__doc.createElement(CURRENT_USER_ELEM_NAME)
        textNode = self.__createTextNode(data)
        currentUserElem.appendChild(textNode)
        self.__addToRoot(currentUserElem)

    def currentDb(self, data):
        '''
        Adds information about the current database is use to the xml
        '''
        currentDBElem = self.__doc.createElement(CURRENT_DB_ELEM_NAME)
        textNode = self.__createTextNode(data)
        currentDBElem.appendChild(textNode)
        self.__addToRoot(currentDBElem)

    def dba(self, isDBA):
        '''
        Adds information to the xml that indicates whether the user has DBA privileges
        '''
        isDBAElem = self.__doc.createElement(IS_DBA_ELEM_NAME)
        isDBAElem.setAttributeNode(
            self.__createAttribute(VALUE_ATTR, getUnicode(isDBA)))
        self.__addToRoot(isDBAElem)

    def users(self, users):
        '''
        Adds a list of the existing users to the xml
        '''
        usersElem = self.__doc.createElement(USERS_ELEM_NAME)
        if isinstance(users, basestring):
            users = [users]
        if users:
            for user in users:
                userElem = self.__doc.createElement(DB_USER_ELEM_NAME)
                usersElem.appendChild(userElem)
                userElem.appendChild(self.__createTextNode(user))
        self.__addToRoot(usersElem)

    def dbs(self, dbs):
        '''
        Adds a list of the existing databases to the xml
        '''
        dbsElem = self.__doc.createElement(DBS_ELEM_NAME)
        if dbs:
            for db in dbs:
                dbElem = self.__doc.createElement(DB_NAME_ELEM_NAME)
                dbsElem.appendChild(dbElem)
                dbElem.appendChild(self.__createTextNode(db))
        self.__addToRoot(dbsElem)

    def userSettings(self, header, userSettings, subHeader):
        '''
        Adds information about the user's settings to the xml.
        The information can be user's passwords, privileges and etc..
        '''
        self.__areAdmins = set()
        userSettingsElem = self.__getRootChild(USER_SETTINGS_ELEM_NAME)
        if (not (userSettingsElem)):
            userSettingsElem = self.__doc.createElement(
                USER_SETTINGS_ELEM_NAME)
            self.__addToRoot(userSettingsElem)

        userSettingElem = self.__doc.createElement(USER_SETTING_ELEM_NAME)
        userSettingElem.setAttributeNode(
            self.__createAttribute(TYPE_ATTR, header))

        if isinstance(userSettings, (tuple, list, set)):
            self.__areAdmins = userSettings[1]
            userSettings = userSettings[0]

        users = userSettings.keys()
        users.sort(key=lambda x: x.lower())

        for user in users:
            userElem = self.__doc.createElement(USER_ELEM_NAME)
            userSettingElem.appendChild(userElem)
            if user in self.__areAdmins:
                userElem.setAttributeNode(
                    self.__createAttribute(TYPE_ATTR, ADMIN_USER))
            else:
                userElem.setAttributeNode(
                    self.__createAttribute(TYPE_ATTR, REGULAR_USER))

            settings = userSettings[user]

            settings.sort()

            for setting in settings:
                settingsElem = self.__doc.createElement(SETTINGS_ELEM_NAME)
                settingsElem.setAttributeNode(
                    self.__createAttribute(TYPE_ATTR, subHeader))
                settingTextNode = self.__createTextNode(setting)
                settingsElem.appendChild(settingTextNode)
                userElem.appendChild(settingsElem)
        userSettingsElem.appendChild(userSettingElem)

    def dbTables(self, dbTables):
        '''
        Adds information of the existing db tables to the xml
        '''
        if not isinstance(dbTables, dict):
            self.string(TABLES_ELEM_NAME, dbTables)
            return

        dbTablesElem = self.__doc.createElement(DB_TABLES_ELEM_NAME)

        for db, tables in dbTables.items():
            tables.sort(key=lambda x: x.lower())
            dbElem = self.__doc.createElement(DATABASE_ELEM_NAME)
            dbElem.setAttributeNode(self.__createAttribute(NAME_ATTR, db))
            dbTablesElem.appendChild(dbElem)
            for table in tables:
                tableElem = self.__doc.createElement(DB_TABLE_ELEM_NAME)
                tableElem.appendChild(self.__createTextNode(table))
                dbElem.appendChild(tableElem)
        self.__addToRoot(dbTablesElem)

    def dbTableColumns(self, tableColumns):
        '''
        Adds information about the columns of the existing tables to the xml
        '''

        columnsElem = self.__getRootChild(COLUMNS_ELEM_NAME)
        if not (columnsElem):
            columnsElem = self.__doc.createElement(COLUMNS_ELEM_NAME)

        for db, tables in tableColumns.items():
            if not db:
                db = DEFAULT_DB
            dbElem = self.__doc.createElement(DATABASE_COLUMNS_ELEM)
            dbElem.setAttributeNode(self.__createAttribute(NAME_ATTR, db))
            columnsElem.appendChild(dbElem)

            for table, columns in tables.items():
                tableElem = self.__doc.createElement(TABLE_ELEM_NAME)
                tableElem.setAttributeNode(
                    self.__createAttribute(NAME_ATTR, table))

                colList = columns.keys()
                colList.sort(key=lambda x: x.lower())

                for column in colList:
                    colType = columns[column]
                    colElem = self.__doc.createElement(COLUMN_ELEM_NAME)
                    if colType is not None:
                        colElem.setAttributeNode(
                            self.__createAttribute(TYPE_ATTR, colType))
                    else:
                        colElem.setAttributeNode(
                            self.__createAttribute(TYPE_ATTR,
                                                   UNKNOWN_COLUMN_TYPE))
                    colElem.appendChild(self.__createTextNode(column))
                    tableElem.appendChild(colElem)

        self.__addToRoot(columnsElem)

    def dbTableValues(self, tableValues):
        '''
        Adds the values of specific table to the xml.
        The values are organized according to the relevant row and column.
        '''
        tableElem = self.__doc.createElement(DB_TABLE_VALUES_ELEM_NAME)
        if (tableValues is not None):
            db = tableValues["__infos__"]["db"]
            if not db:
                db = "All"
            table = tableValues["__infos__"]["table"]

            count = int(tableValues["__infos__"]["count"])
            columns = tableValues.keys()
            columns.sort(key=lambda x: x.lower())

            tableElem.setAttributeNode(self.__createAttribute(DB_ATTR, db))
            tableElem.setAttributeNode(self.__createAttribute(
                NAME_ATTR, table))

            for i in range(count):
                rowElem = self.__doc.createElement(ROW_ELEM_NAME)
                tableElem.appendChild(rowElem)
                for column in columns:
                    if column != "__infos__":
                        info = tableValues[column]
                        value = info["values"][i]

                        if re.search("^[\ *]*$", value):
                            value = "NULL"

                        cellElem = self.__doc.createElement(CELL_ELEM_NAME)
                        cellElem.setAttributeNode(
                            self.__createAttribute(COLUMN_ATTR, column))
                        cellElem.appendChild(self.__createTextNode(value))
                        rowElem.appendChild(cellElem)

        dbValuesElem = self.__getRootChild(DB_VALUES_ELEM)
        if (not (dbValuesElem)):
            dbValuesElem = self.__doc.createElement(DB_VALUES_ELEM)
            self.__addToRoot(dbValuesElem)

        dbValuesElem.appendChild(tableElem)

        logger.info("Table '%s.%s' dumped to XML file" % (db, table))

    def dbColumns(self, dbColumns, colConsider, dbs):
        '''
        Adds information about the columns
        '''
        for column in dbColumns.keys():
            printDbs = {}
            for db, tblData in dbs.items():
                for tbl, colData in tblData.items():
                    for col, dataType in colData.items():
                        if column in col:
                            if db in printDbs:
                                if tbl in printDbs[db]:
                                    printDbs[db][tbl][col] = dataType
                                else:
                                    printDbs[db][tbl] = {col: dataType}
                            else:
                                printDbs[db] = {}
                                printDbs[db][tbl] = {col: dataType}

                            continue

        self.dbTableColumns(printDbs)

    def query(self, query, queryRes):
        '''
        Adds details of an executed query to the xml.
        The query details are the query itself and it's results.
        '''
        queryElem = self.__doc.createElement(QUERY_ELEM_NAME)
        queryElem.setAttributeNode(self.__createAttribute(VALUE_ATTR, query))
        queryElem.appendChild(self.__createTextNode(queryRes))
        queriesElem = self.__getRootChild(QUERIES_ELEM_NAME)
        if (not (queriesElem)):
            queriesElem = self.__doc.createElement(QUERIES_ELEM_NAME)
            self.__addToRoot(queriesElem)
        queriesElem.appendChild(queryElem)

    def registerValue(self, registerData):
        '''
        Adds information about an extracted registry key to the xml
        '''
        registerElem = self.__doc.createElement(REGISTER_DATA_ELEM_NAME)
        registerElem.appendChild(self.__createTextNode(registerData))
        registriesElem = self.__getRootChild(REGISTERY_ENTRIES_ELEM_NAME)
        if (not (registriesElem)):
            registriesElem = self.__doc.createElement(
                REGISTERY_ENTRIES_ELEM_NAME)
            self.__addToRoot(registriesElem)
        registriesElem.appendChild(registerElem)

    def rFile(self, filePath, data):
        '''
        Adds an extracted file's content to the xml
        '''
        fileContentElem = self.__doc.createElement(FILE_CONTENT_ELEM_NAME)
        fileContentElem.setAttributeNode(
            self.__createAttribute(NAME_ATTR, filePath))
        fileContentElem.appendChild(self.__createTextNode(data))
        self.__addToRoot(fileContentElem)

    def setOutputFile(self):
        '''
        Initiates the xml file from the configuration.
        '''
        if (conf.xmlFile):
            try:
                self.__outputFile = conf.xmlFile
                self.__root = None

                if os.path.exists(self.__outputFile):
                    try:
                        self.__doc = xml.dom.minidom.parse(self.__outputFile)
                        self.__root = self.__doc.childNodes[0]
                    except ExpatError:
                        self.__doc = Document()

                self.__outputFP = codecs.open(self.__outputFile, "w+",
                                              UNICODE_ENCODING)

                if self.__root is None:
                    self.__root = self.__doc.createElementNS(
                        NAME_SPACE_ATTR, RESULTS_ELEM_NAME)
                    self.__root.setAttributeNode(
                        self.__createAttribute(XMLNS_ATTR, NAME_SPACE_ATTR))
                    self.__root.setAttributeNode(
                        self.__createAttribute(SCHEME_NAME_ATTR, SCHEME_NAME))
                    self.__doc.appendChild(self.__root)
            except IOError:
                raise sqlmapFilePathException(
                    "Wrong filename provided for saving the xml file: %s" %
                    conf.xmlFile)

    def getOutputFile(self):
        return self.__outputFile

    def finish(self, resultStatus, resultMsg=""):
        '''
        Finishes the dumper operation:
        1. Adds the session status to the xml
        2. Writes the xml to the file
        3. Closes the xml file
        '''
        if ((self.__outputFP is not None) and not (self.__outputFP.closed)):
            statusElem = self.__doc.createElement(STATUS_ELEM_NAME)
            statusElem.setAttributeNode(
                self.__createAttribute(SUCESS_ATTR, getUnicode(resultStatus)))

            if not resultStatus:
                errorElem = self.__doc.createElement(ERROR_ELEM_NAME)

                if isinstance(resultMsg, Exception):
                    errorElem.setAttributeNode(
                        self.__createAttribute(TYPE_ATTR,
                                               type(resultMsg).__name__))
                else:
                    errorElem.setAttributeNode(
                        self.__createAttribute(TYPE_ATTR,
                                               UNHANDLED_PROBLEM_TYPE))

                errorElem.appendChild(
                    self.__createTextNode(getUnicode(resultMsg)))
                statusElem.appendChild(errorElem)

            self.__addToRoot(statusElem)
            self.__write(
                prettyprint.formatXML(self.__doc, encoding=UNICODE_ENCODING))
            self.__outputFP.close()
Example #29
0
    def SaveSettings(self,
                     saveAccountDetails=None,
                     savePassword=None,
                     game=None):
        doc = None

        # Check if settings directory exists if not create
        if not os.path.exists(self.settingsDir):
            os.mkdir(self.settingsDir)
        if not self.osType.usingWindows:
            os.makedirs(self.settingsDir + "wine/prefix", exist_ok=True)

        # Check if settings file exists if not create new settings XML
        if os.path.exists(self.settingsFile):
            doc = defusedxml.minidom.parse(self.settingsFile)
            settingsNode = doc.getElementsByTagName("Settings")
        else:
            doc = Document()
            settingsNode = doc.createElementNS(EMPTY_NAMESPACE, "Settings")
            doc.appendChild(settingsNode)

        current_game = game if game else self.currentGame
        # Set default game to current game
        defaultGameNode = doc.getElementsByTagName("Default.Game")
        if len(defaultGameNode) > 0:
            defaultGameNode[0].firstChild.nodeValue = current_game
        else:
            defaultGameNode = doc.createElementNS(EMPTY_NAMESPACE,
                                                  "Default.Game")
            defaultGameNode.appendChild(doc.createTextNode(current_game))
            settingsNode.appendChild(defaultGameNode)

        # Remove old game block
        tempNode = doc.getElementsByTagName(current_game)
        if len(tempNode) > 0:
            doc.documentElement.removeChild(tempNode[0])

        # Create new game block
        settingsNode = doc.getElementsByTagName("Settings")[0]
        gameConfigNode = doc.createElementNS(EMPTY_NAMESPACE, current_game)
        settingsNode.appendChild(gameConfigNode)

        # Some settings for test/preview clients are saved in normal client settings
        if current_game.endswith(".Test"):
            normalClientNode = self.getNormalClientNode(current_game, doc)
            if not normalClientNode:
                normalClientNode = doc.createElementNS(EMPTY_NAMESPACE,
                                                       current_game)
                settingsNode.appendChild(normalClientNode)

        if not self.osType.usingWindows:
            tempNode = doc.createElementNS(EMPTY_NAMESPACE, "Wine.Program")
            tempNode.appendChild(doc.createTextNode("%s" % (self.wineProg)))
            gameConfigNode.appendChild(tempNode)

            tempNode = doc.createElementNS(EMPTY_NAMESPACE, "Wine.Debug")
            tempNode.appendChild(doc.createTextNode("%s" % (self.wineDebug)))
            gameConfigNode.appendChild(tempNode)

            if self.winePrefix != "":
                tempNode = doc.createElementNS(EMPTY_NAMESPACE, "Wine.Prefix")
                tempNode.appendChild(
                    doc.createTextNode("%s" % (self.winePrefix)))
                gameConfigNode.appendChild(tempNode)

        tempNode = doc.createElementNS(EMPTY_NAMESPACE, "HiRes")
        if self.hiResEnabled:
            tempNode.appendChild(doc.createTextNode("True"))
        else:
            tempNode.appendChild(doc.createTextNode("False"))
        gameConfigNode.appendChild(tempNode)

        tempNode = doc.createElementNS(EMPTY_NAMESPACE, "x64Client")
        if self.x64ClientEnabled:
            tempNode.appendChild(doc.createTextNode("True"))
        else:
            tempNode.appendChild(doc.createTextNode("False"))
        gameConfigNode.appendChild(tempNode)

        tempNode = doc.createElementNS(EMPTY_NAMESPACE, "Game.Directory")
        tempNode.appendChild(doc.createTextNode("%s" % (self.gameDir)))
        gameConfigNode.appendChild(tempNode)

        tempNode = doc.createElementNS(EMPTY_NAMESPACE, "PatchClient")
        tempNode.appendChild(doc.createTextNode("%s" % (self.patchClient)))
        gameConfigNode.appendChild(tempNode)

        tempNode = doc.createElementNS(EMPTY_NAMESPACE, "Language")
        tempNode.appendChild(doc.createTextNode("%s" % (self.language)))
        gameConfigNode.appendChild(tempNode)

        if saveAccountDetails:
            accountsNode = doc.createElementNS(EMPTY_NAMESPACE, "Accounts")

            # Adds all saved accounts with their account specific settings.
            for account in self.accountsDictionary:
                accountNode = doc.createElementNS(EMPTY_NAMESPACE, account)

                tempNode = doc.createElementNS(EMPTY_NAMESPACE, "World")
                tempNode.appendChild(
                    doc.createTextNode("%s" %
                                       (self.accountsDictionary[account][0])))
                accountNode.appendChild(tempNode)

                accountsNode.appendChild(accountNode)

            # Test/preview clients use normal client accounts. I.e they are
            # saved and loaded to and from the normal client node rather than the test node
            if current_game.endswith(".Test"):
                # Delete current accounts node if present. All accounts that were originally
                # there were loaded as if they were the test client's, so they are not lost.
                originalAccountsNode = normalClientNode.getElementsByTagName(
                    "Accounts")
                if originalAccountsNode:
                    normalClientNode.removeChild(originalAccountsNode[0])

                normalClientNode.appendChild(accountsNode)
            else:
                gameConfigNode.appendChild(accountsNode)

            if savePassword:
                tempNode = doc.createElementNS(EMPTY_NAMESPACE,
                                               "Save.Password")
                tempNode.appendChild(doc.createTextNode("True"))
                gameConfigNode.appendChild(tempNode)

        startupScriptsNode = doc.createElementNS(EMPTY_NAMESPACE,
                                                 "StartupScripts")
        for script in self.startupScripts:
            scriptNode = doc.createElementNS(EMPTY_NAMESPACE, "script")
            scriptNode.appendChild(doc.createTextNode("%s" % (script)))
            startupScriptsNode.appendChild(scriptNode)
        # Test/Preview clients store startup scripts in normal client settings,
        # because the add-ons folders are generally shared as well.
        if current_game.endswith(".Test"):
            # Delete current startup scripts node if present. All startup scripts
            # that were originally there were loaded as if they were the test client's,
            # so they are not lost.
            originalStartupScriptsNode = normalClientNode.getElementsByTagName(
                "StartupScripts")
            if originalStartupScriptsNode:
                normalClientNode.removeChild(originalStartupScriptsNode[0])

            normalClientNode.appendChild(startupScriptsNode)
        else:
            gameConfigNode.appendChild(startupScriptsNode)

        # write new settings file
        with open(self.settingsFile, "w") as file:
            pretty_xml = prettify_xml(doc.toxml())
            file.write(pretty_xml)
Example #30
0
def createFeed(examples):
    doc = Document()
    atomuri = "http://www.w3.org/2005/Atom"
    feed = doc.createElementNS(atomuri, "feed")
    feed.setAttribute("xmlns", atomuri)
    title = doc.createElementNS(atomuri, "title")
    title.appendChild(doc.createTextNode("OpenLayers Examples"))
    feed.appendChild(title)
    link = doc.createElementNS(atomuri, "link")
    link.setAttribute("rel", "self")
    link.setAttribute("href", feedPath + feedName)

    modtime = time.strftime("%Y-%m-%dT%I:%M:%SZ", time.gmtime())
    id = doc.createElementNS(atomuri, "id")
    id.appendChild(doc.createTextNode("%s%s#%s" % (feedPath, feedName, modtime)))
    feed.appendChild(id)

    updated = doc.createElementNS(atomuri, "updated")
    updated.appendChild(doc.createTextNode(modtime))
    feed.appendChild(updated)

    examples.sort(key=lambda x: x["modified"])
    for example in sorted(examples, key=lambda x: x["modified"], reverse=True):
        entry = doc.createElementNS(atomuri, "entry")

        title = doc.createElementNS(atomuri, "title")
        title.appendChild(doc.createTextNode(example["title"] or example["example"]))
        entry.appendChild(title)

        tags = doc.createElementNS(atomuri, "tags")
        tags.appendChild(doc.createTextNode(example["tags"] or example["example"]))
        entry.appendChild(tags)

        link = doc.createElementNS(atomuri, "link")
        link.setAttribute("href", "%s%s" % (feedPath, example["example"]))
        entry.appendChild(link)

        summary = doc.createElementNS(atomuri, "summary")
        summary.appendChild(doc.createTextNode(example["shortdesc"] or example["example"]))
        entry.appendChild(summary)

        updated = doc.createElementNS(atomuri, "updated")
        updated.appendChild(doc.createTextNode(example["modified"]))
        entry.appendChild(updated)

        author = doc.createElementNS(atomuri, "author")
        name = doc.createElementNS(atomuri, "name")
        name.appendChild(doc.createTextNode(example["author"]))
        author.appendChild(name)
        entry.appendChild(author)

        id = doc.createElementNS(atomuri, "id")
        id.appendChild(doc.createTextNode("%s%s#%s" % (feedPath, example["example"], example["modified"])))
        entry.appendChild(id)

        feed.appendChild(entry)

    doc.appendChild(feed)
    return doc
Example #31
0
from xml.dom.minidom import Document

doc = Document()

# create the envelope element and set its attributes
envelope = doc.createElementNS('', 's:Envelope')
envelope.setAttribute('xmlns:s', 'http://schemas.xmlsoap.org/soap/envelope/')
envelope.setAttribute('s:encodingStyle',
                      'http://schemas.xmlsoap.org/soap/encoding/')

# create the body element
body = doc.createElementNS('', 's:Body')

# create the function element and set its attribute
fn = doc.createElementNS('', 'u:AddPortMapping')
fn.setAttribute('xmlns:u', 'urn:schemas-upnp-org:service:WANIPConnection:1')

# setup the argument element names and values
# using a list of tuples to preserve order
arguments = [
    ('NewRemoteHost', ''),
    ('NewExternalPort', '2400'),  # specify port on router
    ('NewProtocol', 'TCP'),  # specify protocol
    ('NewInternalPort', '2400'),  # specify port on internal host
    ('NewInternalClient', '192.168.0.104'),  # specify IP of internal host
    ('NewEnabled', '1'),  # turn mapping ON
    ('NewPortMappingDescription', 'Test desc'),  # add a description
    ('NewLeaseDuration', '0')
]  # how long should it be opened?

# NewEnabled should be 1 by default, but better supply it.
Example #32
0
		# create a DOM object that represents the `directory` document
		dom = parseString(directory)
		# find all 'serviceType' elements
		service_types = dom.getElementsByTagName('serviceType')
		# iterate over service_types until we get either WANIPConnection
		# (this should also check for WANPPPConnection, which, if I remember correctly
		# exposed a similar SOAP interface on ADSL routers.
		for service in service_types:
			# I'm using the fact that a 'serviceType' element contains a single text node, who's data can
			# be accessed by the 'data' attribute.
			# When I find the right element, I take a step up into its parent and search for 'controlURL'
			if service.childNodes[0].data.find('WANIPConnection') > 0:
				path = service.parentNode.getElementsByTagName('controlURL')[0].childNodes[0].data
		doc = Document()
		# create the envelope element and set its attributes
		envelope = doc.createElementNS('', 's:Envelope')
		envelope.setAttribute('xmlns:s', 'http://schemas.xmlsoap.org/soap/envelope/')
		envelope.setAttribute('s:encodingStyle', 'http://schemas.xmlsoap.org/soap/encoding/')
		# create the body element
		body = doc.createElementNS('', 's:Body')
		# create the function element and set its attribute
		fn = doc.createElementNS('', 'u:AddPortMapping')
		fn.setAttribute('xmlns:u', 'urn:schemas-upnp-org:service:WANIPConnection:1')
		# setup the argument element names and values
		# using a list of tuples to preserve order
		arguments = [
			('NewRemoteHost', ''),
			('NewExternalPort', '4242'),           # specify port on router
			('NewProtocol', 'TCP'),                 # specify protocol
			('NewInternalPort', '4242'),           # specify port on internal host
			('NewInternalClient', '192.168.0.32'), # specify IP of internal host
Example #33
0
    def __call__(self, *args, **kwargs):

        total_params = len(list(kwargs.keys())) + len(args)

        if len(self.params) < total_params:
            raise RuntimeError(
                'To many parameters specified for UPNP funcion {0}.\n'
                'Allowed parameters are {1}'.format(
                    self.__name__,
                    ', '.join(param.__name__ for param in self.params)))

        for i, arg in enumerate(args):
            try:
                kwargs[self.params[i].__name__] = arg
            except IndexError:
                for param in self.params:
                    print(param.__name__)
                raise

        doc = Document()

        envelope = doc.createElementNS('', 's:Envelope')
        envelope.setAttribute('xmlns:s', ENVELOPE_XMLNS)
        envelope.setAttribute('s:encodingStyle',
                              'http://schemas.xmlsoap.org/soap/encoding/')

        body = doc.createElementNS('', 's:Body')

        fn = doc.createElementNS('', self.__name__)
        fn.setAttribute('xmlns:u', self.service)

        for param in self.params:
            if param.__name__ not in kwargs:
                value = param(None)
            else:
                value = param(kwargs[param.__name__])

            tmp_node = doc.createElement(param.__name__)
            tmp_text_node = doc.createTextNode(str(value))
            tmp_node.appendChild(tmp_text_node)
            fn.appendChild(tmp_node)

        body.appendChild(fn)
        envelope.appendChild(body)
        doc.appendChild(envelope)
        pure_xml = doc.toxml()

        header = {
            'SOAPAction':
            '"{service}#{method}"'.format(service=self.service,
                                          method=self.__name__),
            'Content-Type':
            'text/xml'
        }

        logger.debug(self.__parent.ip_address + ' <-- (' + self.control_url +
                     ') header: ' + str(header) + ' body: ' + pure_xml)
        try:
            response = requests.post(self.control_url,
                                     data=pure_xml,
                                     headers=header)
        except (requests.exceptions.ConnectionError,
                requests.exceptions.ConnectTimeout):
            return [None] * len(self.ret_vals)

        logger.debug(self.__parent.ip_address + ' --> (' + self.control_url +
                     ') ' + response.content.decode('utf-8'))

        try:
            envelope = etree.fromstring(response.content.decode('utf-8'))
        except etree.ParseError:
            return [None] * len(self.ret_vals)
        except ValueError:
            try:
                envelope = etree.fromstring(response.content)
            except etree.ParseError:
                return [None] * len(self.ret_vals)

        envelope = strip_xmlns(envelope)

        body = envelope.find('Body')

        return_value = []

        if body is not None:

            response = body.find(self.__name__ + 'Response')
            if response is not None:
                for ret_val in self.ret_vals:
                    value = response.find(ret_val.__name__)
                    if value is None:
                        value = ret_val(None)
                    else:
                        value = ret_val(value.text)

                    return_value += [value]

        if not return_value and self.ret_vals:
            for val in self.ret_vals:
                return_value += [val(None)]

        return return_value
Example #34
0
    def generate_name_id(value, sp_nq, sp_format, cert=None, debug=False):
        """
        Generates a nameID.

        :param value: fingerprint
        :type: string

        :param sp_nq: SP Name Qualifier
        :type: string

        :param sp_format: SP Format
        :type: string

        :param cert: IdP Public Cert to encrypt the nameID
        :type: string

        :param debug: Activate the xmlsec debug
        :type: bool

        :returns: DOMElement | XMLSec nameID
        :rtype: string
        """
        doc = Document()
        name_id_container = doc.createElementNS(OneLogin_Saml2_Constants.NS_SAML, 'container')
        name_id_container.setAttribute("xmlns:saml", OneLogin_Saml2_Constants.NS_SAML)

        name_id = doc.createElement('saml:NameID')
        name_id.setAttribute('SPNameQualifier', sp_nq)
        name_id.setAttribute('Format', sp_format)
        name_id.appendChild(doc.createTextNode(value))
        name_id_container.appendChild(name_id)

        if cert is not None:
            xml = name_id_container.toxml()
            elem = fromstring(xml)

            xmlsec.initialize()

            if debug:
                xmlsec.set_error_callback(print_xmlsec_errors)

            # Load the public cert
            mngr = xmlsec.KeysMngr()
            file_cert = OneLogin_Saml2_Utils.write_temp_file(cert)
            key_data = xmlsec.Key.load(file_cert.name, xmlsec.KeyDataFormatCertPem, None)
            key_data.name = basename(file_cert.name)
            mngr.addKey(key_data)
            file_cert.close()

            # Prepare for encryption
            enc_data = EncData(xmlsec.TransformAes128Cbc, type=xmlsec.TypeEncElement)
            enc_data.ensureCipherValue()
            key_info = enc_data.ensureKeyInfo()
            # enc_key = key_info.addEncryptedKey(xmlsec.TransformRsaPkcs1)
            enc_key = key_info.addEncryptedKey(xmlsec.TransformRsaOaep)
            enc_key.ensureCipherValue()

            # Encrypt!
            enc_ctx = xmlsec.EncCtx(mngr)
            enc_ctx.encKey = xmlsec.Key.generate(xmlsec.KeyDataAes, 128, xmlsec.KeyDataTypeSession)

            edata = enc_ctx.encryptXml(enc_data, elem[0])

            newdoc = parseString(etree.tostring(edata))

            if newdoc.hasChildNodes():
                child = newdoc.firstChild
                child.removeAttribute('xmlns')
                child.removeAttribute('xmlns:saml')
                child.setAttribute('xmlns:xenc', OneLogin_Saml2_Constants.NS_XENC)
                child.setAttribute('xmlns:dsig', OneLogin_Saml2_Constants.NS_DS)

            nodes = newdoc.getElementsByTagName("*")
            for node in nodes:
                if node.tagName == 'ns0:KeyInfo':
                    node.tagName = 'dsig:KeyInfo'
                    node.removeAttribute('xmlns:ns0')
                    node.setAttribute('xmlns:dsig', OneLogin_Saml2_Constants.NS_DS)
                else:
                    node.tagName = 'xenc:' + node.tagName

            encrypted_id = newdoc.createElement('saml:EncryptedID')
            encrypted_data = newdoc.replaceChild(encrypted_id, newdoc.firstChild)
            encrypted_id.appendChild(encrypted_data)
            return newdoc.saveXML(encrypted_id)
        else:
            return doc.saveXML(name_id)
Example #35
0
def open_port(service_url,
              external_port,
              internal_client,
              internal_port=None,
              protocol='TCP',
              duration=0,
              description=None,
              enabled=1):
    parsedurl = urlparse(service_url)

    if internal_port == None:
        internal_port = external_port

    if description == None:
        description = 'generated by port-forward.py'

    if not enabled:
        duration = 1

    doc = Document()

    # create the envelope element and set its attributes
    envelope = doc.createElementNS('', 's:Envelope')
    envelope.setAttribute('xmlns:s',
                          'http://schemas.xmlsoap.org/soap/envelope/')
    envelope.setAttribute('s:encodingStyle',
                          'http://schemas.xmlsoap.org/soap/encoding/')

    # create the body element
    body = doc.createElementNS('', 's:Body')

    # create the function element and set its attribute
    fn = doc.createElementNS('', 'u:AddPortMapping')
    fn.setAttribute('xmlns:u',
                    'urn:schemas-upnp-org:service:WANIPConnection:1')

    # setup the argument element names and values
    # using a list of tuples to preserve order
    arguments = [
        ('NewRemoteHost', ""),  # unused - but required
        ('NewExternalPort', external_port),  # specify port on router
        ('NewProtocol', protocol),  # specify protocol
        ('NewInternalPort', internal_port),  # specify port on internal host
        ('NewInternalClient', internal_client),  # specify IP of internal host
        ('NewEnabled', enabled),  # turn mapping ON
        ('NewPortMappingDescription', description),  # add a description
        ('NewLeaseDuration', duration)
    ]  # how long should it be opened?

    # NewEnabled should be 1 by default, but better supply it.
    # NewPortMappingDescription Can be anything you want, even an empty string.
    # NewLeaseDuration can be any integer BUT some UPnP devices don't support it,
    # so set it to 0 for better compatibility.

    # container for created nodes
    argument_list = []

    # iterate over arguments, create nodes, create text nodes,
    # append text nodes to nodes, and finally add the ready product
    # to argument_list
    for k, v in arguments:
        v = str(v)
        tmp_node = doc.createElement(k)
        tmp_text_node = doc.createTextNode(v)
        tmp_node.appendChild(tmp_text_node)
        argument_list.append(tmp_node)

    # append the prepared argument nodes to the function element
    for arg in argument_list:
        fn.appendChild(arg)

    # append function element to the body element
    body.appendChild(fn)

    # append body element to envelope element
    envelope.appendChild(body)

    # append envelope element to document, making it the root element
    doc.appendChild(envelope)

    # our tree is ready, conver it to a string
    pure_xml = doc.toxml()

    # use the object returned by urlparse.urlparse to get the hostname and port
    conn = HTTPConnection(parsedurl.hostname, parsedurl.port)

    # use the path of WANIPConnection (or WANPPPConnection) to target that service,
    # insert the xml payload,
    # add two headers to make tell the server what we're sending exactly.
    conn.request(
        'POST', parsedurl.path, pure_xml, {
            'SOAPAction':
            '"urn:schemas-upnp-org:service:WANIPConnection:1#AddPortMapping"',
            'Content-Type': 'text/xml'
        })

    # wait for a response
    resp = conn.getresponse()

    return resp.status, resp.read()
Example #36
0
    def serializeList(self, itemOrList):
        prov = 'http://www.w3.org/ns/prov#'
        nfo = 'http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#'
        dct = 'http://purl.org/dc/terms/'
        dom = Document()
        doc = dom.createElementNS(prov, 'prov:document')
        doc.setAttribute('xmlns:prov', prov)
        doc.setAttribute('xmlns:nfo', nfo)
        doc.setAttribute('xmlns:dct', dct)
        dom.appendChild(doc)
        for i, item in enumerate(itemOrList):
            entity = dom.createElementNS(prov, 'prov:entity')
            entityId = 'niprov:file'+str(i)
            entity.setAttribute('id', entityId)

            fileUrl = dom.createElementNS(nfo, 'nfo:fileUrl')
            fileUrlVal = dom.createTextNode(item.location.toUrl())
            fileUrl.appendChild(fileUrlVal)
            entity.appendChild(fileUrl)

            if 'size' in item.provenance:

                fileSize = dom.createElementNS(nfo, 'nfo:fileSize')
                fileSizeVal = dom.createTextNode(str(item.provenance['size']))
                fileSize.appendChild(fileSizeVal)
                entity.appendChild(fileSize)

            if 'created' in item.provenance:

                fileLastMod = dom.createElementNS(nfo, 'nfo:fileLastModified')
                fileLastModVal = dom.createTextNode(item.provenance['created'].isoformat())
                fileLastMod.appendChild(fileLastModVal)
                entity.appendChild(fileLastMod)

            if 'hash' in item.provenance:

                fileHash = dom.createElementNS(nfo, 'nfo:FileHash')
                hashId = entityId+'.hash'
                fileHash.setAttribute('id', hashId)

                hashAlgo = dom.createElementNS(nfo, 'nfo:hashAlgorithm')
                hashAlgoVal = dom.createTextNode('MD5')
                hashAlgo.appendChild(hashAlgoVal)
                fileHash.appendChild(hashAlgo)

                hashValue = dom.createElementNS(nfo, 'nfo:hashValue')
                hashValueVal = dom.createTextNode(item.provenance['hash'])
                hashValue.appendChild(hashValueVal)
                fileHash.appendChild(hashValue)

                hasHash = dom.createElementNS(nfo, 'nfo:hasHash')
                hasHashVal = dom.createTextNode(hashId)
                hasHash.appendChild(hasHashVal)
                entity.appendChild(hasHash)

                doc.appendChild(fileHash)

            if 'transformation' in item.provenance:

                act = dom.createElementNS(prov, 'prov:activity')
                activityId = entityId+'.xform'
                act.setAttribute('id', activityId)

                actTitle = dom.createElementNS(dct, 'dct:title')
                actTitleVal = dom.createTextNode(item.provenance['transformation'])
                actTitle.appendChild(actTitleVal)
                act.appendChild(actTitle)
                doc.appendChild(act)

                wasGen = dom.createElementNS(prov, 'prov:wasGeneratedBy')
                entityRef = dom.createElementNS(prov, 'prov:entity')
                entityRef.setAttribute('prov:ref', entityId)
                wasGen.appendChild(entityRef)
                activityRef = dom.createElementNS(prov, 'prov:activity')
                activityRef.setAttribute('prov:ref', activityId)
                wasGen.appendChild(activityRef)
                doc.appendChild(wasGen)

                if 'created' in item.provenance:
                    wasGenTime = dom.createElementNS(prov, 'prov:time')
                    wasGenTimeVal = dom.createTextNode(item.provenance['created'].isoformat())
                    wasGenTime.appendChild(wasGenTimeVal)
                    wasGen.appendChild(wasGenTime)

            doc.appendChild(entity)

        return dom.toprettyxml(encoding="UTF-8")
Example #37
0
def open_port(service_url,external_port,internal_client,internal_port=None,protocol='TCP',duration=0,description=None,enabled=1):
    parsedurl = urlparse(service_url)

    if internal_port==None:
        internal_port = external_port

    if description == None:
        description = 'generated by port-forward.py'

    if not enabled:
        duration=1

    doc = Document()

    # create the envelope element and set its attributes
    envelope = doc.createElementNS('', 's:Envelope')
    envelope.setAttribute('xmlns:s', 'http://schemas.xmlsoap.org/soap/envelope/')
    envelope.setAttribute('s:encodingStyle', 'http://schemas.xmlsoap.org/soap/encoding/')

    # create the body element
    body = doc.createElementNS('', 's:Body')

    # create the function element and set its attribute
    fn = doc.createElementNS('', 'u:AddPortMapping')
    fn.setAttribute('xmlns:u', 'urn:schemas-upnp-org:service:WANIPConnection:1')

    # setup the argument element names and values
    # using a list of tuples to preserve order
    arguments = [
        ('NewExternalPort', external_port),           # specify port on router
        ('NewProtocol', protocol),                 # specify protocol
        ('NewInternalPort', internal_port),           # specify port on internal host
        ('NewInternalClient', internal_client), # specify IP of internal host
        ('NewEnabled', enabled),                    # turn mapping ON
        ('NewPortMappingDescription', description), # add a description
        ('NewLeaseDuration', duration)]              # how long should it be opened?

    # NewEnabled should be 1 by default, but better supply it.
    # NewPortMappingDescription Can be anything you want, even an empty string.
    # NewLeaseDuration can be any integer BUT some UPnP devices don't support it,
    # so set it to 0 for better compatibility.

    # container for created nodes
    argument_list = []

    # iterate over arguments, create nodes, create text nodes,
    # append text nodes to nodes, and finally add the ready product
    # to argument_list
    for k, v in arguments:
        v = str(v)
        tmp_node = doc.createElement(k)
        tmp_text_node = doc.createTextNode(v)
        tmp_node.appendChild(tmp_text_node)
        argument_list.append(tmp_node)

    # append the prepared argument nodes to the function element
    for arg in argument_list:
        fn.appendChild(arg)

    # append function element to the body element
    body.appendChild(fn)

    # append body element to envelope element
    envelope.appendChild(body)

    # append envelope element to document, making it the root element
    doc.appendChild(envelope)

    # our tree is ready, conver it to a string
    pure_xml = doc.toxml()

    # use the object returned by urlparse.urlparse to get the hostname and port
    conn = httplib.HTTPConnection(parsedurl.hostname, parsedurl.port)

    # use the path of WANIPConnection (or WANPPPConnection) to target that service,
    # insert the xml payload,
    # add two headers to make tell the server what we're sending exactly.
    conn.request('POST',
        parsedurl.path,
        pure_xml,
        {'SOAPAction': '"urn:schemas-upnp-org:service:WANIPConnection:1#AddPortMapping"',
         'Content-Type': 'text/xml'}
    )

    # wait for a response
    resp = conn.getresponse()

    return resp.status,resp.read()
Example #38
0
def get_XSD(conf):
    xmlfile = Document()
    
    schema = xmlfile.createElementNS('xs','schema')
    schema.setAttributeNS('xmlns','xs','http://www.w3.org/2001/XMLSchema')
    schema.setAttribute("targetNamespace",'http://www.w3school.com.cn')
    schema.setAttribute('xmlns','http://www.w3school.com.cn')
    schema.setAttribute('elementFormDefault','qualified')
    xmlfile.appendChild(schema)

    root=xmlfile.createElementNS('xs','element')
    root.setAttribute('name','root ')
    complex = xmlfile.createElementNS('xs','complexType')
    schema.appendChild(root)

    root.appendChild(complex)

    information = xmlfile.createElementNS('xs','sequence')
    complex.appendChild(information)

    conffile=open(conf)
    father=None

    while len(elements):
        elements.pop()
        
    for line in conffile.readlines():
        temp=line.split('=')
        for j in range(len(temp)):
            temp[j]=temp[j].strip()
        te = xmlfile.createElementNS('xs','element')
        te.setAttribute('name',temp[0])
        elements.append(XMLE(temp[0],te))
        if len(temp)>1:
            temp[0]=temp[1].split(';')
            for j in temp[0]:
                j=j.strip()
                if j == '':
                    continue
                j=j.split(':')
                if j[0]=='type':
                    if j[1]=='str':
                        te.setAttribute('type','xs:string')
                    elif j[1]=='int':
                        te.setAttribute('type','xs:positiveInteger')
                elif j[0]=='fix':
                    te.setAttribute('fixed',j[1])
                elif j[0]=='maxo' :
                    if j[1]!='INF':
                        te.setAttribute("maxOccurs",j[1])
                    else:
                        te.setAttribute("maxOccurs","unbounded")
                elif j[0]=='mino':
                    te.setAttribute("maxOccurs",j[1])
                elif j[0]=='father':
                    father=serach_E_R(j[1])
                    if father == None:
                        te.setAttribute('error','no father node named :%s' % j[1])
            
            if father == None:
                information.appendChild(te)
            else:
                father.appendChild(te)
                father=None
    conffile.close()
    temp = conf.split('\\')            
    f=open('%s.xsd' % temp[-1].split('.')[0] ,'w')
    xmlfile.writexml(f, "\t", "\t", "\n", "gbk")
    f.close()
Example #39
0
def _prepare_response():
    doc = Document()
    resp = doc.createElementNS('http://www.yale.edu/tp/cas', 'cas:serviceResponse')
    resp.setAttribute('xmlns:cas', 'http://www.yale.edu/tp/cas') # seriously minidom?
    doc.appendChild(resp)
    return (doc, resp)
Example #40
0
def createFeed(examples):
    doc = Document()
    atomuri = "http://www.w3.org/2005/Atom"
    feed = doc.createElementNS(atomuri, "feed")
    feed.setAttribute("xmlns", atomuri)
    title = doc.createElementNS(atomuri, "title")
    title.appendChild(doc.createTextNode("procrastinatio.org's web mapping examples"))
    feed.appendChild(title)
    link = doc.createElementNS(atomuri, "link")
    link.setAttribute("rel", "self")
    link.setAttribute("href", feedPath + feedName)
    
    modtime = time.strftime("%Y-%m-%dT%I:%M:%SZ", time.gmtime())
    id = doc.createElementNS(atomuri, "id")
    id.appendChild(doc.createTextNode("%s%s#%s" % (feedPath, feedName, modtime)))
    feed.appendChild(id)
    
    updated = doc.createElementNS(atomuri, "updated")
    updated.appendChild(doc.createTextNode(modtime))
    feed.appendChild(updated)

    examples.sort(key=lambda x:x["modified"])
    for example in sorted(examples, key=lambda x:x["modified"], reverse=True):
        entry = doc.createElementNS(atomuri, "entry")
        
        title = doc.createElementNS(atomuri, "title")
        title.appendChild(doc.createTextNode(example["title"] or example["example"]))
        entry.appendChild(title)
              
        tags = doc.createElementNS(atomuri, "tags")
        tags.appendChild(doc.createTextNode(example["tags"] or example["example"]))
        entry.appendChild(tags)
        
        link = doc.createElementNS(atomuri, "link")
        link.setAttribute("href", "%s%s" % (feedPath, example["example"]))
        entry.appendChild(link)
    
        summary = doc.createElementNS(atomuri, "summary")
        summary.appendChild(doc.createTextNode(example["shortdesc"] or example["example"]))
        entry.appendChild(summary)
        
        updated = doc.createElementNS(atomuri, "updated")
        updated.appendChild(doc.createTextNode(example["modified"]))
        entry.appendChild(updated)
        
        author = doc.createElementNS(atomuri, "author")
        name = doc.createElementNS(atomuri, "name")
        name.appendChild(doc.createTextNode(example["author"]))
        author.appendChild(name)
        entry.appendChild(author)
        
        id = doc.createElementNS(atomuri, "id")
        id.appendChild(doc.createTextNode("%s%s#%s" % (feedPath, example["example"], example["modified"])))
        entry.appendChild(id)
        
        feed.appendChild(entry)

    doc.appendChild(feed)
    return doc    
Example #41
0
    def add_port_mapping(self, local_ip):
        SSDP_ADDR = "239.255.255.250"
        SSDP_PORT = 1900
        SSDP_MX = 2
        SSDP_ST = "urn:schemas-upnp-org:device:InternetGatewayDevice:1"

        ssdpRequest = "M-SEARCH * HTTP/1.1\r\n" + \
                        "HOST: %s:%d\r\n" % (SSDP_ADDR, SSDP_PORT) + \
                        "MAN: \"ssdp:discover\"\r\n" + \
                        "MX: %d\r\n" % (SSDP_MX, ) + \
                        "ST: %s\r\n" % (SSDP_ST, ) + "\r\n"
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sock.sendto(str.encode(ssdpRequest), (SSDP_ADDR, SSDP_PORT))
        resp = sock.recv(1000)

        import re
        from urllib import parse

        parsed = re.findall(r'(?P<name>.*?): (?P<value>.*?)\r\n',
                            resp.decode('utf-8'))
        # get the location header
        location = list(filter(lambda x: x[0].lower() == "location", parsed))
        # use the urlparse function to create an easy to use object to hold a URL
        router_path = parse.urlparse(location[0][1])

        from urllib.request import urlopen
        from xml.dom.minidom import parseString
        # get the profile xml file and read it into a variable
        directory = urlopen(location[0][1]).read()

        # create a DOM object that represents the `directory` document
        dom = parseString(directory)

        # find all 'serviceType' elements
        service_types = dom.getElementsByTagName('serviceType')

        # iterate over service_types until we get either WANIPConnection
        # (this should also check for WANPPPConnection, which, if I remember correctly
        # exposed a similar SOAP interface on ADSL routers.
        for service in service_types:
            # I'm using the fact that a 'serviceType' element contains a single text node, who's data can
            # be accessed by the 'data' attribute.
            # When I find the right element, I take a step up into its parent and search for 'controlURL'
            if service.childNodes[0].data.find('WANIPConnection') > 0:
                path = str(
                    service.parentNode.getElementsByTagName('controlURL')
                    [0].childNodes[0].data)
                #path = service.parentNode.getElementsByTagName('controlURL')[0].childNodes[0].data)

        from xml.dom.minidom import Document

        doc = Document()

        # create the envelope element and set its attributes
        envelope = doc.createElementNS('', 's:Envelope')
        envelope.setAttribute('xmlns:s',
                              'http://schemas.xmlsoap.org/soap/envelope/')
        envelope.setAttribute('s:encodingStyle',
                              'http://schemas.xmlsoap.org/soap/encoding/')

        # create the body element
        body = doc.createElementNS('', 's:Body')

        # create the function element and set its attribute
        fn = doc.createElementNS('', 'u:AddPortMapping')
        fn.setAttribute('xmlns:u',
                        'urn:schemas-upnp-org:service:WANIPConnection:1')

        # setup the argument element names and values
        # using a list of tuples to preserve order
        arguments = [
            ('NewRemoteHost', ''),
            ('NewExternalPort', '43210'),  # specify port on router
            ('NewProtocol', 'TCP'),  # specify protocol
            ('NewInternalPort', '43210'),  # specify port on internal host
            ('NewInternalClient', local_ip),  # specify IP of internal host
            ('NewEnabled', '1'),  # turn mapping ON
            ('NewPortMappingDescription',
             'Maneframe Tensorflow'),  # add a description
            ('NewLeaseDuration', '0')
        ]  # how long should it be opened?

        # NewEnabled should be 1 by default, but better supply it.
        # NewPortMappingDescription Can be anything you want, even an empty string.
        # NewLeaseDuration can be any integer BUT some UPnP devices don't support it,
        # so set it to 0 for better compatibility.

        # container for created nodes
        argument_list = []

        # iterate over arguments, create nodes, create text nodes,
        # append text nodes to nodes, and finally add the ready product
        # to argument_list
        for k, v in arguments:
            tmp_node = doc.createElement(k)
            tmp_text_node = doc.createTextNode(v)
            tmp_node.appendChild(tmp_text_node)
            argument_list.append(tmp_node)

        # append the prepared argument nodes to the function element
        for arg in argument_list:
            fn.appendChild(arg)

        # append function element to the body element
        body.appendChild(fn)

        # append body element to envelope element
        envelope.appendChild(body)

        # append envelope element to document, making it the root element
        doc.appendChild(envelope)

        # our tree is ready, conver it to a string
        pure_xml = doc.toxml()

        import http.client

        # use the object returned by urlparse.urlparse to get the hostname and port
        print(pure_xml)
        conn = http.client.HTTPConnection(router_path.hostname,
                                          router_path.port)

        # use the path of WANIPConnection (or WANPPPConnection) to target that service,
        # insert the xml payload,
        # add two headers to make tell the server what we're sending exactly.
        conn.request(
            'POST', path, pure_xml, {
                'SOAPAction':
                '"urn:schemas-upnp-org:service:WANIPConnection:1#AddPortMapping"',
                'Content-Type': 'text/xml'
            })

        # wait for a response
        resp = conn.getresponse()

        # print the response status
        print(resp.status)

        # print the response body
        print(resp.read())