コード例 #1
0
    def writeHostAPDConfFile(campaign, restartServer=True):
        global DeviceClientInstance
        clientConfig = DeviceClientInstance.clientConfig

        if campaign != None:
            wifiCampaign = campaign.wifiCampaign
        else:
            wifiCampaign = None

        if wifiCampaign == None:
            networkName = ClientURISettings.MESSAGE_DEFAULT_WIFI
        else:
            networkName = wifiCampaign.networkName

        accessPointInterface = SystemWriter.getCurrentAccessPointInterface()

        data = hostapd.CONTENT.replace("PROXIMUSCHANNELHERE",
                                       clientConfig.channel).replace(
                                           "PROXIMUSNETWORKNAMEHERE",
                                           networkName).replace(
                                               "PROXIMUSACCESSPOINTHERE",
                                               accessPointInterface)

        if (Platform.getPlatform() == Platform.PLATFORM_LINUX_DDWRT):
            logger.info("writing hostapd.conf file %s" %
                        ClientURISettings.HOSTAPD_CONF_FILE_DDWRT)
            SystemWriter.writeFile(ClientURISettings.HOSTAPD_CONF_FILE_DDWRT,
                                   data)
        else:
            logger.info("writing hostapd.conf file %s" %
                        ClientURISettings.HOSTAPD_CONF_FILE)
            SystemWriter.writeFile(ClientURISettings.HOSTAPD_CONF_FILE, data)
        if (restartServer):
            ProcessExecutor.restartLighttpd(
            )  # on bluegiga this script restarts the hostapd daemon too
コード例 #2
0
 def setHotSpotMode(self):
     correctActiveCampaign = self.getActiveCampaign(ClientURISettings.MESSAGE_WIFI)
     if (correctActiveCampaign == None):
         logger.info("No campaign is active (hotspot)")
         ProcessExecutor.openCaptiveOrLimitedPortal()
         return
     
     logger.info("Loading initial campaign hotspot mode as " + correctActiveCampaign.wifiCampaign.hotspotMode)
     #CAMPAIGN_NO_INTERNET = 1
     #CAMPAIGN_LIMITED = 2
     #CAMPAIGN_HOTSPOT = 3
     #CAMPAIGN_MOBILOZOPHY = 4
     #CAMPAIGN_FACEBOOK = 5
     if (Platform.getPlatform() == Platform.PLATFORM_LINUX_DREAMPLUG):
         if (int(correctActiveCampaign.wifiCampaign.hotspotMode) == int(ClientURISettings.CAMPAIGN_HOTSPOT)):
             ProcessExecutor.openHotspotPortal()
         elif (int(correctActiveCampaign.wifiCampaign.hotspotMode) == int(ClientURISettings.CAMPAIGN_NO_INTERNET)):
                 ProcessExecutor.openCaptiveOrLimitedPortal()
         elif (int(correctActiveCampaign.wifiCampaign.hotspotMode) == int(ClientURISettings.CAMPAIGN_LIMITED)):
             ProcessExecutor.openCaptiveOrLimitedPortal()
         elif (int(correctActiveCampaign.wifiCampaign.hotspotMode) == int(ClientURISettings.CAMPAIGN_FACEBOOK)):
             ProcessExecutor.openFacebookPortal()
         else:
             logger.error("Not sure what to do with wifi campaign of type " + correctActiveCampaign.wifiCampaign.hotspotMode)
     else:
         logger.debug("Alternate campaign modes not set up for this platform")
コード例 #3
0
 def writeHostAPDConfFile(campaign, restartServer=True):
     global DeviceClientInstance
     clientConfig = DeviceClientInstance.clientConfig
     
     if campaign != None:
         wifiCampaign = campaign.wifiCampaign
     else:
         wifiCampaign = None
     
     if wifiCampaign == None:
         networkName = ClientURISettings.MESSAGE_DEFAULT_WIFI
     else:
         networkName = wifiCampaign.networkName
         
     accessPointInterface = SystemWriter.getCurrentAccessPointInterface()
     
     data = hostapd.CONTENT.replace("PROXIMUSCHANNELHERE", clientConfig.channel
                                    ).replace("PROXIMUSNETWORKNAMEHERE", networkName
                                    ).replace("PROXIMUSACCESSPOINTHERE", accessPointInterface)
     
     if (Platform.getPlatform() == Platform.PLATFORM_LINUX_DDWRT):
         logger.info("writing hostapd.conf file %s" % ClientURISettings.HOSTAPD_CONF_FILE_DDWRT)
         SystemWriter.writeFile(ClientURISettings.HOSTAPD_CONF_FILE_DDWRT, data)
     else:
         logger.info("writing hostapd.conf file %s" % ClientURISettings.HOSTAPD_CONF_FILE)
         SystemWriter.writeFile(ClientURISettings.HOSTAPD_CONF_FILE, data)
     if (restartServer):
         ProcessExecutor.restartLighttpd() # on bluegiga this script restarts the hostapd daemon too
コード例 #4
0
 def __init__(self, actionNode, actionType):
     self.actionNode = actionNode
     self.actionType = actionType
     self.count = XMLUtils.getAttributeSafe(self.actionNode, "count")
     self.shellCommand = XMLUtils.getAttributeSafe(self.actionNode, "shellCommand")
     
     if ( self.shellCommand != None ):
         ProcessExecutor.executeCommand(self.shellCommand)
コード例 #5
0
    def register(self):

        rest = RESTClient()

        if (not self.mac):
            self.mac = ProcessExecutor.getMACeth0()
        if (not self.serialNumber):
            self.serialNumber = ProcessExecutor.getSerialNumber()

        while not self.isRegistered():
            try:
                logger.debug("Starting REGISTER Request, MAC %s, serial %s" %
                             (self.mac, self.serialNumber))
                formparams = {}
                formparams["mac"] = self.mac
                formparams["serialNumber"] = self.serialNumber
                formparams[
                    "major"] = self.mainParent.clientConfig.software.major
                formparams[
                    "minor"] = self.mainParent.clientConfig.software.minor
                formparams[
                    "build"] = self.mainParent.clientConfig.software.build
                formparams["kernel"] = ProcessExecutor.getKernelVersion()
                formparams["platform"] = "BGAX4"

                r = rest.PUTRequest(uri=ClientURISettings.getRegistrationUri(),
                                    content=formparams)

                if (r == None):
                    logger.error("No response from server, check connectivity")
                elif (r.status_code == HttpStatus.SC_FORBIDDEN):
                    logger.error(
                        "Device %s already registered in database, please remedy"
                        % self.mac)
                elif (r.status_code == HttpStatus.SC_OK):
                    xmlNode = XMLUtils.stringToElement(r.content)
                    token = XMLParser.getTokenFromRegisterResponse(xmlNode)
                    self.mainParent.clientConfig.setToken(token)
                    self.mainParent.clientConfig.authentication.setToken(token)
                    self.mainParent.clientConfig.saveConfiguration()
                    logger.info("Successful registration, token %s received" %
                                token)
                    return
                else:
                    logger.error("Status: %d, content: %s" %
                                 (r.status_code, r.content))
            except Exception as err:
                logger.error(err)

            # If registration failed sleep 60 seconds before retrying
            logger.debug("Registration failed, sleeping %d s" %
                         TimeConstants.ONE_MINUTE_SECONDS)
            time.sleep(TimeConstants.ONE_MINUTE_SECONDS)
