Example #1
0
def submitData(dataRaw):
    global APIPipe
    print(APIPipe)
    data = RawCoT()
    data.clientInformation = "SERVER"
    data.xmlString = dataRaw.encode()
    APIPipe.send([data])
Example #2
0
def test(json):
    modelObject = Event.dropPoint()
    out = XMLCoTController().serialize_CoT_to_model(modelObject,
                                                    etree.fromstring(json))
    xml = XMLCoTController().serialize_model_to_CoT(out, 'event')
    from FreeTAKServer.controllers.SpecificCoTControllers.SendDropPointController import SendDropPointController
    rawcot = RawCoT()
    rawcot.xmlString = xml
    rawcot.clientInformation = None
    object = SendDropPointController(rawcot)
    print(
        etree.tostring(object.sendDropPoint.xmlString,
                       pretty_print=True).decode())
    '''EventObject = json
Example #3
0
 def returnReceivedData(self, clientInformation, data, queue):
     try:
         from FreeTAKServer.model.RawCoT import RawCoT
         # print(data)
         RawCoT = RawCoT()
         RawCoT.clientInformation = clientInformation
         RawCoT.xmlString = data
         self.dataPipe.append(RawCoT)
         return 1
     except Exception as e:
         logger.error(loggingConstants.
                      CLIENTRECEPTIONHANDLERRETURNRECEIVEDDATAERROR +
                      str(e))
         return -1
Example #4
0
def SendGeoChat():
    try:
        json = request.json
        modelObject = Event.GeoChat()
        out = ApplyFullJsonController().serializeJsonToModel(modelObject, json)
        xml = XMLCoTController().serialize_model_to_CoT(out, 'event')
        from FreeTAKServer.controllers.SpecificCoTControllers.SendGeoChatController import SendGeoChatController
        rawcot = RawCoT()
        rawcot.xmlString = xml
        rawcot.clientInformation = None
        object = SendGeoChatController(rawcot)
        APIPipe.send(object.getObject())
        return '200', 200
    except Exception as e:
        print(e)
    def sendUserConnectionGeoChat(self, clientInformation):
        # TODO: refactor as it has a proper implementation of a PM to a user generated by the server
        '''
        function to create and send pm to connecting user
        :param clientInformation:
        :return:
        '''
        from FreeTAKServer.controllers.SpecificCoTControllers.SendGeoChatController import SendGeoChatController
        from FreeTAKServer.model.RawCoT import RawCoT
        from FreeTAKServer.model.FTSModel.Dest import Dest
        import uuid
        if OrchestratorConstants().DEFAULTCONNECTIONGEOCHATOBJ != None:
            ChatObj = RawCoT()
            ChatObj.xmlString = f'<event><point/><detail><remarks>{OrchestratorConstants().DEFAULTCONNECTIONGEOCHATOBJ}</remarks><marti><dest/></marti></detail></event>'

            classobj = SendGeoChatController(ChatObj, AddToDB=False)
            instobj = classobj.getObject()
            instobj.modelObject.detail._chat.chatgrp.setuid1(
                clientInformation.modelObject.uid)
            dest = Dest()
            dest.setcallsign(
                clientInformation.modelObject.detail.contact.callsign)
            instobj.modelObject.detail.marti.setdest(dest)
            instobj.modelObject.detail._chat.setchatroom(
                clientInformation.modelObject.detail.contact.callsign)
            instobj.modelObject.detail._chat.setparent("RootContactGroup")
            instobj.modelObject.detail._chat.setid(
                clientInformation.modelObject.uid)
            instobj.modelObject.detail._chat.setgroupOwner("True")
            instobj.modelObject.detail.remarks.setto(
                clientInformation.modelObject.uid)
            instobj.modelObject.setuid(
                'GeoChat.' + 'SERVER-UID.' +
                clientInformation.modelObject.detail.contact.callsign + '.' +
                str(uuid.uuid1()))
            instobj.modelObject.detail._chat.chatgrp.setid(
                clientInformation.modelObject.uid)
            classobj.reloadXmlString()
            SendDataController().sendDataInQueue(None, instobj,
                                                 self.clientInformationQueue)
            return 1
        else:
            return 1
Example #6
0
def addSystemUser(jsondata):
    from FreeTAKServer.controllers import certificate_generation
    import uuid
    for systemuser in json.loads(jsondata)['systemUsers']:
        if systemuser["Certs"] == "true":
            # create certs
            certificate_generation.AtakOfTheCerts().bake(cn=systemuser["Name"])
            certificate_generation.generate_zip(
                user_filename=systemuser["Name"] + '.p12')
            # add DP
            import string
            import random
            from pathlib import PurePath, Path
            import hashlib
            from lxml import etree
            import shutil
            import os
            dp_directory = str(PurePath(Path(MainConfig.DataPackageFilePath)))
            letters = string.ascii_letters
            openfile = open(str(
                PurePath(
                    Path(str(MainConfig.clientPackages),
                         systemuser["Name"] + '.zip'))),
                            mode='rb')
            file_hash = str(hashlib.sha256(openfile.read()).hexdigest())
            openfile.close()
            newDirectory = str(PurePath(Path(dp_directory), Path(file_hash)))
            os.mkdir(newDirectory)
            shutil.copy(
                str(
                    PurePath(
                        Path(str(MainConfig.clientPackages),
                             systemuser["Name"] + '.zip'))),
                str(
                    PurePath(Path(newDirectory),
                             Path(systemuser["Name"] + '.zip'))))
            fileSize = Path(str(newDirectory),
                            systemuser["Name"] + '.zip').stat().st_size
            dbController.create_datapackage(uid=str(uuid.uuid4()),
                                            Name=systemuser["Name"] + '.zip',
                                            Hash=file_hash,
                                            SubmissionUser='******',
                                            CreatorUid='server-uid',
                                            Size=fileSize,
                                            Privacy=1)
            DatabaseController().create_systemUser(
                name=systemuser["Name"],
                group=systemuser["Group"],
                token=systemuser["Token"],
                password=systemuser["Password"],
                uid=str(uuid.uuid4()),
                certificate_package_name=systemuser["Name"] + '.zip')
            import datetime as dt
            DATETIME_FMT = "%Y-%m-%dT%H:%M:%S.%fZ"
            timer = dt.datetime
            now = timer.utcnow()
            zulu = now.strftime(DATETIME_FMT)
            add = dt.timedelta(seconds=600)
            stale_part = dt.datetime.strptime(zulu, DATETIME_FMT) + add
            stale = stale_part.strftime(DATETIME_FMT)
            timer = dt.datetime
            now = timer.utcnow()
            zulu = now.strftime(DATETIME_FMT)
            time = zulu
            from FreeTAKServer.controllers.SpecificCoTControllers.SendOtherController import SendOtherController
            from FreeTAKServer.model.RawCoT import RawCoT
            cot = RawCoT()
            clientXML = f'<?xml version="1.0"?><event version="2.0" uid="{str(uuid.uuid4())}" type="b-f-t-r" time="{time}" start="{time}" stale="{stale}" how="h-e"><point lat="43.85570300" lon="-66.10801200" hae="19.55866360" ce="3.21600008" le="nan" /><detail><fileshare filename="{systemuser["Name"]}" senderUrl="{MainConfig.DataPackageServiceDefaultIP}:8080/Marti/api/sync/metadata/{str(file_hash)}/tool" sizeInBytes="{fileSize}" sha256="{str(file_hash)}" senderUid="{"server-uid"}" senderCallsign="{"server"}" name="{systemuser["Name"]+".zip"}" /><ackrequest uid="{uuid.uuid4()}" ackrequested="true" tag="{systemuser["Name"]+".zip"}" /><marti><dest callsign="{systemuser["Name"]}" /></marti></detail></event>'
            cot.xmlString = clientXML.encode()
            newCoT = SendOtherController(cot)
            APIPipe.send(newCoT.getObject())

        else:
            DatabaseController().create_systemUser(
                name=systemuser["Name"],
                group=systemuser["Group"],
                token=systemuser["Token"],
                password=systemuser["Password"],
                uid=str(uuid.uuid4()))
    def clientDisconnected(self, clientInformation):
        if hasattr(clientInformation, "clientInformation"):
            clientInformation = clientInformation.clientInformation
        try:
            for client in self.clientInformationQueue:
                if client.ID == clientInformation.ID:
                    self.clientInformationQueue.remove(client)
                else:
                    pass
        except AttributeError:
            for client in self.clientInformationQueue:
                if client.ID == clientInformation.clientInformation.ID:
                    self.clientInformationQueue.remove(client)
                else:
                    pass
        except Exception as e:
            self.logger.critical("client removal failed " + str(e))
        try:
            self.ActiveThreadsController.removeClientThread(clientInformation)
            self.dbController.remove_user(
                query=f'uid = "{clientInformation.modelObject.uid}"')
        except Exception as e:
            self.logger.critical(
                'there has been an error in a clients disconnection while adding information to the database '
                + str(e))
            pass
        if hasattr(clientInformation, 'clientInformation'):
            clientInformation = clientInformation.clientInformation
        else:
            pass
        try:
            self.openSockets -= 1
            socketa = clientInformation.socket
            clientInformation.socket = None
            self.clientDataPipe.put(
                ['remove', clientInformation, self.openSockets])
            clientInformation.socket = socketa
            try:
                clientInformation.socket.shutdown(socket.SHUT_RDWR)
            except Exception as e:
                self.logger.error(
                    'error shutting socket down in client disconnection')
                pass
            try:
                clientInformation.socket.close()
            except Exception as e:
                self.logger.error(
                    'error closing socket in client disconnection')
                pass

            self.logger.info(loggingConstants.CLIENTDISCONNECTSTART)
            # TODO: remove string
            tempXml = RawCoT()
            tempXml.xmlString = '<event><detail><link uid="{0}"/></detail></event>'.format(
                clientInformation.modelObject.uid).encode()
            disconnect = SendDisconnectController(tempXml)
            SendDataController().sendDataInQueue(
                disconnect.getObject().clientInformation,
                disconnect.getObject(), self.clientInformationQueue,
                self.CoTSharePipe)
            self.logger.info(
                loggingConstants.CLIENTDISCONNECTEND +
                str(clientInformation.modelObject.detail.contact.callsign))
            return 1
        except Exception as e:
            self.logger.error(loggingConstants.CLIENTCONNECTEDERROR + " " +
                              str(e))
            pass
Example #8
0
def updatetemplate(checklistid, taskid):
    from flask import request
    from defusedxml import ElementTree as etree
    from FreeTAKServer.controllers.SpecificCoTControllers.SendExcheckUpdateController import SendExcheckUpdateController
    from FreeTAKServer.controllers.XMLCoTController import XMLCoTController
    from FreeTAKServer.model.FTSModel.Event import Event
    from FreeTAKServer.model.RawCoT import RawCoT
    import uuid
    import hashlib

    data = request.data

    xml = etree.parse(
        str(
            PurePath(Path(MainConfig.ExCheckChecklistFilePath),
                     Path(checklistid + '.xml')))).getroot()
    updatedTask = etree.fromstring(data)
    tasks = xml.find('checklistTasks')
    for task in tasks:
        uid = task.find('uid')
        if uid.text == taskid:
            tasks.replace(task, updatedTask)
        else:
            pass
    with open(
            str(
                PurePath(Path(MainConfig.ExCheckChecklistFilePath),
                         Path(checklistid + '.xml'))), 'w+') as file:
        file.write(etree.tostring(xml).decode())
        file.close()

    # Create Object to send to client
    object = Event.ExcheckUpdate()
    object.setuid(str(uuid.uuid4()))
    object.setversion('2.0')
    object.detail.mission.settype("CHANGE")
    object.detail.mission.settool("ExCheck")
    object.detail.mission.setname(checklistid)
    object.detail.mission.setauthorUid(request.args.get("clientUid"))
    object.detail.mission.MissionChanges.MissionChange.creatorUid.setINTAG(
        request.args.get("clientUid"))
    object.detail.mission.MissionChanges.MissionChange.missionName.setINTAG(
        checklistid)
    object.detail.mission.MissionChanges.MissionChange.type.setINTAG(
        "ADD_CONTENT")
    object.detail.mission.MissionChanges.MissionChange.contentResource.filename.setINTAG(
        taskid + '.xml')
    object.detail.mission.MissionChanges.MissionChange.contentResource.hash.setINTAG(
        str(
            hashlib.sha256(
                str(
                    open(
                        MainConfig.ExCheckChecklistFilePath + '/' +
                        checklistid + '.xml', 'r')).encode()).hexdigest()))
    object.detail.mission.MissionChanges.MissionChange.contentResource.keywords.setINTAG(
        'Task')
    object.detail.mission.MissionChanges.MissionChange.contentResource.name.setINTAG(
        taskid)
    object.detail.mission.MissionChanges.MissionChange.contentResource.size.setINTAG(
        str(len(data)))
    #TODO: change this value
    object.detail.mission.MissionChanges.MissionChange.contentResource.submitter.setINTAG(
        'atak')
    object.detail.mission.MissionChanges.MissionChange.contentResource.uid.setINTAG(
        taskid)
    '''object = etree.fromstring(templateex)
    object.uid = uuid.uuid4()
    object.find('detail').find('mission').type= "CHANGE"
    object.find('detail').find('mission').name = taskid
    object.find('detail').find('mission').Uid = request.args.get("clientUid")
    object.find('detail').find('mission').find('MissionChanges').find('MissionChange').find('creatorUid').text = request.args.get("clientUid")
    object.find('detail').find('mission').find('MissionChanges').find('MissionChange').find('missionName').text = taskid
    object.find('detail').find('mission').find('MissionChanges').find('MissionChange').find('filename').text = checklistid+'.xml'
    object.detail.mission.MissionChanges.MissionChange.contentResource.hash.setINTAG(str(hashlib.sha256(str(data).encode()).hexdigest()))
    object.detail.mission.MissionChanges.MissionChange.contentResource.keywords.setINTAG('Task')
    object.detail.mission.MissionChanges.MissionChange.contentResource.name.setINTAG(checklistid)
    object.detail.mission.MissionChanges.MissionChange.contentResource.size.setINTAG(str(len(data)))
    #TODO: change this value
    object.detail.mission.MissionChanges.MissionChange.contentResource.submitter.setINTAG('test')
    object.detail.mission.MissionChanges.MissionChange.contentResource.uid.setINTAG(checklistid)'''
    rawcot = RawCoT()
    xml = XMLCoTController().serialize_model_to_CoT(object)
    rawcot.xmlString = xml

    PIPE.put(rawcot)
    #PIPE.send()

    return '', 200
Example #9
0
                raise TypeError(
                    'this function should only be supplied a list object')
        except Exception as e:
            return -1


if __name__ == "__main__":
    import multiprocessing
    from FreeTAKServer.controllers import SendOtherController
    from FreeTAKServer.model.RawCoT import RawCoT
    import time
    temp = RawCoT()
    temp.type = None
    temp.clientInformation = None
    temp.protocol = None
    temp.xmlString = b'<event version="2.0" uid="123e915c-7b9a-44ed-91e7-5165e384b213" type="a-h-G" time="2020-09-02T00:15:50.504Z" start="2020-09-02T00:15:50.504Z" stale="2020-09-02T00:20:50.504Z" how="h-g-i-g-o"><point lat="28.31507" lon="-81.34564" hae="-5.185734847652469" ce="6.0" le="9999999.0"/><detail><contact callsign="2340 Cordova Ct, Kissimmee, FL 34743, USA"/><status readiness="true"/><archive/><link uid="ANDROID-863134036519299" production_time="2020-07-19T18:32:31.535Z" type="a-f-G-E-V-C" parent_callsign="WP4JMV" relation="p-p"/><remarks/><archive/><ce_human_input>true</ce_human_input><color argb="-1"/><_flow-tags_ TAK-Server-c0a2d13e="2020-09-01T12:32:01Z"/></detail></event>'
    a, b = multiprocessing.Pipe()
    #multiprocessing.Process(target=).start()
    FtsObject = SendOtherController(temp).getObject()
    #b.send(FtsObject)
    FederationClientServiceController(a, '192.168.2.105', 9000).start()
    time.sleep(1000)
    x = 1
    '''
    event {
  sendTime: 1598963344000
  startTime: 1599005949000
  staleTime: 1599006324000
  lat: 43.855695
  lon: -66.108016
  hae: 13.058658054176142
    def clientDisconnected(self, clientInformation):
        import time
        import traceback
        from copy import deepcopy
        print(str(traceback.format_stack()))
        print('disconnecting client')
        if hasattr(clientInformation, "clientInformation"):
            clientInformation = clientInformation.clientInformation
        """try:
            clientInformation.socket.send(b'sample')
            return 1
        except:
            try:
                clientInformation.socket.settimeout(0)
                if clientInformation.socket.recv() == b'':
                    pass
                else:
                    return 1
            except:
                return 1"""
        try:
            for client in self.clientInformationQueue:
                if client.ID == clientInformation.ID:
                    self.clientInformationQueue.remove(client)
                else:
                    pass
        except AttributeError:
            for client in self.clientInformationQueue:
                if client.ID == clientInformation.clientInformation.ID:
                    self.clientInformationQueue.remove(client)
                else:
                    pass
        except Exception as e:
            self.logger.critical("client removal failed " + str(e))
        print('stage 1')
        #time.sleep(1)
        try:
            self.ActiveThreadsController.removeClientThread(clientInformation)
            self.dbController.remove_user(
                query=f'uid = "{clientInformation.modelObject.uid}"')
        except Exception as e:
            self.logger.critical(
                'there has been an error in a clients disconnection while adding information to the database '
                + str(e))
            pass
        print('stage 1 a')
        if hasattr(clientInformation, 'clientInformation'):
            clientInformation = clientInformation.clientInformation
        else:
            pass
        try:
            self.openSockets -= 1
            socketa = clientInformation.socket
            clientInformation.socket = None
            clientInformationcopy = deepcopy(clientInformation)
            print('stage 1 b')
            #time.sleep(1)
            if clientInformationcopy.socket == None:
                self.clientDataPipe.put(
                    ['remove', clientInformationcopy, self.openSockets])
            #working
            #time.sleep(1)
            print('stage 1 c')
            clientInformation.socket = socketa
            try:
                clientInformation.socket.shutdown(socket.SHUT_RDWR)
            except Exception as e:
                self.logger.error(
                    'error shutting socket down in client disconnection')
                pass
            try:
                clientInformation.socket.close()
            except Exception as e:
                self.logger.error(
                    'error closing socket in client disconnection')
                pass
            #time.sleep(1)
            print('stage 2')

            self.logger.info(loggingConstants.CLIENTDISCONNECTSTART)
            # TODO: remove string
            tempXml = RawCoT()
            tempXml.xmlString = '<event><detail><link uid="{0}"/></detail></event>'.format(
                clientInformation.modelObject.uid).encode()
            disconnect = SendDisconnectController(tempXml)
            print('stage 3')
            #working
            #time.sleep(1)
            SendDataController().sendDataInQueue(
                disconnect.getObject().clientInformation,
                disconnect.getObject(), self.clientInformationQueue,
                self.CoTSharePipe)
            self.logger.info(
                loggingConstants.CLIENTDISCONNECTEND +
                str(clientInformation.modelObject.detail.contact.callsign))
            print('client disconnected')
            return 1
        except Exception as e:
            print(e)
            self.logger.error(loggingConstants.CLIENTCONNECTEDERROR + " " +
                              str(e))
            pass
Example #11
0
    #contr.remove_datapackage('Hash == "36e4506f4d6a9582fc60529525c55f3ebd42b887b5164d24e44b85d7ea686a3d"')
    #UID = 123
    #callsign = contr.query_user(query=f'uid == "{UID}"', column=['callsign'])
    # contr.(uid='9', CreatorUid='abc123', Hash='1bc21o', Keywords="foobar", MIMEType="aaa/bbb", Name="other", Privacy=1, Size=32, SubmissionDateTime=dt.datetime.utcnow(), SubmissionUser="******")
    y = contr.query_user()

    from FreeTAKServer.controllers.SpecificCoTControllers.SendDropPointController import SendDropPointController
    from FreeTAKServer.model.RawCoT import RawCoT
    from FreeTAKServer.model.SQLAlchemy.Event import Event
    from FreeTAKServer.model.SQLAlchemy.CoTTables.Detail import Detail
    import uuid
    m = RawCoT()
    e1 = Event(uid=str(uuid.uuid4()))
    d1 = Detail()
    d1.Event = e1
    contr.session.add(e1)
    contr.session.commit()
    m.xmlString = "<event version='2.0' uid='4oh2-4265fe-83hb-9bd3442e6de0' type='a-h-G' time='2020-05-06T13:29:25.146Z' start='2020-05-06T13:29:25.146Z' stale='2020-05-06T13:34:25.146Z' how='h-g-i-g-o'><point lat='44.22054348420014' lon='-66.14146066424053' hae='9999999.0' ce='9999999.0' le='9999999.0' /><detail><status readiness='true'/><archive/><precisionlocation altsrc='???'/><archive/><usericon iconsetpath='COT_MAPPING_2525B/a-h/a-h-G'/><contact callsign='Bob'/><color argb='-1'/><link uid='ANDROID-352614100054990' production_time='2020-01-20T00:15:03.281Z' type='a-f-G-U-C' parent_callsign='Peregrin' relation='p-p'/><marti><dest callsign = 'abc'/></marti></detail></event>"
    # m.xmlString = "<event version='2.0' uid='87f64797-4ae2-42ce-83cb-9bd3442e6dd0' type='a-h-G' time='2020-05-06T13:29:25.146Z' start='2020-05-06T13:29:25.146Z' stale='2020-05-06T13:34:25.146Z' how='h-g-i-g-o'><point lat='44.22054348420014' lon='-66.14146066424053' hae='9999999.0' ce='9999999.0' le='9999999.0' /><detail/></event>"
    x = SendDropPointController(m)
    b = RawCoT()
    b.dbController = contr
    b.xmlString = '<event version="2.0" uid="5bbka076-caea-4766-a300-1c9ac3f58d00" type="a-n-G" how="h-g-i-g-o" start="2020-09-30T00:56:29.71Z" time="2020-07-18T13:38:31.220Z" stale="2020-10-07T00:56:29.71Z"><detail><status readiness="true"/><usericon iconsetpath="COT_MAPPING_2525B/a-n/a-n-G"/><link uid="ANDROID-359975090666199" relation="p-p" production_time="2020-07-11T17:31:36.007Z" type="a-f-G-U-C" parent_callsign="NOVA"/><color argb="-1"/><precisionlocation altsrc="???"/><contact callsign="N.11.143136"/><remarks time="2020-09-30T00:56:12Z">DEFAULT</remarks></detail><point le="9999999.0" ce="9999999.0" hae="9999999.0" lon="-61.137312737751884" lat="-11.005735933018565"/></event>'
    x = SendDropPointController(b)
    y = x.getObject()
    contr.create_CoT(y.modelObject)
    x = contr.session.query(Event).all()[-1]
    #contr.create_user(callsign = 'abc')
    #import operator
    #a = contr.query_datapackage("uid == 423")