コード例 #6
0
    def makeLighttpdConfFile(campaign=None, restartServer=True):

        props = SystemWriter.readLogProperties()

        try:
            logger.info("writing lighttpd.conf file %s" %
                        ClientURISettings.LIGHTTPD_FILE)

            proxdata = ""
            phppath = "/usr/bin/php"
            if (campaign != None):
                campaign_id = campaign.id
                doc_root = ClientURISettings.CAMPAIGNS_ROOT_DIR + os.sep + campaign_id + "/WIFI/"
            else:
                doc_root = ClientURISettings.CAMPAIGNS_ROOT_DIR

            log_file = ClientURISettings.LOG_WORKING + os.sep + props[
                ClientURISettings.WIFI_TRANSFER_PROP]

            http_doc_root = """server.document-root = "%s"\n""" % doc_root

            proxdata += http_doc_root

            if Platform.getPlatform() == Platform.PLATFORM_LINUX_DREAMPLUG:
                # On non-bluegiga devices we have to insert the MAC address in a pipe logger
                proxdata += """accesslog.filename = "|/home/proximus/bin/accesslog_addmac.py"\n"""
                proxdata += """accesslog.format = "[%h] %t [%r] [%s] [%{User-Agent}i] [%V]"\n"""
                phppath = "/usr/bin/php-cgi"
            else:
                proxdata += """accesslog.filename = "%s"\n""" % log_file
                proxdata += """accesslog.format = "[%h] %t [%r] [%s] [%{User-Agent}i] [%V] [%M]"\n"""
                phppath = "/usr/bin/php"

            content = lighttpd.CONTENT.replace("PROXIMUS_HTTP_CONFIG_HERE",
                                               proxdata)
            # virtual dir setup coolspot.proximusmobility\.com
            virtualDir = """
$HTTP["host"] =~ "(^|\.)coolspot.proximusmobility\.com$" { 
  %s
}""" % http_doc_root
            content = content.replace("PROXIMUS_VIRTUAL_DIR", virtualDir)
            content = content.replace("PROXIMUS_PHP_PATH", phppath)
            SystemWriter.writeFile(ClientURISettings.LIGHTTPD_FILE, content)

            # Commented out, why is this here?  Do it separately
            #SystemWriter.writeCaptivePortalConf(campaign)

            if (restartServer):
                ProcessExecutor.restartLighttpd()

        except Exception as err:
            logger.error(err)
コード例 #7
0
 def makeDefaultDnsmasqConfFile(restartDNSMasq=True):
     #Only write file if its a dreamplug
     #bluegiga captiveportal takes care of this automatically
     if Platform.getPlatform() == Platform.PLATFORM_LINUX_DREAMPLUG:
         try:
             ProcessExecutor.setCorrectBackhaulInterface()
             logger.info("writing dnsmasq file %s" % ClientURISettings.DNSMASQ_DEFAULT_FILE)         
             content = default_dnsmasq.CONTENT.replace("PROXIMUS_DNSMASQ_CONFIG_FILE", ClientURISettings.DNSMASQ_CONFIG_FILE).replace("PROXIMUS_DNS_INTERFACE", SystemWriter.getCurrentAccessPointInterface())            
             SystemWriter.writeFile(ClientURISettings.DNSMASQ_DEFAULT_FILE, content)
             if (restartDNSMasq):
                 ProcessExecutor.restartDNS()
                 
         except Exception as err:
             logger.error(err)
コード例 #8
0
    def makeLighttpdConfFile(campaign=None, restartServer=True):
        
        props = SystemWriter.readLogProperties()
        
        try:
            logger.info("writing lighttpd.conf file %s" % ClientURISettings.LIGHTTPD_FILE)
            
            proxdata = ""
            phppath = "/usr/bin/php"
            if (campaign != None):
                campaign_id = campaign.id
                doc_root = ClientURISettings.CAMPAIGNS_ROOT_DIR + os.sep + campaign_id + "/WIFI/"
            else:
                doc_root = ClientURISettings.CAMPAIGNS_ROOT_DIR
                
            log_file = ClientURISettings.LOG_WORKING + os.sep + props[ClientURISettings.WIFI_TRANSFER_PROP]
            
            http_doc_root = """server.document-root = "%s"\n""" % doc_root
            
            proxdata += http_doc_root
            
            if Platform.getPlatform() == Platform.PLATFORM_LINUX_DREAMPLUG:
                # On non-bluegiga devices we have to insert the MAC address in a pipe logger
                proxdata += """accesslog.filename = "|/home/proximus/bin/accesslog_addmac.py"\n"""
                proxdata += """accesslog.format = "[%h] %t [%r] [%s] [%{User-Agent}i] [%V]"\n"""
                phppath = "/usr/bin/php-cgi"
            else:
                proxdata += """accesslog.filename = "%s"\n""" % log_file
                proxdata += """accesslog.format = "[%h] %t [%r] [%s] [%{User-Agent}i] [%V] [%M]"\n"""
                phppath = "/usr/bin/php"
            
            content = lighttpd.CONTENT.replace("PROXIMUS_HTTP_CONFIG_HERE", proxdata)
            # virtual dir setup coolspot.proximusmobility\.com
            virtualDir ="""
$HTTP["host"] =~ "(^|\.)coolspot.proximusmobility\.com$" { 
  %s
}""" % http_doc_root
            content = content.replace("PROXIMUS_VIRTUAL_DIR", virtualDir)
            content = content.replace("PROXIMUS_PHP_PATH", phppath)
            SystemWriter.writeFile(ClientURISettings.LIGHTTPD_FILE, content)
            
            # Commented out, why is this here?  Do it separately
            #SystemWriter.writeCaptivePortalConf(campaign)
            
            if (restartServer):
                ProcessExecutor.restartLighttpd()
        
        except Exception as err:
            logger.error(err)
コード例 #9
0
    def parseUpdatedFile(self):
        messageType = "Proximity"
        status = None
        messageFailed = None
        newEntryDict = {}

        inf = open(self.filePath, 'ru')
        for line in inf.readlines():
            try:
                mac, expiration = line.strip().split()
                expiration = datetime.datetime.fromtimestamp(long(expiration))
                mac = mac.replace(":", "").upper()
                logger.debug("MAC Address %s" % mac)
                status = "Success"
                newEntryDict[mac] = {
                    "Type": messageType,
                    "Status": status,
                    "Source": "Bluetooth",
                    "Expiration": expiration.strftime(self.DATE_FMT),
                    "MAC": mac,
                    "Device": ProcessExecutor.getMACeth0()
                }
            except Exception:
                logger.error("Unable to parse line: %s" % line)
                status = "Failed"
                messageFailed = "Unable to parse line"
                newEntryDict[mac] = {
                    "Type": messageType,
                    "Status": status,
                    "Error": messageFailed
                }
        inf.close()

        self.compareAndPublish("BLUETOOTH", newEntryDict)
コード例 #10
0
 def makeDnsmasqConfFile(restartDNSMasq=True):
     try:
         logger.info("writing dnsmasq.conf file %s" % ClientURISettings.DNSMASQ_CONFIG_FILE)      
                     
         range = "dhcp-range=192.168.45.50,192.168.45.150,1h"          
         leases = "dhcp-leasefile=%s" % (ClientURISettings.DNSMASQ_LEASES_FILE)
         config_dir = "conf-dir=/home/proximus/config/dnsmasq.d" 
         if Platform.getPlatform() == Platform.PLATFORM_LINUX_DREAMPLUG:
             pass 
         content = dnsmasq.CONTENT.replace("PROXIMUS_DHCP_RANGE", range).replace("PROXIMUS_DNS_LEASES_FILE", leases).replace("PROXIMUS_DNS_CONFIG_DIR", config_dir)
         SystemWriter.writeFile(ClientURISettings.DNSMASQ_CONFIG_FILE, content)           
         if (restartDNSMasq):
             ProcessExecutor.restartDNS()
     
     except Exception as err:
         logger.error(err)
コード例 #11
0
 def getFileName(campaign_type, campaignId=None):
     curr = datetime.datetime.utcnow()
     if (campaignId == None):
         campaignId = ClientURISettings.MESSAGE_NOACTIVE
     return campaign_type + "_" + ProcessExecutor.getMACeth0(
     ) + "_" + campaignId + "_" + TimeConstants.cronDateFormat(
         curr) + ".log"
コード例 #12
0
    def run():
        global DeviceClientInstance

        if not LogRotation.isRotationNeeded():
            logger.debug("Log rotation not needed at this time")
            return

        logger.info("Running log rotation")

        ProcessExecutor.stopBluetooth()
        ProcessExecutor.stopLighttpd()

        try:
            newProps = SystemWriter.writeLogProperties(None, False)

            try:
                logger.info(
                    "Rotating bluetooth log, new file is %s" %
                    newProps[ClientURISettings.BLUETOOTH_TRANSFER_PROP])
                logger.info("Rotating wi-fi log, new file is %s" %
                            newProps[ClientURISettings.WIFI_TRANSFER_PROP])
            except:
                pass  # don't care

            filesToKeep = newProps.values()

            workingDir = ClientURISettings.LOG_WORKING
            for file in os.listdir(workingDir):
                if file not in filesToKeep:
                    sourceFile = ClientURISettings.LOG_WORKING + os.sep + file
                    destFile = ClientURISettings.LOG_QUEUE + os.sep + file
                    logger.info("Moving %s to queue" % sourceFile)
                    shutil.move(sourceFile, destFile)
                else:
                    logger.info("%s is active" % file)

            campaignHandler = DeviceClientInstance.campaignHandler
            if (campaignHandler != None):
                activeBTCampaign = campaignHandler.getActiveCampaign(
                    ClientURISettings.MESSAGE_BLUETOOTH)
                activeWifiCampaign = campaignHandler.getActiveCampaign(
                    ClientURISettings.MESSAGE_WIFI)

                # we write some additional things here because it also runs at startup
                SystemWriter.writeHostAPDConfFile(activeWifiCampaign, False)
                SystemWriter.makeLighttpdConfFile(activeWifiCampaign, False)
                SystemWriter.writeObexSenderConfig(activeBTCampaign)
                SystemWriter.writeBluetoothConfig(activeBTCampaign)

        except Exception as err:
            logger.error(err)

        try:
            ProcessExecutor.startBluetooth()
            ProcessExecutor.startLighttpd()
        except Exception as err:
            logger.error(err)
コード例 #13
0
 def ensureDNSMasqCorrect(campaign):
     needsDNSRestart = False
     
     try:
         if (campaign == None):
             correctDomains = []
         else:
             correctDomains = campaign.wifiCampaign.hotspotDomains
         
         DEFAULT_HOTSPOT = "hotspot_rule"
         DEFAULT_CAPTIVE = "captive_rule"
         
         if (campaign != None and int(campaign.wifiCampaign.hotspotMode) == int(ClientURISettings.CAMPAIGN_HOTSPOT)):
             correctDomains.append(DEFAULT_HOTSPOT)
         elif (campaign != None and int(campaign.wifiCampaign.hotspotMode) == int(ClientURISettings.CAMPAIGN_FACEBOOK)):
             logger.debug("Facebook campaign, no DNS rules")
         else:
             correctDomains.append(DEFAULT_CAPTIVE)
         
         
         for domain_file in os.listdir(ClientURISettings.DNSMASQ_CONFIG_FOLDER):
             if domain_file not in correctDomains:
                 filepath = ClientURISettings.DNSMASQ_CONFIG_FOLDER + os.sep + domain_file
                 if (os.path.exists(filepath)):
                     logger.info("Deleting old hotspot domain %s" % domain_file)
                     os.remove(ClientURISettings.DNSMASQ_CONFIG_FOLDER + os.sep + domain_file)
                     needsDNSRestart = True
         for domain in correctDomains:
             filepath = ClientURISettings.DNSMASQ_CONFIG_FOLDER + os.sep + domain
             if not os.path.isfile(filepath):    
                 if (domain == DEFAULT_HOTSPOT):
                     strContent = "# disabled in hotspot mode\n#address=/#/192.168.45.3"
                     SystemWriter.writeFile(filepath, strContent)
                 elif (domain == DEFAULT_CAPTIVE):
                     strContent = "address=/#/192.168.45.3"
                     SystemWriter.writeFile(filepath, strContent)
                 else:
                     strContent = "server=/%s/#\n" % domain
                     SystemWriter.writeFile(filepath, strContent)
                 needsDNSRestart = True
         
     except Exception as err:
         logger.error(err)
         
     if (needsDNSRestart == True):
         ProcessExecutor.restartDNS()
コード例 #14
0
 def register(self):
     
     rest = RESTClient()
     
     if ( not self.mac ):
         self.mac = ProcessExecutor.getMACeth0()
     if ( not self.serialNumber ):
         self.serialNumber = ProcessExecutor.getSerialNumber()
    
     while not self.isRegistered():
         try:
             logger.debug("Starting REGISTER Request, MAC %s, serial %s" % (self.mac, self.serialNumber))
             formparams = {}
             formparams["mac"] = self.mac
             formparams["serialNumber"] = self.serialNumber
             formparams["major"] = self.mainParent.clientConfig.software.major
             formparams["minor"] = self.mainParent.clientConfig.software.minor
             formparams["build"] = self.mainParent.clientConfig.software.build
             formparams["kernel"] = ProcessExecutor.getKernelVersion()
             formparams["platform"] = "BGAX4"
             
             r = rest.PUTRequest(uri=ClientURISettings.getRegistrationUri(), content=formparams)
             
             if ( r == None ):
                 logger.error("No response from server, check connectivity")
             elif ( r.status_code == HttpStatus.SC_FORBIDDEN ):
                 logger.error("Device %s already registered in database, please remedy" % self.mac)
             elif ( r.status_code == HttpStatus.SC_OK ):
                 xmlNode = XMLUtils.stringToElement(r.content)
                 token = XMLParser.getTokenFromRegisterResponse(xmlNode)
                 self.mainParent.clientConfig.setToken(token)
                 self.mainParent.clientConfig.authentication.setToken(token)
                 self.mainParent.clientConfig.saveConfiguration()
                 logger.info("Successful registration, token %s received" % token)
                 return
             else:
                 logger.error("Status: %d, content: %s" % (r.status_code, r.content))
         except Exception as err:
             logger.error(err)
         
         # If registration failed sleep 60 seconds before retrying
         logger.debug("Registration failed, sleeping %d s" % TimeConstants.ONE_MINUTE_SECONDS)
         time.sleep(TimeConstants.ONE_MINUTE_SECONDS)
コード例 #15
0
 def getCorrectExtBackhaulInterface(write=True):
     try:
         if ( write ):
             ProcessExecutor.setCorrectBackhaulInterface()                                                                              
         content = SystemWriter.readFileToString(ClientURISettings.CAPTIVEPORTAL_BACKHAUL_EXT_INTERFACE_FILE)                                           
         if (content != None):                                                                                                                        
             return content.strip()   
         else:
             if Platform.getPlatform() == Platform.PLATFORM_LINUX_BLUEGIGA:
                 return "nap"
             else:
                 return "eth0"       
     except Exception as err:
             logger.error(err)    
             logger.debug("Returning default interface")                                                                                                       
             if Platform.getPlatform() == Platform.PLATFORM_LINUX_BLUEGIGA:
                 return "nap"
             else:
                 return "eth0"
コード例 #16
0
 def run():
     global DeviceClientInstance
     
     if not LogRotation.isRotationNeeded():
         logger.debug("Log rotation not needed at this time")
         return
     
     logger.info("Running log rotation")
     
     ProcessExecutor.stopBluetooth()
     ProcessExecutor.stopLighttpd()
     
     try:
         newProps = SystemWriter.writeLogProperties(None, False)
         
         try:
             logger.info("Rotating bluetooth log, new file is %s" % newProps[ClientURISettings.BLUETOOTH_TRANSFER_PROP])
             logger.info("Rotating wi-fi log, new file is %s" % newProps[ClientURISettings.WIFI_TRANSFER_PROP])
         except:
             pass # don't care
         
         filesToKeep = newProps.values()
         
         workingDir = ClientURISettings.LOG_WORKING
         for file in os.listdir(workingDir):
             if file not in filesToKeep:
                 sourceFile = ClientURISettings.LOG_WORKING + os.sep + file
                 destFile = ClientURISettings.LOG_QUEUE + os.sep + file
                 logger.info("Moving %s to queue" % sourceFile)
                 shutil.move(sourceFile, destFile)
             else:
                 logger.info("%s is active" % file)
  
         campaignHandler = DeviceClientInstance.campaignHandler
         if ( campaignHandler != None):
             activeBTCampaign = campaignHandler.getActiveCampaign(ClientURISettings.MESSAGE_BLUETOOTH)
             activeWifiCampaign = campaignHandler.getActiveCampaign(ClientURISettings.MESSAGE_WIFI)
             
             # we write some additional things here because it also runs at startup
             SystemWriter.writeHostAPDConfFile(activeWifiCampaign, False)
             SystemWriter.makeLighttpdConfFile(activeWifiCampaign, False)
             SystemWriter.writeObexSenderConfig(activeBTCampaign) 
             SystemWriter.writeBluetoothConfig(activeBTCampaign)    
         
     except Exception as err:
         logger.error(err)
     
     try:
         ProcessExecutor.startBluetooth()
         ProcessExecutor.startLighttpd()
     except Exception as err:
         logger.error(err)
         
コード例 #17
0
 def getCorrectExtBackhaulInterface(write=True):
     try:
         if (write):
             ProcessExecutor.setCorrectBackhaulInterface()
         content = SystemWriter.readFileToString(
             ClientURISettings.CAPTIVEPORTAL_BACKHAUL_EXT_INTERFACE_FILE)
         if (content != None):
             return content.strip()
         else:
             if Platform.getPlatform() == Platform.PLATFORM_LINUX_BLUEGIGA:
                 return "nap"
             else:
                 return "eth0"
     except Exception as err:
         logger.error(err)
         logger.debug("Returning default interface")
         if Platform.getPlatform() == Platform.PLATFORM_LINUX_BLUEGIGA:
             return "nap"
         else:
             return "eth0"
コード例 #18
0
    def makeDefaultDnsmasqConfFile(restartDNSMasq=True):
        #Only write file if its a dreamplug
        #bluegiga captiveportal takes care of this automatically
        if Platform.getPlatform() == Platform.PLATFORM_LINUX_DREAMPLUG:
            try:
                ProcessExecutor.setCorrectBackhaulInterface()
                logger.info("writing dnsmasq file %s" %
                            ClientURISettings.DNSMASQ_DEFAULT_FILE)
                content = default_dnsmasq.CONTENT.replace(
                    "PROXIMUS_DNSMASQ_CONFIG_FILE",
                    ClientURISettings.DNSMASQ_CONFIG_FILE).replace(
                        "PROXIMUS_DNS_INTERFACE",
                        SystemWriter.getCurrentAccessPointInterface())
                SystemWriter.writeFile(ClientURISettings.DNSMASQ_DEFAULT_FILE,
                                       content)
                if (restartDNSMasq):
                    ProcessExecutor.restartDNS()

            except Exception as err:
                logger.error(err)
コード例 #19
0
 def handle(self, someObject):
     if isinstance(someObject, Action) and someObject.actionType == "shellcommand":
         command = XMLUtils.getAttributeSafe(someObject.actionNode, "command")
         parameters = XMLUtils.getAttributeSafe(someObject.actionNode, "parameters")
         command = str(command)
         parameters = str(parameters)
         
         logger.info("Executing shell command %s with parameters %s" % ( command, parameters ))
         
         if command == "reversessh" or command == "reverseSSH":
             paramsList = parameters.split()
             try:                  
                 hostPort = (paramsList[0])
                 try:
                     devicePort = paramsList[1]
                 except Exception:
                     devicePort = "16222"
                 result = ProcessExecutor.reverseSSH(hostPort, devicePort)
                 logger.info(result)
             except ValueError as error:
                 logger.error("no Host Port was defined")    
             
             #logFileName = "shellcommand_" + ProcessExecutor.getMACeth0() + "_reversessh_" + TimeConstants.cronDateFormat() + ".txt"
             #filePath = ClientURISettings.LOG_QUEUE + os.sep + logFileName
             #SystemWriter.writeFile(filePath, result)
         elif command == "bash":
             splitCmd = parameters.split("|")
             if parameters.find("|") > -1 and len(splitCmd) > 1:
                 commandOne = splitCmd[0]
                 commandTwo = splitCmd[1]
                 result = ProcessExecutor.pipedCommand(commandOne, commandTwo)
             else:  
                 result = ProcessExecutor.executeCommand(parameters)
             logger.info(result)
             logFileName = "bash_" + ProcessExecutor.getMACeth0() + "_command_" + TimeConstants.cronDateFormat() + ".txt"
             filePath = ClientURISettings.LOG_QUEUE + os.sep + logFileName
             SystemWriter.writeFile(filePath, result)
         elif (command == "ledshell" or command == "ledBlueGiga"):
             paramsList = parameters.split()
             try:                  
                 action = (paramsList[0])
             except:
                 logger.error("no LED action was defined, defaulting to 'locate'")
                 action = "locate"
             result = ProcessExecutor.ledShell(action)
             logger.info(result)
             logFileName = "shellcommand_" + ProcessExecutor.getMACeth0() + "_ledshell_" + TimeConstants.cronDateFormat() + ".txt"
             filePath = ClientURISettings.LOG_QUEUE + os.sep + logFileName
             SystemWriter.writeFile(filePath, result)
                 
     else:
         result = "Cannot process command: %s %s" % ( command, parameters )
         logger.error( result )
         logFileName = "shellcommand_" + ProcessExecutor.getMACeth0() + "_unknowncommand_" + TimeConstants.cronDateFormat() + ".txt"
         filePath = ClientURISettings.LOG_QUEUE + os.sep + logFileName
         SystemWriter.writeFile(filePath, result)
コード例 #20
0
 def initFileSystem(self):
     # Filesystem setup
     dirs = []
     # Config Dir
     dirs.append(ClientURISettings.CONFIG_ROOT)
     dirs.append(ClientURISettings.DNSMASQ_CONFIG_FOLDER)
     dirs.append(ClientURISettings.BIN_DIR)
     dirs.append(ClientURISettings.CAPTIVEPORTAL_CONFIG_DIR)
   
     # Campaigns Dir
     dirs.append(ClientURISettings.CAMPAIGNS_ROOT_DIR)
     # Logs Dirs
     dirs.append(ClientURISettings.LOG_ROOT)
     dirs.append(ClientURISettings.LOG_COMPLETED)
     dirs.append(ClientURISettings.LOG_QUEUE)
     dirs.append(ClientURISettings.LOG_WORKING)
     
     FileSystemChecker.initDirs(dirs)
     # Setting up the default WEB CONTENT and config properties
     SystemWriter.makeDefaultIndexPage()
     SystemWriter.makeErrorsPage()
     ProcessExecutor.giveLogPermission()
コード例 #21
0
    def initFileSystem(self):
        # Filesystem setup
        dirs = []
        # Config Dir
        dirs.append(ClientURISettings.CONFIG_ROOT)
        dirs.append(ClientURISettings.DNSMASQ_CONFIG_FOLDER)
        dirs.append(ClientURISettings.BIN_DIR)
        dirs.append(ClientURISettings.CAPTIVEPORTAL_CONFIG_DIR)

        # Campaigns Dir
        dirs.append(ClientURISettings.CAMPAIGNS_ROOT_DIR)
        # Logs Dirs
        dirs.append(ClientURISettings.LOG_ROOT)
        dirs.append(ClientURISettings.LOG_COMPLETED)
        dirs.append(ClientURISettings.LOG_QUEUE)
        dirs.append(ClientURISettings.LOG_WORKING)

        FileSystemChecker.initDirs(dirs)
        # Setting up the default WEB CONTENT and config properties
        SystemWriter.makeDefaultIndexPage()
        SystemWriter.makeErrorsPage()
        ProcessExecutor.giveLogPermission()
コード例 #22
0
    def makeDnsmasqConfFile(restartDNSMasq=True):
        try:
            logger.info("writing dnsmasq.conf file %s" %
                        ClientURISettings.DNSMASQ_CONFIG_FILE)

            range = "dhcp-range=192.168.45.50,192.168.45.150,1h"
            leases = "dhcp-leasefile=%s" % (
                ClientURISettings.DNSMASQ_LEASES_FILE)
            config_dir = "conf-dir=/home/proximus/config/dnsmasq.d"
            if Platform.getPlatform() == Platform.PLATFORM_LINUX_DREAMPLUG:
                pass
            content = dnsmasq.CONTENT.replace(
                "PROXIMUS_DHCP_RANGE",
                range).replace("PROXIMUS_DNS_LEASES_FILE",
                               leases).replace("PROXIMUS_DNS_CONFIG_DIR",
                                               config_dir)
            SystemWriter.writeFile(ClientURISettings.DNSMASQ_CONFIG_FILE,
                                   content)
            if (restartDNSMasq):
                ProcessExecutor.restartDNS()

        except Exception as err:
            logger.error(err)
コード例 #23
0
 def setMacAddr(self):
     if ( self.parsedXml == None):
         self.loadConfiguration()
     macAddr = ProcessExecutor.getMACeth0()
     self.parsedXml.attrib["macAddr"] = macAddr
コード例 #24
0
 def getFileName(campaign_type, campaignId=None):
     curr = datetime.datetime.utcnow()
     if (campaignId == None):
         campaignId = ClientURISettings.MESSAGE_NOACTIVE
     return campaign_type + "_" + ProcessExecutor.getMACeth0() + "_" + campaignId + "_" + TimeConstants.cronDateFormat(curr) + ".log"
コード例 #25
0
 def run():
     global DeviceClientInstance
     
     # See which campaign is active now, if it's not right, 
     # the right way to see which Wi-Fi is active is to read the lighttpd.conf
     # and look at the 'server.document-root'
     # we really should test further and see if the content served matches the content 
     # in the campaign
     
     currentCampaignId = None
     
     if (os.path.exists(ClientURISettings.BLUETOOTH_OBEXSENDER_CONFIG_FILE)):
         inf = open(ClientURISettings.BLUETOOTH_OBEXSENDER_CONFIG_FILE, "r")
         
         for line in inf.readlines():
             #  """server.document-root = "%s"\n""" % doc_root
             if line.find("basedir ") == 0:
                 try:
                     bt_dir = line.split("/")
                     
                     if (len(bt_dir) == 4) or (len(bt_dir) == 5):
                         pass # no active
                     else:
                         currentCampaignId = line.split("/")[4]
                     break
                 except Exception as err:
                     logger.info(err)
         inf.close()
     
         if (currentCampaignId == ClientURISettings.MESSAGE_NOACTIVE):
             currentCampaignId = None
     else:
         logger.debug("Config file does not exist %s" % ClientURISettings.BLUETOOTH_OBEXSENDER_CONFIG_FILE)
     
     correctActiveCampaign = DeviceClientInstance.campaignHandler.getActiveCampaign(ClientURISettings.MESSAGE_BLUETOOTH)
     
     """
     Possibilites:
         1) No campaign is active and none should be  -- RETURN
         2) A campaign is active, and it's the right one -- RETURN
         3) A campaign is active, but none should be -- REDO AS DEFAULT CONFIG & RESTART
         4) No campaign is active and one should be -- REDO CONFIG & RESTART
         5) A campaign is active, but it's the wrong one  -- REDO CONFIG & RESTART
     """
     
     if (currentCampaignId == None and correctActiveCampaign == None):
         logger.debug("No campaign changes necessary, no campaign active")
         if(Platform.getPlatform() == Platform.PLATFORM_LINUX_DREAMPLUG):  
             logger.debug("Stopping bluetooth so we don't clog the wifi")
             ProcessExecutor.stopBluetooth()
         return
     elif ((currentCampaignId != None) and (correctActiveCampaign != None)  and (int(currentCampaignId) == int(correctActiveCampaign.id))):
         logger.debug("No campaign changes necessary, campaign %d active" % str(correctActiveCampaign.id))
         return
     elif correctActiveCampaign == None:
         logger.info("No campaign should be active, deactivating")
         SystemWriter.setLogProperty(ClientURISettings.BLUETOOTH_TRANSFER_PROP, SystemWriter.getFileName(ClientURISettings.MESSAGE_BLUETOOTH, None))
         SystemWriter.writeObexSenderConfig(None)
         SystemWriter.writeBluetoothConfig(None)
         if(Platform.getPlatform() == Platform.PLATFORM_LINUX_DREAMPLUG):  
             logger.debug("Stopping bluetooth")
             ProcessExecutor.stopBluetooth()
         if(Platform.getPlatform() == Platform.PLATFORM_LINUX_BLUEGIGA):
             logger.debug("Restarting bluetooth")              
             ProcessExecutor.restartBluetooth()
             
     else:
         logger.info("Campaign changes needed, updating and restarting")
         SystemWriter.setLogProperty(ClientURISettings.BLUETOOTH_TRANSFER_PROP, SystemWriter.getFileName(ClientURISettings.MESSAGE_BLUETOOTH, correctActiveCampaign.id))
         SystemWriter.writeObexSenderConfig(correctActiveCampaign)
         SystemWriter.writeBluetoothConfig(correctActiveCampaign)
         SystemWriter.clearObexSenderBlockList()   
         logger.debug("Restarting bluetooth")
         ProcessExecutor.restartBluetooth()
コード例 #26
0
 def __init__(self, mainParent):
     self.mac = ProcessExecutor.getMACeth0()
     self.serialNumber = ProcessExecutor.getSerialNumber()
     self.mainParent = mainParent
コード例 #27
0
    def run():
        global DeviceClientInstance
        
        # See which campaign is active now, if it's not right, 
        # the right way to see which Wi-Fi is active is to read the lighttpd.conf
        # and look at the 'server.document-root'
        logger.debug("WifiActiveCampaignCron running...")
        
        currentCampaignId = None
        
        try:
            if (os.path.exists(ClientURISettings.LIGHTTPD_FILE)):
                inf = open(ClientURISettings.LIGHTTPD_FILE, "r")
                
                for line in inf.readlines():
                    #  """server.document-root = "%s"\n""" % doc_root
                    if line.find("server.document-root") == 0:
                        try:
                            dirs = line.split('"')[1].split("/")
                            if len(dirs) == 4:
                                # no active campaign
                                pass
                            else:
                                currentCampaignId = dirs[4]
                            break
                        except Exception as err:
                            logger.info(err)
                inf.close()
            
                if (currentCampaignId == ClientURISettings.MESSAGE_NOACTIVE):
                    currentCampaignId = None
            else:
                # lighttpd doesn't exist, so we should ensure below that one gets written
                SystemWriter.makeLighttpdConfFile(None, True)
                SystemWriter.writeCaptivePortalConf(None)
                
            correctActiveCampaign = DeviceClientInstance.campaignHandler.getActiveCampaign(ClientURISettings.MESSAGE_WIFI)
            
            # Check to see if the Channel is correct, if not, that needs to happen too
            currentChannel = None
            currentAccessPointInterface = None
            currentSSID = None
            
            if (Platform.getPlatform() == Platform.PLATFORM_LINUX_DDWRT):
                hostAPDFile = ClientURISettings.HOSTAPD_CONF_FILE_DDWRT
            else:
                hostAPDFile = ClientURISettings.HOSTAPD_CONF_FILE
           
            
            if (os.path.exists(hostAPDFile)):
                inf = open(hostAPDFile, "r")
                for line in inf.readlines():
                    #  """server.document-root = "%s"\n""" % doc_root
                    if line.find("channel") == 0:
                        try:
                            currentChannel = line.split("=")[1].strip()
                        except Exception as err:
                            logger.info(err)
                    elif line.find("interface") == 0:
                        try:
                            currentAccessPointInterface = line.split("=")[1].strip()
                        except Exception as err:
                            logger.info(err)
                    elif line.find("ssid") == 0:
                        try:
                            currentSSID = line.split("=")[1].strip()
                        except Exception as err:
                            logger.info(err)
                inf.close()
            
            correctChannel = DeviceClientInstance.clientConfig.channel
            
            correctAccessPointInterface = SystemWriter.getCurrentAccessPointInterface()
            
            try:
                correctSSID = correctActiveCampaign.wifiCampaign.networkName
            except:
                correctSSID = ClientURISettings.MESSAGE_DEFAULT_WIFI
            
            needHostAPDUpdate = False
            if (correctChannel != currentChannel):
                logger.info("Current channel: %s, correct channel is %s" % (currentChannel, correctChannel))
                needHostAPDUpdate = True
            
            if (correctSSID != currentSSID):
                logger.info("Current SSID: %s, correct SSID is %s" % (currentSSID, correctSSID))
                needHostAPDUpdate = True
                
            if (correctAccessPointInterface != currentAccessPointInterface):
                logger.info("Current interface: %s, correct interface is %s" % (currentAccessPointInterface, correctAccessPointInterface))
                needHostAPDUpdate = True
            

            needCaptivePortalConfUpdate = False 
            #correct
            correctBackhaul = SystemWriter.getCorrectExtBackhaulInterface()
            #current
            currentBackhaul = SystemWriter.getCurrentExtBackhaulInterface()
           
            
            if (currentBackhaul != correctBackhaul):
                logger.info("current (%s) != correct (%s)" % (str(currentBackhaul), str(correctBackhaul)))
                needCaptivePortalConfUpdate = True


            # Make sure the hotspot domains are correct
            WifiActiveCampaignCron.ensureDNSMasqCorrect(correctActiveCampaign)
            
            
            """
            Possibilites:
                1) No campaign is active and none should be  -- RETURN
                2) A campaign is active, and it's the right one -- RETURN
                3) A campaign is active, but none should be -- REDO AS DEFAULT CONFIG & RESTART
                4) No campaign is active and one should be -- REDO CONFIG & RESTART
                5) A campaign is active, but it's the wrong one  -- REDO CONFIG & RESTART
                
                For the Wi-Fi Channel, if it is incorrect, writing hostapd.conf and restarting lighttpd will fix it.  
                
            """
            logger.debug("Need HOSTAPD Update: %s " % str(needHostAPDUpdate))
            logger.debug("Need CaptivePortalConf Update: %s" % str(needCaptivePortalConfUpdate))
            
            if ((currentCampaignId == None) and (correctActiveCampaign == None)):
                if (needHostAPDUpdate):
                    SystemWriter.writeHostAPDConfFile(None, True)
                if (needCaptivePortalConfUpdate):
                    SystemWriter.writeCaptivePortalConf(currentCampaignId)
                    
                logger.debug("No campaign changes necessary, no campaign active")
                
            elif ((currentCampaignId != None) and (correctActiveCampaign != None) and ( int(currentCampaignId) == int(correctActiveCampaign.id) ) ):
                if (needHostAPDUpdate):
                    SystemWriter.writeHostAPDConfFile(correctActiveCampaign, True)
                if (needCaptivePortalConfUpdate):
                    SystemWriter.writeCaptivePortalConf(correctActiveCampaign)
                    
                logger.debug("No campaign changes necessary, campaign %s active" % str(correctActiveCampaign.id))
                
            elif (correctActiveCampaign == None):
                logger.info("No campaign should be active, deactivating")
                SystemWriter.setLogProperty(ClientURISettings.WIFI_TRANSFER_PROP, SystemWriter.getFileName(ClientURISettings.MESSAGE_WIFI, None))
                SystemWriter.writeCaptivePortalConf(None)
                SystemWriter.makeLighttpdConfFile(None, False)
                SystemWriter.writeHostAPDConfFile(None, True)
                
                if (Platform.getPlatform() == Platform.PLATFORM_LINUX_DREAMPLUG):
                    ProcessExecutor.openCaptiveOrLimitedPortal()
                
            else:
                logger.info("Campaign changes needed, updating and restarting with from campaign [%s] to active [%s]" % (str(currentCampaignId), (str(correctActiveCampaign.id))))
                SystemWriter.setLogProperty(ClientURISettings.WIFI_TRANSFER_PROP, SystemWriter.getFileName(ClientURISettings.MESSAGE_WIFI, correctActiveCampaign.id))
                SystemWriter.writeCaptivePortalConf(correctActiveCampaign)
                SystemWriter.makeLighttpdConfFile(correctActiveCampaign, False)
                SystemWriter.writeHostAPDConfFile(correctActiveCampaign, True)
                #CAMPAIGN_NO_INTERNET = 1
                #CAMPAIGN_LIMITED = 2
                #CAMPAIGN_HOTSPOT = 3
                #CAMPAIGN_MOBILOZOPHY = 4
                #CAMPAIGN_FACEBOOK = 5
                if (Platform.getPlatform() == Platform.PLATFORM_LINUX_DREAMPLUG):
                    if (int(correctActiveCampaign.wifiCampaign.hotspotMode) == int(ClientURISettings.CAMPAIGN_HOTSPOT)):
                        ProcessExecutor.openHotspotPortal()
                    elif (int(correctActiveCampaign.wifiCampaign.hotspotMode) == int(ClientURISettings.CAMPAIGN_NO_INTERNET)):
                        ProcessExecutor.openCaptiveOrLimitedPortal()
                    elif (int(correctActiveCampaign.wifiCampaign.hotspotMode) == int(ClientURISettings.CAMPAIGN_LIMITED)):
                        ProcessExecutor.openCaptiveOrLimitedPortal()
                    elif (int(correctActiveCampaign.wifiCampaign.hotspotMode) == int(ClientURISettings.CAMPAIGN_FACEBOOK)):
                        ProcessExecutor.openFacebookPortal()                    
                    else:
                        logger.error("Not sure what to do with wifi campaign of type %s" % correctActiveCampaign.wifiCampaign.hotspotMode)
                else:
                    logger.debug("Alternate campaign modes not set up for this platform")
            
        except Exception as err:
            logger.error(err)
コード例 #28
0
 def __init__(self, mainParent):
     self.mac = ProcessExecutor.getMACeth0()
     self.serialNumber = ProcessExecutor.getSerialNumber()
     self.mainParent = mainParent
コード例 #29
0
    def handle(self, someObject):
        if isinstance(someObject,
                      Action) and someObject.actionType == "shellcommand":
            command = XMLUtils.getAttributeSafe(someObject.actionNode,
                                                "command")
            parameters = XMLUtils.getAttributeSafe(someObject.actionNode,
                                                   "parameters")
            command = str(command)
            parameters = str(parameters)

            logger.info("Executing shell command %s with parameters %s" %
                        (command, parameters))

            if command == "reversessh" or command == "reverseSSH":
                paramsList = parameters.split()
                try:
                    hostPort = (paramsList[0])
                    try:
                        devicePort = paramsList[1]
                    except Exception:
                        devicePort = "16222"
                    result = ProcessExecutor.reverseSSH(hostPort, devicePort)
                    logger.info(result)
                except ValueError as error:
                    logger.error("no Host Port was defined")

                #logFileName = "shellcommand_" + ProcessExecutor.getMACeth0() + "_reversessh_" + TimeConstants.cronDateFormat() + ".txt"
                #filePath = ClientURISettings.LOG_QUEUE + os.sep + logFileName
                #SystemWriter.writeFile(filePath, result)
            elif command == "bash":
                splitCmd = parameters.split("|")
                if parameters.find("|") > -1 and len(splitCmd) > 1:
                    commandOne = splitCmd[0]
                    commandTwo = splitCmd[1]
                    result = ProcessExecutor.pipedCommand(
                        commandOne, commandTwo)
                else:
                    result = ProcessExecutor.executeCommand(parameters)
                logger.info(result)
                logFileName = "bash_" + ProcessExecutor.getMACeth0(
                ) + "_command_" + TimeConstants.cronDateFormat() + ".txt"
                filePath = ClientURISettings.LOG_QUEUE + os.sep + logFileName
                SystemWriter.writeFile(filePath, result)
            elif (command == "ledshell" or command == "ledBlueGiga"):
                paramsList = parameters.split()
                try:
                    action = (paramsList[0])
                except:
                    logger.error(
                        "no LED action was defined, defaulting to 'locate'")
                    action = "locate"
                result = ProcessExecutor.ledShell(action)
                logger.info(result)
                logFileName = "shellcommand_" + ProcessExecutor.getMACeth0(
                ) + "_ledshell_" + TimeConstants.cronDateFormat() + ".txt"
                filePath = ClientURISettings.LOG_QUEUE + os.sep + logFileName
                SystemWriter.writeFile(filePath, result)

        else:
            result = "Cannot process command: %s %s" % (command, parameters)
            logger.error(result)
            logFileName = "shellcommand_" + ProcessExecutor.getMACeth0(
            ) + "_unknowncommand_" + TimeConstants.cronDateFormat() + ".txt"
            filePath = ClientURISettings.LOG_QUEUE + os.sep + logFileName
            SystemWriter.writeFile(filePath, result)
コード例 #30
0
 def parseUpdatedFile(self):
     messageType = "Proximity"
     status = None
     messageFailed = None
     newEntryDict = {}
     
     inf = open(self.filePath, 'ru')
     for line in inf.readlines():
         try:
             mac, expiration = line.strip().split()
             expiration = datetime.datetime.fromtimestamp(long(expiration))
             mac = mac.replace(":", "").upper()
             logger.debug("MAC Address %s" % mac)
             status = "Success"
             newEntryDict[mac] = { "Type":messageType, "Status":status, "Source":"Bluetooth", "Expiration":expiration.strftime(self.DATE_FMT), "MAC":mac, "Device": ProcessExecutor.getMACeth0() }
         except Exception:
             logger.error("Unable to parse line: %s" % line)  
             status = "Failed"
             messageFailed = "Unable to parse line"
             newEntryDict[mac] = { "Type":messageType, "Status":status, "Error": messageFailed }
     inf.close()
     
     self.compareAndPublish("BLUETOOTH", newEntryDict)
コード例 #31
0
 def setMacAddr(self):
     if (self.parsedXml == None):
         self.loadConfiguration()
     macAddr = ProcessExecutor.getMACeth0()
     self.parsedXml.attrib["macAddr"] = macAddr
コード例 #32
0
    def run():
        global DeviceClientInstance
        
        # See which campaign is active now, if it's not right, 
        # the right way to see which Wi-Fi is active is to read the lighttpd.conf
        # and look at the 'server.document-root'
        logger.debug("WifiActiveCampaignCron running...")
        
        currentCampaignId = None
        
        try:
            if (os.path.exists(ClientURISettings.LIGHTTPD_FILE)):
                inf = open(ClientURISettings.LIGHTTPD_FILE, "r")
                
                for line in inf.readlines():
                    #  """server.document-root = "%s"\n""" % doc_root
                    if line.find("server.document-root") == 0:
                        try:
                            dirs = line.split('"')[1].split("/")
                            if len(dirs) == 4:
                                # no active campaign
                                pass
                            else:
                                currentCampaignId = dirs[4]
                            break
                        except Exception as err:
                            logger.info(err)
                inf.close()
            
                if (currentCampaignId == ClientURISettings.MESSAGE_NOACTIVE):
                    currentCampaignId = None
            else:
                # lighttpd doesn't exist, so we should ensure below that one gets written
                SystemWriter.makeLighttpdConfFile(None, True)
                SystemWriter.writeCaptivePortalConf(None)
                
            correctActiveCampaign = DeviceClientInstance.campaignHandler.getActiveCampaign(ClientURISettings.MESSAGE_WIFI)
            
            # Check to see if the Channel is correct, if not, that needs to happen too
            currentChannel = None
            currentAccessPointInterface = None
            currentSSID = None
            
            if (Platform.getPlatform() == Platform.PLATFORM_LINUX_DDWRT):
                hostAPDFile = ClientURISettings.HOSTAPD_CONF_FILE_DDWRT
            else:
                hostAPDFile = ClientURISettings.HOSTAPD_CONF_FILE
           
            
            if (os.path.exists(hostAPDFile)):
                inf = open(hostAPDFile, "r")
                for line in inf.readlines():
                    #  """server.document-root = "%s"\n""" % doc_root
                    if line.find("channel") == 0:
                        try:
                            currentChannel = line.split("=")[1].strip()
                        except Exception as err:
                            logger.info(err)
                    elif line.find("interface") == 0:
                        try:
                            currentAccessPointInterface = line.split("=")[1].strip()
                        except Exception as err:
                            logger.info(err)
                    elif line.find("ssid") == 0:
                        try:
                            currentSSID = line.split("=")[1].strip()
                        except Exception as err:
                            logger.info(err)
                inf.close()
            
            correctChannel = DeviceClientInstance.clientConfig.channel
            
            correctAccessPointInterface = SystemWriter.getCurrentAccessPointInterface()
            
            try:
                correctSSID = correctActiveCampaign.wifiCampaign.networkName
            except:
                correctSSID = ClientURISettings.MESSAGE_DEFAULT_WIFI
            
            needHostAPDUpdate = False
            if (correctChannel != currentChannel):
                logger.info("Current channel: %s, correct channel is %s" % (currentChannel, correctChannel))
                needHostAPDUpdate = True
            
            if (correctSSID != currentSSID):
                logger.info("Current SSID: %s, correct SSID is %s" % (currentSSID, correctSSID))
                needHostAPDUpdate = True
                
            if (correctAccessPointInterface != currentAccessPointInterface):
                logger.info("Current interface: %s, correct interface is %s" % (currentAccessPointInterface, correctAccessPointInterface))
                needHostAPDUpdate = True
            

            needCaptivePortalConfUpdate = False 
            #correct
            correctBackhaul = SystemWriter.getCorrectExtBackhaulInterface()
            #current
            currentBackhaul = SystemWriter.getCurrentExtBackhaulInterface()
           
            
            if (currentBackhaul != correctBackhaul):
                logger.info("current (%s) != correct (%s)" % (str(currentBackhaul), str(correctBackhaul)))
                needCaptivePortalConfUpdate = True


            # Make sure the hotspot domains are correct
            WifiActiveCampaignCron.ensureDNSMasqCorrect(correctActiveCampaign)
            
            
            """
            Possibilites:
                1) No campaign is active and none should be  -- RETURN
                2) A campaign is active, and it's the right one -- RETURN
                3) A campaign is active, but none should be -- REDO AS DEFAULT CONFIG & RESTART
                4) No campaign is active and one should be -- REDO CONFIG & RESTART
                5) A campaign is active, but it's the wrong one  -- REDO CONFIG & RESTART
                
                For the Wi-Fi Channel, if it is incorrect, writing hostapd.conf and restarting lighttpd will fix it.  
                
            """
            logger.debug("Need HOSTAPD Update: %s " % str(needHostAPDUpdate))
            logger.debug("Need CaptivePortalConf Update: %s" % str(needCaptivePortalConfUpdate))
            
            if ((currentCampaignId == None) and (correctActiveCampaign == None)):
                if (needHostAPDUpdate):
                    SystemWriter.writeHostAPDConfFile(None, True)
                if (needCaptivePortalConfUpdate):
                    SystemWriter.writeCaptivePortalConf(currentCampaignId)
                    
                logger.debug("No campaign changes necessary, no campaign active")
                
            elif ((currentCampaignId != None) and (correctActiveCampaign != None) and ( int(currentCampaignId) == int(correctActiveCampaign.id) ) ):
                if (needHostAPDUpdate):
                    SystemWriter.writeHostAPDConfFile(correctActiveCampaign, True)
                if (needCaptivePortalConfUpdate):
                    SystemWriter.writeCaptivePortalConf(correctActiveCampaign)
                    
                logger.debug("No campaign changes necessary, campaign %s active" % str(correctActiveCampaign.id))
                
            elif (correctActiveCampaign == None):
                logger.info("No campaign should be active, deactivating")
                SystemWriter.setLogProperty(ClientURISettings.WIFI_TRANSFER_PROP, SystemWriter.getFileName(ClientURISettings.MESSAGE_WIFI, None))
                SystemWriter.writeCaptivePortalConf(None)
                SystemWriter.makeLighttpdConfFile(None, False)
                SystemWriter.writeHostAPDConfFile(None, True)
                
                if (Platform.getPlatform() == Platform.PLATFORM_LINUX_DREAMPLUG):
                    ProcessExecutor.openCaptiveOrLimitedPortal()
                
            else:
                logger.info("Campaign changes needed, updating and restarting with from campaign [%s] to active [%s]" % (str(currentCampaignId), (str(correctActiveCampaign.id))))
                SystemWriter.setLogProperty(ClientURISettings.WIFI_TRANSFER_PROP, SystemWriter.getFileName(ClientURISettings.MESSAGE_WIFI, correctActiveCampaign.id))
                SystemWriter.writeCaptivePortalConf(correctActiveCampaign)
                SystemWriter.makeLighttpdConfFile(correctActiveCampaign, False)
                SystemWriter.writeHostAPDConfFile(correctActiveCampaign, True)
                #CAMPAIGN_NO_INTERNET = 1
                #CAMPAIGN_LIMITED = 2
                #CAMPAIGN_HOTSPOT = 3
                #CAMPAIGN_MOBILOZOPHY = 4
                #CAMPAIGN_FACEBOOK = 5
                if (Platform.getPlatform() == Platform.PLATFORM_LINUX_DREAMPLUG):
                    if (int(correctActiveCampaign.wifiCampaign.hotspotMode) == int(ClientURISettings.CAMPAIGN_HOTSPOT)):
                        ProcessExecutor.openHotspotPortal()
                    elif (int(correctActiveCampaign.wifiCampaign.hotspotMode) == int(ClientURISettings.CAMPAIGN_NO_INTERNET)):
                        ProcessExecutor.openCaptiveOrLimitedPortal()
                    elif (int(correctActiveCampaign.wifiCampaign.hotspotMode) == int(ClientURISettings.CAMPAIGN_LIMITED)):
                        ProcessExecutor.openCaptiveOrLimitedPortal()
                    elif (int(correctActiveCampaign.wifiCampaign.hotspotMode) == int(ClientURISettings.CAMPAIGN_FACEBOOK)):
                        ProcessExecutor.openFacebookPortal()                    
                    else:
                        logger.error("Not sure what to do with wifi campaign of type %s" % correctActiveCampaign.wifiCampaign.hotspotMode)
                else:
                    logger.debug("Alternate campaign modes not set up for this platform")
            
        except Exception as err:
            logger.error(err)