Exemplo n.º 1
0
    def get_sms_stats(self):

        respdata = '{ "processed_sms": "N/A", "unprocessed_sms": "N/A" }'
        try:
            if wisglobals.sslenabled is not None and 'true' in wisglobals.sslenabled.lower():
                request = urllib.request.Request('https://' +
                                                 wisglobals.wisipaddress +
                                                 ':' +
                                                 wisglobals.wisport +
                                                 "/api/get_sms_stats")
            else:
                request = urllib.request.Request('http://' +
                                                wisglobals.wisipaddress +
                                                ':' +
                                                wisglobals.wisport +
                                                 "/api/get_sms_stats")
            request.add_header("Content-Type",
                           "application/json;charset=utf-8")

            data = GlobalHelper.encodeAES('{"get": "sms"}')
            f = urllib.request.urlopen(request, data, timeout=30)
            resp = f.read().decode('utf-8')
            respdata = GlobalHelper.decodeAES(resp)
        except urllib.error.URLError as e:
            smsgwglobals.wislogger.debug(e)
            smsgwglobals.wislogger.debug("AJAX: get_sms_stats connect error")
        except socket.timeout as e:
            smsgwglobals.wislogger.debug(e)
            smsgwglobals.wislogger.debug("AJAX: get_sms_stats socket connection timeout")
        finally:
            return respdata
Exemplo n.º 2
0
        def getUrl(url):
            try:
                data = GlobalHelper.encodeAES('{"get": "peers"}')
                request = \
                    urllib.request.Request(url +
                                           "/smsgateway/api/requestrouting")
                request.add_header("Content-Type",
                                   "application/json;charset=utf-8")
                f = urllib.request.urlopen(request, data, timeout=5)
                if f.getcode() != 200:
                    smsgwglobals.wislogger.debug("Get peers NOTOK," +
                                                 " Error Code: ",
                                                 f.getcode())
                    return

                smsgwglobals.wislogger.debug("Get peers OK")
                rawbody = f.read().decode('utf-8')
                plaintext = GlobalHelper.decodeAES(rawbody)
                routelist = json.loads(plaintext)
                smsgwglobals.wislogger.debug(routelist)

                wisglobals.rdb.merge_routing(routelist)

            except urllib.error.URLError as e:
                smsgwglobals.wislogger.debug(e)
                smsgwglobals.wislogger.debug("Get peers NOTOK")
            except error.DatabaseError as e:
                smsgwglobals.wislogger.debug(e.message)
            except socket.timeout as e:
                smsgwglobals.wislogger.debug(e)
                smsgwglobals.wislogger.debug("HELPER: requestrouting socket connection timeout")
Exemplo n.º 3
0
        def getUrl(url):
            try:
                data = GlobalHelper.encodeAES('{"get": "peers"}')
                request = \
                    urllib.request.Request(url +
                                           "/smsgateway/api/requestrouting")
                request.add_header("Content-Type",
                                   "application/json;charset=utf-8")
                f = urllib.request.urlopen(request, data, timeout=5)
                if f.getcode() != 200:
                    smsgwglobals.wislogger.debug(
                        "Get peers NOTOK," + " Error Code: ", f.getcode())
                    return

                smsgwglobals.wislogger.debug("Get peers OK")
                rawbody = f.read().decode('utf-8')
                plaintext = GlobalHelper.decodeAES(rawbody)
                routelist = json.loads(plaintext)
                smsgwglobals.wislogger.debug(routelist)

                wisglobals.rdb.merge_routing(routelist)

            except urllib.error.URLError as e:
                smsgwglobals.wislogger.debug(e)
                smsgwglobals.wislogger.debug("Get peers NOTOK")
            except error.DatabaseError as e:
                smsgwglobals.wislogger.debug(e.message)
            except socket.timeout as e:
                smsgwglobals.wislogger.debug(e)
                smsgwglobals.wislogger.debug(
                    "HELPER: requestrouting socket connection timeout")
Exemplo n.º 4
0
    def received_message(self, msg):
        plaintext = GlobalHelper.decodeAES(str(msg))

        smsgwglobals.pidlogger.debug(pidglobals.pidid + ": " +
                                     "Message received: " +
                                     str(plaintext))
        data = json.loads(plaintext)

        if data['action'] == "sendsms":
            tosend = Modem.sendsms(data)

            plaintext = json.dumps(tosend)
            smsgwglobals.pidlogger.debug(pidglobals.pidid + ": " +
                                         "Message delivery status: " +
                                         str(plaintext))
            message = GlobalHelper.encodeAES(plaintext)
            # reply sms-status to PIS
            self.send(message)

            # Exit PID on ERROR on sending sms
            if "ERROR" in tosend['status']:
                closingreason = "Modem ERROR while sending SMS!"
                pidglobals.closingcode = 4000
                self.close(code=4000, reason=closingreason)

            # calculate difference time to last primary PIS check
            diff = datetime.now() - self.lastprimcheck

            # only if 5 mins are passed (= 300 sec)
            if diff.seconds > 300:
                if self.check_primpid() == "reconnect":
                    # close Websocket to reconnect!
                    # fixes #25 wait a bit to let pis fetch the smsstatus first
                    time.sleep(1)

                    closingreason = "Primary PID is back! Reinit now!"
                    pidglobals.closingcode = 4001
                    self.close(code=4001, reason=closingreason)

        if data['action'] == "register":
            if data['status'] == "registered":
                # Start Heartbeat to connected PID
                hb = Heartbeat(data['modemlist'], self)
                hb.daemon = True
                hb.start()

        if data['action'] == "heartbeat":
            # connection to PIS is OK but
            # Response from WIS is NOT OK
            if data['status'] != 200:
                # close Connection to PIS and retry initialisation
                self.close()
Exemplo n.º 5
0
    def received_message(self, msg):
        plaintext = GlobalHelper.decodeAES(str(msg))

        smsgwglobals.pidlogger.debug(pidglobals.pidid + ": " +
                                     "Message received: " + str(plaintext))
        data = json.loads(plaintext)

        if data['action'] == "sendsms":
            tosend = Modem.sendsms(data)

            plaintext = json.dumps(tosend)
            smsgwglobals.pidlogger.debug(pidglobals.pidid + ": " +
                                         "Message delivery status: " +
                                         str(plaintext))
            message = GlobalHelper.encodeAES(plaintext)
            # reply sms-status to PIS
            self.send(message)

            # Exit PID on ERROR on sending sms
            if "ERROR" in tosend['status']:
                closingreason = "Modem ERROR while sending SMS!"
                pidglobals.closingcode = 4000
                self.close(code=4000, reason=closingreason)

            # calculate difference time to last primary PIS check
            diff = datetime.now() - self.lastprimcheck

            # only if 5 mins are passed (= 300 sec)
            if diff.seconds > 300:
                if self.check_primpid() == "reconnect":
                    # close Websocket to reconnect!
                    # fixes #25 wait a bit to let pis fetch the smsstatus first
                    time.sleep(1)

                    closingreason = "Primary PID is back! Reinit now!"
                    pidglobals.closingcode = 4001
                    self.close(code=4001, reason=closingreason)

        if data['action'] == "register":
            if data['status'] == "registered":
                # Start Heartbeat to connected PID
                hb = Heartbeat(data['modemlist'], self)
                hb.daemon = True
                hb.start()

        if data['action'] == "heartbeat":
            # connection to PIS is OK but
            # Response from WIS is NOT OK
            if data['status'] != 200:
                # close Connection to PIS and retry initialisation
                self.close()
Exemplo n.º 6
0
    def opened(self):
        # as we are connected set the time when it was done
        self.lastprimcheck = datetime.now()

        smsgwglobals.pidlogger.info(pidglobals.pidid + ": " +
                                    "Opened connection to " +
                                    str(self.bind_addr))
        data = {}
        data['action'] = 'register'
        data['pidid'] = pidglobals.pidid
        data['modemlist'] = pidglobals.modemlist
        data['pidprotocol'] = pidglobals.pidprotocol

        # if modemlist is not [] register at PIS
        if data['modemlist']:
            asjson = json.dumps(data)
            smsgwglobals.pidlogger.debug(pidglobals.pidid + ": " +
                                         "Registration data: " +
                                         asjson)
            tosend = GlobalHelper.encodeAES(asjson)
            self.send(tosend)
        else:
            # close connection to PIS
            closingreason = "Unable to connect to modem(s)"
            pidglobals.closingcode = 4000
            self.close(code=4000, reason=closingreason)
Exemplo n.º 7
0
    def opened(self):
        # as we are connected set the time when it was done
        self.lastprimcheck = datetime.now()

        smsgwglobals.pidlogger.info(pidglobals.pidid + ": " +
                                    "Opened connection to " +
                                    str(self.bind_addr))
        data = {}
        data['action'] = 'register'
        data['pidid'] = pidglobals.pidid
        data['modemlist'] = pidglobals.modemlist
        data['pidprotocol'] = pidglobals.pidprotocol

        # if modemlist is not [] register at PIS
        if data['modemlist']:
            asjson = json.dumps(data)
            smsgwglobals.pidlogger.debug(pidglobals.pidid + ": " +
                                         "Registration data: " +
                                         asjson)
            tosend = GlobalHelper.encodeAES(asjson)
            self.send(tosend)
        else:
            # close connection to PIS
            closingreason = "Unable to connect to modem(s)"
            pidglobals.closingcode = 4000
            self.close(code=4000, reason=closingreason)
Exemplo n.º 8
0
    def sendtopid(address, data):
        asjson = json.dumps(data)
        tosend = GlobalHelper.encodeAES(asjson)

        client = PID.getclienthandler(address)
        client.send(tosend)
        smsgwglobals.pislogger.debug("/ws: Sending data to " + str(address) +
                                     " - " + str(data))
Exemplo n.º 9
0
    def send(self, smstrans, route):
        # encode to json
        jdata = json.dumps(smstrans.smsdict)
        data = GlobalHelper.encodeAES(jdata)

        request = \
            urllib.request.Request(
                route[0]["pisurl"] +
                "/sendsms")

        request.add_header("Content-Type",
                           "application/json;charset=utf-8")

        try:
            smsgwglobals.wislogger.debug("WATCHDOG: " +
                                         "Sending VIA " +
                                         smstrans.smsdict["modemid"] +
                                         route[0]["pisurl"] +
                                         "/sendsms")
            f = urllib.request.urlopen(request, data, timeout=wisglobals.pissendtimeout)
            smsgwglobals.wislogger.debug("WATCHDOG: SMS send to PIS returncode:" + str(f.getcode()))
            # if all is OK set the sms status to SENT
            smstrans.smsdict["statustime"] = datetime.utcnow()
            if f.getcode() == 200:
                if smstrans.smsdict["status"] == 0:
                    smstrans.smsdict["status"] = 4
                    smsgwglobals.wislogger.debug("WATCHDOD: SEND direct:" + str(smstrans.smsdict))
                else:
                    smstrans.smsdict["status"] = 5
                    smsgwglobals.wislogger.debug("WATCHDOD: SEND deligated:" + str(smstrans.smsdict))
                smsgwglobals.wislogger.debug("WATCHDOD: SEND Update DB SUCCESS:" + str(smstrans.smsdict))
                smstrans.updatedb()
            else:
                if smstrans.smsdict["status"] == 0:
                    smstrans.smsdict["status"] = 104
                    smsgwglobals.wislogger.debug("WATCHDOD: SEND direct ERROR:" + str(smstrans.smsdict))
                else:
                    smstrans.smsdict["status"] = 105
                    smsgwglobals.wislogger.debug("WATCHDOD: SEND deligated ERROR:" + str(smstrans.smsdict))
                smsgwglobals.wislogger.debug("WATCHDOD: SEND Update DB ERROR:" + str(smstrans.smsdict))
                smstrans.updatedb()

        except urllib.error.URLError as e:
            if smstrans.smsdict["status"] == 0:
                smstrans.smsdict["status"] = 100
            else:
                smstrans.smsdict["status"] = 105
            smsgwglobals.wislogger.debug("WATCHDOG: SEND EXCEPTION " + str(smstrans.smsdict))
            smstrans.updatedb()
            # set SMS to not send!!!
            smsgwglobals.wislogger.debug(e)
            smsgwglobals.wislogger.debug("WATCHDOG: SEND Get peers NOTOK")
        except socket.timeout as e:
            smstrans.smsdict["status"] = 107
            smstrans.updatedb()
            smsgwglobals.wislogger.debug(e)
            smsgwglobals.wislogger.debug("WATCHDOG: SEND Socket connection timeout")
Exemplo n.º 10
0
    def sendtopid(address, data):
        asjson = json.dumps(data)
        tosend = GlobalHelper.encodeAES(asjson)

        client = PID.getclienthandler(address)
        client.send(tosend)
        smsgwglobals.pislogger.debug("/ws: Sending data to " +
                                     str(address) + " - " +
                                     str(data))
Exemplo n.º 11
0
    def send(self, sms, route):
        # encode to json
        jdata = json.dumps(sms)
        data = GlobalHelper.encodeAES(jdata)

        request = \
            urllib.request.Request(
                route[0]["pisurl"] +
                "/sendsms")

        request.add_header("Content-Type",
                           "application/json;charset=utf-8")

        smstrans = smstransfer.Smstransfer(**sms)

        try:
            smsgwglobals.wislogger.debug("WATCHDOG: " +
                                         "Sending VIA " +
                                         sms["modemid"] +
                                         route[0]["pisurl"] +
                                         "/sendsms")
            f = urllib.request.urlopen(request, data, timeout=20)
            smsgwglobals.wislogger.debug(f.getcode())
            # if all is OK set the sms status to SENT
            smstrans.smsdict["statustime"] = datetime.utcnow()
            if f.getcode() == 200:
                if smstrans.smsdict["status"] == 0:
                    smstrans.smsdict["status"] = 4
                else:
                    smstrans.smsdict["status"] = 5
                smsgwglobals.wislogger.debug(smstrans.smsdict)
                smstrans.updatedb()
            else:
                if smstrans.smsdict["status"] == 0:
                    smstrans.smsdict["status"] = 104
                else:
                    smstrans.smsdict["status"] = 105
                smsgwglobals.wislogger.debug(smstrans.smsdict)
                smstrans.updatedb()
        except urllib.error.URLError as e:
            if smstrans.smsdict["status"] == 0:
                smstrans.smsdict["status"] = 100
            else:
                smstrans.smsdict["status"] = 105
            smsgwglobals.wislogger.debug(smstrans.smsdict)
            smstrans.updatedb()
            # set SMS to not send!!!
            smsgwglobals.wislogger.debug(e)
            smsgwglobals.wislogger.debug("Get peers NOTOK")
        except socket.timeout as e:
            smsgwglobals.wislogger.debug(e)
            smsgwglobals.wislogger.debug("WATCHDOG: Socket connection timeout")
Exemplo n.º 12
0
    def deligate(self, smstrans, route):
        # encode to json
        jdata = smstrans.getjson()
        data = GlobalHelper.encodeAES(jdata)

        request = \
            urllib.request.Request(
                route[0]["wisurl"] +
                "/smsgateway/api/deligatesms")

        request.add_header("Content-Type", "application/json;charset=utf-8")

        try:
            smsgwglobals.wislogger.debug("WATCHDOG: " + "Deligate VIA " +
                                         route[0]["wisurl"] +
                                         "/smsgateway/api/deligate")
            f = urllib.request.urlopen(request,
                                       data,
                                       timeout=wisglobals.pissendtimeout)
            smsgwglobals.wislogger.debug(
                "WATCHDOG: SMS deligate to PIS returncode:" + str(f.getcode()))
            # if all is OK set the sms status to SENT
            smstrans.smsdict["statustime"] = datetime.utcnow()
            if f.getcode() == 200:
                smstrans.smsdict["status"] = 3
                smsgwglobals.wislogger.debug("WATCHDOF: DELIGATE SUCCESS " +
                                             str(smstrans.smsdict))
                smsgwglobals.wislogger.debug(
                    "WATCHDOD: DELIGATE update  DB SUCCESS:" +
                    str(smstrans.smsdict))
                smstrans.updatedb()
            else:
                smstrans.smsdict["status"] = 103
                smsgwglobals.wislogger.debug("WATCHDOF: DELIGATE ERROR " +
                                             str(smstrans.smsdict))
                smsgwglobals.wislogger.debug(
                    "WATCHDOD: DELIGATE update DB ERROR: " +
                    str(smstrans.smsdict))
                smstrans.updatedb()
        except urllib.error.URLError as e:
            # set SMS to not send!!!
            smstrans.smsdict["status"] = 103
            smstrans.updatedb()
            smsgwglobals.wislogger.debug(e)
            smsgwglobals.wislogger.debug(
                "WATCHDOG: DELIGATE Get peers NOTOK " + str(smstrans.smsdict))
        except socket.timeout as e:
            smsgwglobals.wislogger.debug(e)
            smsgwglobals.wislogger.debug(
                "WATCHDOG: DELIGATE socket connection timeout " +
                str(smstrans.smsdict))
Exemplo n.º 13
0
    def restartmodem(self, **params):
        """ json before encoding
        {
        "modemid":"00436762222222",
        """
        # for receiving restartmodem from WIS
        cl = cherrypy.request.headers['Content-Length']
        rawbody = cherrypy.request.body.read(int(cl))
        # smsgwglobals.pislogger.debug("/sendsms: rawbody: " + str(rawbody))
        plaintext = GlobalHelper.decodeAES(rawbody)

        try:
            data = json.loads(plaintext)
            # adding action switch for message to PID
            data['action'] = "restartmodem"
            smsgwglobals.pislogger.debug("/restartmodem: dictionary: " +
                                         str(data))

        except Exception as e:
            smsgwglobals.pislogger.warning("/restartmodem: Invalid data received! "
                                           + str(e))
            cherrypy.response.status = 400  # Bad Request
            return

        try:
            address = PID.getclientaddress(data['modemid'])

            if address:
                # sending SMS to Pid
                PID.sendtopid(address, data)
            else:
                smsgwglobals.pislogger.warning("/restartmodem: No PID for " +
                                               "modem " +
                                               data['modemid'] +
                                               " found!")
                # If no modem endpoint to send - set own status code
                cherrypy.response.status = 404
                return

        except Exception as e:
            smsgwglobals.pislogger.debug("/restartmodem: Internal Server "
                                         "Error! " +
                                         str(e))
            cherrypy.response.status = 500  # Internal Server Error
            return
Exemplo n.º 14
0
    def deligate(self, smstrans, route):
        # encode to json
        jdata = smstrans.getjson()
        data = GlobalHelper.encodeAES(jdata)

        request = \
            urllib.request.Request(
                route[0]["wisurl"] +
                "/smsgateway/api/deligatesms")

        request.add_header("Content-Type",
                           "application/json;charset=utf-8")

        try:
            smsgwglobals.wislogger.debug("WATCHDOG: " +
                                         "Deligate VIA " +
                                         route[0]["wisurl"] +
                                         "/smsgateway/api/deligate")
            f = urllib.request.urlopen(request, data, timeout=wisglobals.pissendtimeout)
            smsgwglobals.wislogger.debug("WATCHDOG: SMS deligate to PIS returncode:" + str(f.getcode()))
            # if all is OK set the sms status to SENT
            smstrans.smsdict["statustime"] = datetime.utcnow()
            if f.getcode() == 200:
                smstrans.smsdict["status"] = 3
                smsgwglobals.wislogger.debug("WATCHDOF: DELIGATE SUCCESS " + str(smstrans.smsdict))
                smsgwglobals.wislogger.debug("WATCHDOD: DELIGATE update  DB SUCCESS:" + str(smstrans.smsdict))
                smstrans.updatedb()
            else:
                smstrans.smsdict["status"] = 103
                smsgwglobals.wislogger.debug("WATCHDOF: DELIGATE ERROR " + str(smstrans.smsdict))
                smsgwglobals.wislogger.debug("WATCHDOD: DELIGATE update DB ERROR: " + str(smstrans.smsdict))
                smstrans.updatedb()
        except urllib.error.URLError as e:
            # set SMS to not send!!!
            smstrans.smsdict["status"] = 103
            smstrans.updatedb()
            smsgwglobals.wislogger.debug(e)
            smsgwglobals.wislogger.debug("WATCHDOG: DELIGATE Get peers NOTOK " + str(smstrans.smsdict))
        except socket.timeout as e:
            smsgwglobals.wislogger.debug(e)
            smsgwglobals.wislogger.debug("WATCHDOG: DELIGATE socket connection timeout " + str(smstrans.smsdict))
Exemplo n.º 15
0
    def request_managemodem(wisurl, data):
        asjson = json.dumps(data)
        smsgwglobals.pislogger.info("/ws: Call /managemodem: " + str(asjson) +
                                    " at WIS " + wisurl['url'])

        tosend = GlobalHelper.encodeAES(asjson)

        request = urllib.request.Request(wisurl['url'] + "/api/managemodem")
        request.add_header("Content-Type", "application/json;charset=utf-8")
        try:
            f = urllib.request.urlopen(request, tosend, timeout=5)
            httpcode = f.getcode()
        except Exception as e:
            httpcode = 500  # Internal Server error
            smsgwglobals.pislogger.warning("/ws: WIS managemodem error: " +
                                           str(e))

        smsgwglobals.pislogger.debug("/ws: WIS managemodem response: " +
                                     str(httpcode))

        return httpcode
Exemplo n.º 16
0
    def received_message(self, msg):
        # smsgwglobals.pislogger.debug("/ws: " + str(self.peer_address) +
        #                              " - Got message: '" + str(msg) + "'")
        try:
            plaintext = GlobalHelper.decodeAES(str(msg))
            # smsgwglobals.pislogger.debug("/ws: plaintext: " + plaintext)
            data = json.loads(plaintext)
            smsgwglobals.pislogger.debug("/ws: message-dictionary: " +
                                         str(data))

            # check the protocol version of pid and pis if transmitted
            if ('pidprotocol' in data) and (data['pidprotocol'] != pisglobals.pisprotocol):
                closingreason = ('PID protocol ' + data['pidprotocol'] +
                                 " does not fit " +
                                 'PIS protocol ' + pisglobals.pisprotocol)
                # setting defined closing reasion for shutdown PID
                self.close(1011, closingreason)
            else:
                self.process_msg(data)
        except Exception as e:
            smsgwglobals.pislogger.debug("/ws: ERROR at WebSocektHandler " +
                                         "received_message: " + str(e))
Exemplo n.º 17
0
    def received_message(self, msg):
        # smsgwglobals.pislogger.debug("/ws: " + str(self.peer_address) +
        #                              " - Got message: '" + str(msg) + "'")
        try:
            plaintext = GlobalHelper.decodeAES(str(msg))
            # smsgwglobals.pislogger.debug("/ws: plaintext: " + plaintext)
            data = json.loads(plaintext)
            smsgwglobals.pislogger.debug("/ws: message-dictionary: " +
                                         str(data))

            # check the protocol version of pid and pis if transmitted
            if ('pidprotocol' in data) and (data['pidprotocol'] != pisglobals.pisprotocol):
                closingreason = ('PID protocol ' + data['pidprotocol'] +
                                 " does not fit " +
                                 'PIS protocol ' + pisglobals.pisprotocol)
                # setting defined closing reasion for shutdown PID
                self.close(1011, closingreason)
            else:
                self.process_msg(data)
        except Exception as e:
            smsgwglobals.pislogger.debug("/ws: ERROR at WebSocektHandler " +
                                         "received_message: " + str(e))
Exemplo n.º 18
0
    def request_heartbeat(data):
        asjson = json.dumps(data)
        smsgwglobals.pislogger.debug("/ws: Call WIS /heartbeat: " +
                                     str(asjson) + " at WIS " +
                                     str(pisglobals.activewisurl))

        tosend = GlobalHelper.encodeAES(asjson)

        request = urllib.request.Request(pisglobals.activewisurl +
                                         "/smsgateway/api/heartbeat")
        request.add_header("Content-Type", "application/json;charset=utf-8")
        try:
            f = urllib.request.urlopen(request, tosend, timeout=5)
            httpcode = f.getcode()
        except Exception as e:
            httpcode = 500  # Internal Server error
            smsgwglobals.pislogger.warning("/ws: WIS heartbeat error: " +
                                           str(e))

        smsgwglobals.pislogger.debug("/ws: WIS heartbeat response: " +
                                     str(httpcode))

        return httpcode
Exemplo n.º 19
0
    def wis_heartbeat(self):
        # sending 1 heartbeat for each Modem (routingid)
        for modem in self.modemlist:
            data = {}
            data['routingid'] = modem['routingid']
            data['action'] = "heartbeat"
            data['status'] = "sent"

            asjson = json.dumps(data)
            smsgwglobals.pidlogger.debug("HEARTBEAT: SENT heartbeat msg: " +
                                         str(self.handler))
            #                             str(asjson) + " to handler " +

            tosend = GlobalHelper.encodeAES(asjson)
            try:
                # sending heartbeat message to PID
                # returncodes are handled in PidWsClient.received_message
                self.handler.send(tosend)
            except Exception as e:
                # at any error with communication to PID end heartbeat
                smsgwglobals.pidlogger.warning("HEARTBEAT: ERROR at " +
                                               "wis_heartbeat: " + str(e))
                self.stop()
Exemplo n.º 20
0
    def wis_heartbeat(self):
        # sending 1 heartbeat for each Modem (routingid)
        for modem in self.modemlist:
            data = {}
            data['routingid'] = modem['routingid']
            data['action'] = "heartbeat"
            data['status'] = "sent"

            asjson = json.dumps(data)
            smsgwglobals.pidlogger.debug("HEARTBEAT: SENT heartbeat msg: " +
                                         str(self.handler))
            tosend = GlobalHelper.encodeAES(asjson)

            try:
                gammu_object = pidglobals.modemcondict[modem["modemid"]]
                gammu_object.get_modem_carrier()
            except Exception as e:
                closingreason = "PID lost connection to the modem. Probably SIM card ejected!"

                pidglobals.closingcode = 4010
                self.handler.close(code=4010, reason=closingreason)
                self.terminate()
            else:
                try:
                    # sending heartbeat message to PID
                    # returncodes are handled in PidWsClient.received_message
                    self.handler.send(tosend)
                except Exception as e:
                    # at any error with communication to PID end heartbeat
                    smsgwglobals.pidlogger.warning("HEARTBEAT: ERROR at " +
                                                   "wis_heartbeat: " + str(e))

                    closingreason = "Can't send HEARTBEAT to PIS/WIS!"

                    pidglobals.closingcode = 4010
                    self.handler.close(code=4010, reason=closingreason)
                    self.terminate()
Exemplo n.º 21
0
    def wis_heartbeat(self):
        # sending 1 heartbeat for each Modem (routingid)
        for modem in self.modemlist:
            data = {}
            data['routingid'] = modem['routingid']
            data['action'] = "heartbeat"
            data['status'] = "sent"

            asjson = json.dumps(data)
            smsgwglobals.pidlogger.debug("HEARTBEAT: SENT heartbeat msg: " +
                                         str(self.handler))
            #                             str(asjson) + " to handler " +

            tosend = GlobalHelper.encodeAES(asjson)
            try:
                # sending heartbeat message to PID
                # returncodes are handled in PidWsClient.received_message
                self.handler.send(tosend)
            except Exception as e:
                # at any error with communication to PID end heartbeat
                smsgwglobals.pidlogger.warning("HEARTBEAT: ERROR at " +
                                               "wis_heartbeat: "
                                               + str(e))
                self.stop()
Exemplo n.º 22
0
    def request_heartbeat(data):
        asjson = json.dumps(data)
        smsgwglobals.pislogger.debug("/ws: Call WIS /heartbeat: " +
                                     str(asjson) + " at WIS " +
                                     str(pisglobals.activewisurl))

        tosend = GlobalHelper.encodeAES(asjson)

        request = urllib.request.Request(pisglobals.activewisurl +
                                         "/smsgateway/api/heartbeat")
        request.add_header("Content-Type",
                           "application/json;charset=utf-8")
        try:
            f = urllib.request.urlopen(request, tosend, timeout=5)
            httpcode = f.getcode()
        except Exception as e:
            httpcode = 500  # Internal Server error
            smsgwglobals.pislogger.warning("/ws: WIS heartbeat error: " +
                                           str(e))

        smsgwglobals.pislogger.debug("/ws: WIS heartbeat response: " +
                                     str(httpcode))

        return httpcode
Exemplo n.º 23
0
    def request_managemodem(wisurl, data):
        asjson = json.dumps(data)
        smsgwglobals.pislogger.info("/ws: Call /managemodem: " +
                                    str(asjson) + " at WIS " +
                                    wisurl['url'])

        tosend = GlobalHelper.encodeAES(asjson)

        request = urllib.request.Request(wisurl['url'] +
                                         "/smsgateway/api/managemodem")
        request.add_header("Content-Type",
                           "application/json;charset=utf-8")
        try:
            f = urllib.request.urlopen(request, tosend, timeout=5)
            httpcode = f.getcode()
        except Exception as e:
            httpcode = 500  # Internal Server error
            smsgwglobals.pislogger.warning("/ws: WIS managemodem error: "
                                           + str(e))

        smsgwglobals.pislogger.debug("/ws: WIS managemodem response: " +
                                     str(httpcode))

        return httpcode
Exemplo n.º 24
0
    def receiverouting():
        # get conf peers
        abspath = path.abspath(path.join(path.dirname(__file__),
                                         path.pardir))
        configfile = abspath + '/../conf/smsgw.conf'
        cfg = SmsConfig(configfile)
        peersjson = cfg.getvalue('peers', '[{}]', 'wis')
        smsgwglobals.wislogger.debug(peersjson)

        peers = json.loads(peersjson)

        # read all active routes
        try:
            routes = wisglobals.rdb.read_routing()
        except error.DatabaseError as e:
            smsgwglobals.wislogger.debug(e.message)

        # if we have an empty rounting table,
        # try to get one from our direct connected
        # neighbor = backup
        if len(routes) == 0 or routes is None:
            Helper.requestrouting(initial=True)

        # for all routes but myself
        # send the full table
        for route in routes:
            # remove route von conf routes
            # if exist
            for p in list(peers):
                if "url" not in p:
                    continue
                if route["wisurl"] == p["url"]:
                    peers.remove(p)

            if route["wisid"] != wisglobals.wisid:
                smsgwglobals.wislogger.debug("Sending to "
                                             + route["wisurl"])
                # encode to json
                jdata = json.dumps(routes)
                data = GlobalHelper.encodeAES(jdata)

                request = \
                    urllib.request.Request(
                        route["wisurl"] +
                        "/smsgateway/api/receiverouting")

                request.add_header("Content-Type",
                                   "application/json;charset=utf-8")

                try:
                    f = urllib.request.urlopen(request, data, timeout=5)
                    smsgwglobals.wislogger.debug(f.getcode())
                except urllib.error.URLError as e:
                    smsgwglobals.wislogger.debug(e)
                    smsgwglobals.wislogger.debug("Get peers NOTOK")
                except socket.timeout as e:
                    smsgwglobals.wislogger.debug(e)
                    smsgwglobals.wislogger.debug("HELPER: receiverouting socket connection timeout")

        # check if there are remaining peers which
        # are not recognized by routing table to send
        # routing table to
        if len(peers) != 0:
            for p in peers:
                if "url" not in p:
                    continue
                jdata = json.dumps(routes)
                data = GlobalHelper.encodeAES(jdata)

                request = \
                    urllib.request.Request(
                        p["url"] +
                        "/smsgateway/api/receiverouting")

                request.add_header("Content-Type",
                                   "application/json;charset=utf-8")

                try:
                    f = urllib.request.urlopen(request, data, timeout=5)
                    smsgwglobals.wislogger.debug(f.getcode())
                    smsgwglobals.wislogger.debug("HELPER: " +
                                                 "sending to " +
                                                 p["url"])
                except urllib.error.URLError as e:
                    smsgwglobals.wislogger.debug(e)
                    smsgwglobals.wislogger.debug("Get peers NOTOK")
                    pass
                except socket.timeout as e:
                    smsgwglobals.wislogger.debug(e)
                    smsgwglobals.wislogger.debug("HELPER: receiverouting socket connection timeout")
Exemplo n.º 25
0
    def send(self, smstrans, route):
        # encode to json
        jdata = json.dumps(smstrans.smsdict)
        data = GlobalHelper.encodeAES(jdata)

        request = \
            urllib.request.Request(
                route[0]["pisurl"] +
                "/sendsms")

        request.add_header("Content-Type", "application/json;charset=utf-8")

        try:
            smsgwglobals.wislogger.debug("WATCHDOG: " + "Sending VIA " +
                                         smstrans.smsdict["modemid"] +
                                         route[0]["pisurl"] + "/sendsms")
            f = urllib.request.urlopen(request,
                                       data,
                                       timeout=wisglobals.pissendtimeout)
            smsgwglobals.wislogger.debug(
                "WATCHDOG: SMS send to PIS returncode:" + str(f.getcode()))
            # if all is OK set the sms status to SENT
            smstrans.smsdict["statustime"] = datetime.utcnow()
            if f.getcode() == 200:
                if smstrans.smsdict["status"] == 0:
                    smstrans.smsdict["status"] = 4
                    smsgwglobals.wislogger.debug("WATCHDOD: SEND direct:" +
                                                 str(smstrans.smsdict))
                else:
                    smstrans.smsdict["status"] = 5
                    smsgwglobals.wislogger.debug("WATCHDOD: SEND deligated:" +
                                                 str(smstrans.smsdict))
                smsgwglobals.wislogger.debug(
                    "WATCHDOD: SEND Update DB SUCCESS:" +
                    str(smstrans.smsdict))
                smstrans.updatedb()
            else:
                if smstrans.smsdict["status"] == 0:
                    smstrans.smsdict["status"] = 104
                    smsgwglobals.wislogger.debug(
                        "WATCHDOD: SEND direct ERROR:" + str(smstrans.smsdict))
                else:
                    smstrans.smsdict["status"] = 105
                    smsgwglobals.wislogger.debug(
                        "WATCHDOD: SEND deligated ERROR:" +
                        str(smstrans.smsdict))
                smsgwglobals.wislogger.debug(
                    "WATCHDOD: SEND Update DB ERROR:" + str(smstrans.smsdict))
                smstrans.updatedb()

        except urllib.error.URLError as e:
            if smstrans.smsdict["status"] == 0:
                smstrans.smsdict["status"] = 100
            else:
                smstrans.smsdict["status"] = 105
            smsgwglobals.wislogger.debug("WATCHDOG: SEND EXCEPTION " +
                                         str(smstrans.smsdict))
            smstrans.updatedb()
            # set SMS to not send!!!
            smsgwglobals.wislogger.debug(e)
            smsgwglobals.wislogger.debug("WATCHDOG: SEND Get peers NOTOK")
        except socket.timeout as e:
            smstrans.smsdict["status"] = 107
            smstrans.updatedb()
            smsgwglobals.wislogger.debug(e)
            smsgwglobals.wislogger.debug(
                "WATCHDOG: SEND Socket connection timeout")
Exemplo n.º 26
0
    def receiverouting():
        # get conf peers
        abspath = path.abspath(path.join(path.dirname(__file__), path.pardir))
        configfile = abspath + '/../conf/smsgw.conf'
        cfg = SmsConfig(configfile)
        peersjson = cfg.getvalue('peers', '[{}]', 'wis')
        smsgwglobals.wislogger.debug(peersjson)

        peers = json.loads(peersjson)

        # read all active routes
        try:
            routes = wisglobals.rdb.read_routing()
        except error.DatabaseError as e:
            smsgwglobals.wislogger.debug(e.message)

        # if we have an empty rounting table,
        # try to get one from our direct connected
        # neighbor = backup
        if len(routes) == 0 or routes is None:
            Helper.requestrouting(initial=True)

        # for all routes but myself
        # send the full table
        for route in routes:
            # remove route von conf routes
            # if exist
            for p in list(peers):
                if "url" not in p:
                    continue
                if route["wisurl"] == p["url"]:
                    peers.remove(p)

            if route["wisid"] != wisglobals.wisid:
                smsgwglobals.wislogger.debug("Sending to " + route["wisurl"])
                # encode to json
                jdata = json.dumps(routes)
                data = GlobalHelper.encodeAES(jdata)

                request = \
                    urllib.request.Request(
                        route["wisurl"] +
                        "/smsgateway/api/receiverouting")

                request.add_header("Content-Type",
                                   "application/json;charset=utf-8")

                try:
                    f = urllib.request.urlopen(request, data, timeout=5)
                    smsgwglobals.wislogger.debug(f.getcode())
                except urllib.error.URLError as e:
                    smsgwglobals.wislogger.debug(e)
                    smsgwglobals.wislogger.debug("Get peers NOTOK")
                except socket.timeout as e:
                    smsgwglobals.wislogger.debug(e)
                    smsgwglobals.wislogger.debug(
                        "HELPER: receiverouting socket connection timeout")

        # check if there are remaining peers which
        # are not recognized by routing table to send
        # routing table to
        if len(peers) != 0:
            for p in peers:
                if "url" not in p:
                    continue
                jdata = json.dumps(routes)
                data = GlobalHelper.encodeAES(jdata)

                request = \
                    urllib.request.Request(
                        p["url"] +
                        "/smsgateway/api/receiverouting")

                request.add_header("Content-Type",
                                   "application/json;charset=utf-8")

                try:
                    f = urllib.request.urlopen(request, data, timeout=5)
                    smsgwglobals.wislogger.debug(f.getcode())
                    smsgwglobals.wislogger.debug("HELPER: " + "sending to " +
                                                 p["url"])
                except urllib.error.URLError as e:
                    smsgwglobals.wislogger.debug(e)
                    smsgwglobals.wislogger.debug("Get peers NOTOK")
                    pass
                except socket.timeout as e:
                    smsgwglobals.wislogger.debug(e)
                    smsgwglobals.wislogger.debug(
                        "HELPER: receiverouting socket connection timeout")
                except socket.error as e:
                    smsgwglobals.wislogger.debug(e)
                    smsgwglobals.wislogger.debug(
                        "HELPER: receiverouting socket connection error")
Exemplo n.º 27
0
    def sendsms(self, **params):
        """ json before encoding
        {
        "smsid":"uuid.uuid1()",
        "modemid":"00436762222222",
        "targetnr":"+43200200200",
        "content":"test_sendsms200 ♠ ♣ ♥ ♦ ↙ ↺ ↻ ⇒ ä"}
        """
        # for receiving sms from WIS
        cl = cherrypy.request.headers['Content-Length']
        rawbody = cherrypy.request.body.read(int(cl))
        # smsgwglobals.pislogger.debug("/sendsms: rawbody: " + str(rawbody))
        plaintext = GlobalHelper.decodeAES(rawbody)

        try:
            # smsgwglobals.pislogger.debug("/sendsms: plaintext: " + plaintext)
            data = json.loads(plaintext)
            # adding action switch for message to PID
            data['action'] = "sendsms"
            smsgwglobals.pislogger.debug("/sendsms: dictionary: " +
                                         str(data))

        except Exception as e:
            smsgwglobals.pislogger.warning("/sendsms: Invalid data received! "
                                           + str(e))
            cherrypy.response.status = 400  # Bad Request
            return

        try:
            address = PID.getclientaddress(data['modemid'])

            if address:
                # sending SMS to Pid
                PID.sendtopid(address, data)
                PID.addclientsms(address, data['smsid'])

                # Poll PIDsmstatus every 0.20 second till maxwait
                maxwaitpid = pisglobals.maxwaitpid
                now = datetime.utcnow()
                until = now + timedelta(seconds=maxwaitpid)

                while now < until:
                    status = PID.getclientsmsstatus(address, data['smsid'])

                    if status == 'SUCCESS':
                        cherrypy.response.status = 200
                        PID.removeclientsms(address, data['smsid'])
                        return

                    if status == 'ERROR':
                        cherrypy.response.status = 500
                        PID.removeclientsms(address, data['smsid'])
                        return

                    # wait for next run
                    time.sleep(0.50)
                    now = datetime.utcnow()

                # maxwaitpid reached so raise an error
                smsgwglobals.pislogger.warning("/sendsms: maxwaitpid " +
                                               "of " + str(maxwaitpid) +
                                               " seconds reached!")
                cherrypy.response.status = 500
                PID.removeclientsms(address, data['smsid'])
                return

            else:
                smsgwglobals.pislogger.warning("/sendsms: No PID for " +
                                               "modem " +
                                               data['modemid'] +
                                               " found!")
                cherrypy.response.status = 500  # Internal Server Error
                return

        except Exception as e:
            smsgwglobals.pislogger.debug("/sendsms: Internal Server "
                                         "Error! " +
                                         str(e))
            cherrypy.response.status = 500  # Internal Server Error
            return
Exemplo n.º 28
0
    def restartmodem(self, **params):
        json_data = cherrypy.request.json

        # all parameters to lower case
        json_data = dict([(x[0].lower(), x[1]) for x in json_data.items()])

        # check if parameters are given
        resp = {}
        if not json_data.get("imsi"):
            cherrypy.response.status = 422
            resp["message"] = ":imsi attribute not set"
            return resp

        imsi = json_data.get("imsi")
        route = [
            r for r in wisglobals.rdb.read_routing()
            if r["imsi"] == imsi and r["obsolete"] < 1
        ]

        if route:
            modemid = route[0]["modemid"]
            db = Database()
            sms_in_progress = db.read_sms(status=0, modemid=modemid)
            if sms_in_progress:
                cherrypy.response.status = 409
                resp[
                    "message"] = ":imsi '" + imsi + "'(Modem #" + modemid + ") BUSY now sending SMS!"
                return resp
            else:
                try:
                    jdata = json.dumps({"modemid": modemid})
                    data = GlobalHelper.encodeAES(jdata)
                    request = urllib.request.Request(route[0]["pisurl"] +
                                                     "/restartmodem")
                    request.add_header("Content-Type",
                                       "application/json;charset=utf-8")
                    smsgwglobals.wislogger.debug("WIS: restartmodem '" +
                                                 route[0]["modemid"] +
                                                 "' VIA " +
                                                 route[0]["pisurl"] +
                                                 "/restartmodem")

                    f = urllib.request.urlopen(request, data, timeout=10)
                    smsgwglobals.wislogger.debug("WIS modem restart (Modem #" +
                                                 modemid +
                                                 ") send to PIS returncode:" +
                                                 str(f.getcode()))
                    # if all is OK set the sms status to SENT
                    if f.getcode() == 200:
                        cherrypy.response.status = 200
                        resp[
                            "message"] = ":imsi '" + imsi + "'(Modem #" + modemid + ") BUSY now sending SMS!"
                        return resp
                except urllib.error.URLError as e:
                    cherrypy.response.status = 500
                    resp[
                        "message"] = ":imsi '" + imsi + "'(Modem #" + modemid + ") can't be restarted now!"
                    return resp
                except socket.timeout as e:
                    cherrypy.response.status = 500
                    resp[
                        "message"] = ":imsi '" + imsi + "'(Modem #" + modemid + ") can't be restarted now!"
                    return resp

        else:
            cherrypy.response.status = 404
            resp[
                "message"] = ":imsi '" + imsi + "' not found inside any active modem!"
            return resp
Exemplo n.º 29
0
    def getsms(self, all=False, date=None):
        smsgwglobals.wislogger.debug("AJAX: " + str(all))
        smsgwglobals.wislogger.debug("AJAX: " + str(date))

        str_list = []
        smsen = []

        if all is False:
            smsgwglobals.wislogger.debug("AJAX: " + str(all))
            try:
                if date is None:
                    data = GlobalHelper.encodeAES('{"get": "sms"}')
                else:
                    data = GlobalHelper.encodeAES('{"get": "sms", "date": "' + str(date) + '"}')

                if wisglobals.sslenabled is not None and 'true' in wisglobals.sslenabled.lower():
                    request = urllib.request.Request('https://' +
                                                     wisglobals.wisipaddress +
                                                     ':' +
                                                     wisglobals.wisport +
                                                     "/smsgateway/api/getsms")
                else:
                    request = urllib.request.Request('http://' +
                                                     wisglobals.wisipaddress +
                                                     ':' +
                                                     wisglobals.wisport +
                                                     "/smsgateway/api/getsms")
                request.add_header("Content-Type",
                                   "application/json;charset=utf-8")
                f = urllib.request.urlopen(request, data, timeout=5)
                resp = f.read().decode('utf-8')
                respdata = GlobalHelper.decodeAES(resp)
                smsen = json.loads(respdata)

            except urllib.error.URLError as e:
                smsgwglobals.wislogger.debug(e)
                smsgwglobals.wislogger.debug("AJAX: getsms connect error")
            except socket.timeout as e:
                smsgwglobals.wislogger.debug(e)
                smsgwglobals.wislogger.debug("AJAX: getsms socket connection timeout")
        else:
            smsgwglobals.wislogger.debug("AJAX: " + str(all))
            entries = wisglobals.rdb.read_wisurls_union()
            if len(entries) == 0:
                return "No Wis Urls"
            else:
                for entry in entries:
                    try:
                        if date is None:
                            data = GlobalHelper.encodeAES('{"get": "sms"}')
                        else:
                            data = GlobalHelper.encodeAES('{"get": "sms", "date": "' + str(date) + '"}')

                        request = urllib.request.Request(entry["wisurl"] +
                                                         "/smsgateway/api/getsms")
                        request.add_header("Content-Type",
                                           "application/json;charset=utf-8")
                        f = urllib.request.urlopen(request, data, timeout=5)
                        resp = f.read().decode('utf-8')
                        respdata = GlobalHelper.decodeAES(resp)
                        smsen = smsen + json.loads(respdata)

                    except urllib.error.URLError as e:
                        smsgwglobals.wislogger.debug(e)
                        smsgwglobals.wislogger.debug("AJAX: getsms connect error")
                    except socket.timeout as e:
                        smsgwglobals.wislogger.debug(e)
                        smsgwglobals.wislogger.debug("AJAX: getsms socket connection timeout")

        if smsen is None or len(smsen) == 0:
            return "No SMS in Tables found"

        th = []
        tr = []

        if len(smsen) > 0:
            od = collections.OrderedDict(sorted(smsen[0].items()))
            for k, v in od.items():
                th.append(k)

        for sms in smsen:
            od = collections.OrderedDict(sorted(sms.items()))
            td = []
            for k, v in od.items():
                td.append(v)

            tr.append(td)

        str_list.append('<table id="smsTable" class="tablesorter">\n')

        str_list.append('<thead>\n')
        str_list.append('<tr>\n')
        for h in th:
            str_list.append('<th>' + h + '</th>\n')

        str_list.append('</tr>\n')
        str_list.append('</thead>\n')

        str_list.append('<tbody>\n')
        for r in tr:
            str_list.append('<tr>\n')
            for d in r:
                str_list.append('<td>' + str(d) + '</td>\n')

            str_list.append('</tr>')

        str_list.append('</tbody>\n')
        str_list.append('</table>\n')
        return ''.join(str_list)
Exemplo n.º 30
0
    def api(self, arg, **params):
        cl = cherrypy.request.headers['Content-Length']
        rawbody = cherrypy.request.body.read(int(cl))
        smsgwglobals.wislogger.debug(rawbody)
        plaintext = GlobalHelper.decodeAES(rawbody)
        smsgwglobals.wislogger.debug(plaintext)
        data = json.loads(plaintext)

        if arg == "watchdog":
            if data["run"] == "True":
                self.triggerwatchdog()
            else:
                cherrypy.response.status = 400

        if arg == "heartbeat":
            if "routingid" in data:
                smsgwglobals.wislogger.debug(data["routingid"])
                try:
                    count = wisglobals.rdb.raise_heartbeat(data["routingid"])
                    if count == 0:
                        smsgwglobals.wislogger.debug("COUNT: " + str(count))
                        cherrypy.response.status = 400
                except error.DatabaseError:
                    cherrypy.response.status = 400
            else:
                cherrypy.response.status = 400

        if arg == "receiverouting":
            try:
                wisglobals.rdb.merge_routing(data)
            except error.DatabaseError as e:
                smsgwglobals.wislogger.debug(e.message)

        if arg == "requestrouting":
            if data["get"] != "peers":
                cherrypy.response.status = 400
                return

            smsgwglobals.wislogger.debug("Sending routing table to you")
            try:
                erg = wisglobals.rdb.read_routing()
                jerg = json.dumps(erg)
                data = GlobalHelper.encodeAES(jerg)
                return data

            except error.DatabaseError as e:
                smsgwglobals.wislogger.debug(e.message)

        if arg == "managemodem":
            try:
                if data["action"] == "register":
                    smsgwglobals.wislogger.debug("managemodem register")
                    smsgwglobals.wislogger.debug(wisglobals.wisid)

                    # add wisid to data object
                    data["wisid"] = wisglobals.wisid

                    # store date in routing table
                    wisglobals.rdb.write_routing(data)

                    # call receiverouting to distribute routing
                    Helper.receiverouting()

                elif data["action"] == "unregister":
                    smsgwglobals.wislogger.debug("managemodem unregister")
                    routingid = data["routingid"]
                    wisglobals.rdb.change_obsolete(routingid, 14)
                    if routingid in wisglobals.watchdogRouteThread:
                        wisglobals.watchdogRouteThread[routingid].terminate()
                        wisglobals.watchdogRouteThread.pop(routingid)
                        wisglobals.watchdogRouteThreadNotify.pop(routingid)
                        wisglobals.watchdogRouteThreadQueue.pop(routingid)

                    Helper.receiverouting()
                else:
                    return False
            except error.DatabaseError as e:
                smsgwglobals.wislogger.debug(e.message)

        if arg == "deligatesms":
            if "sms" in data:
                smsgwglobals.wislogger.debug(data["sms"])
                try:
                    sms = Smstransfer(**data["sms"])
                    sms.smsdict["status"] = -1
                    sms.writetodb()
                    self.triggerwatchdog()
                except error.DatabaseError:
                    cherrypy.response.status = 400
            else:
                cherrypy.response.status = 400

        if arg == "router":
            if data["action"] == "status":
                smsgwglobals.wislogger.debug("API: " + data["action"])
                if wisglobals.routerThread is None:
                    cherrypy.response.status = 200
                    data = GlobalHelper.encodeAES('{"ROUTER":"noobject"}')
                    return data

                if wisglobals.routerThread.isAlive():
                    cherrypy.response.status = 200
                    data = GlobalHelper.encodeAES('{"ROUTER":"alive"}')
                    return data
                else:
                    cherrypy.response.status = 200
                    data = GlobalHelper.encodeAES('{"ROUTER":"dead"}')
                    return data

        if arg == "getsms":
            if data["get"] != "sms":
                cherrypy.response.status = 400
                return

            if "date" in data:
                date = data["date"]
                smsgwglobals.wislogger.debug("API: " + date)
            else:
                date = None

            smsgwglobals.wislogger.debug("Sending SMS Table")
            smsgwglobals.wislogger.debug("Sending SMS Table date: " +
                                         str(date))
            try:
                db = Database()
                erg = db.read_sms_date(date=date)
                jerg = json.dumps(erg)
                data = GlobalHelper.encodeAES(jerg)
                return data

            except error.DatabaseError as e:
                smsgwglobals.wislogger.debug(e.message)

        if arg == "get_sms_stats":
            if data["get"] != "sms":
                cherrypy.response.status = 400
                return
            try:
                db = Database()
                erg = db.read_sms_stats()
                jerg = json.dumps(erg)
                data = GlobalHelper.encodeAES(jerg)
                return data

            except error.DatabaseError as e:
                smsgwglobals.wislogger.debug(e.message)
Exemplo n.º 31
0
    def getsms(self, all=False, date=None):
        smsgwglobals.wislogger.debug("AJAX: " + str(all))
        smsgwglobals.wislogger.debug("AJAX: " + str(date))

        str_list = []
        smsen = []

        if all is False:
            smsgwglobals.wislogger.debug("AJAX: " + str(all))
            try:
                if date is None:
                    data = GlobalHelper.encodeAES('{"get": "sms"}')
                else:
                    data = GlobalHelper.encodeAES('{"get": "sms", "date": "' +
                                                  str(date) + '"}')

                if wisglobals.sslenabled is not None and 'true' in wisglobals.sslenabled.lower(
                ):
                    request = urllib.request.Request('https://' +
                                                     wisglobals.wisipaddress +
                                                     ':' + wisglobals.wisport +
                                                     "/smsgateway/api/getsms")
                else:
                    request = urllib.request.Request('http://' +
                                                     wisglobals.wisipaddress +
                                                     ':' + wisglobals.wisport +
                                                     "/smsgateway/api/getsms")
                request.add_header("Content-Type",
                                   "application/json;charset=utf-8")
                f = urllib.request.urlopen(request, data, timeout=5)
                resp = f.read().decode('utf-8')
                respdata = GlobalHelper.decodeAES(resp)
                smsen = json.loads(respdata)

            except urllib.error.URLError as e:
                smsgwglobals.wislogger.debug(e)
                smsgwglobals.wislogger.debug("AJAX: getsms connect error")
            except socket.timeout as e:
                smsgwglobals.wislogger.debug(e)
                smsgwglobals.wislogger.debug(
                    "AJAX: getsms socket connection timeout")
        else:
            smsgwglobals.wislogger.debug("AJAX: " + str(all))
            entries = wisglobals.rdb.read_wisurls_union()
            if len(entries) == 0:
                return "No Wis Urls"
            else:
                for entry in entries:
                    try:
                        if date is None:
                            data = GlobalHelper.encodeAES('{"get": "sms"}')
                        else:
                            data = GlobalHelper.encodeAES(
                                '{"get": "sms", "date": "' + str(date) + '"}')

                        request = urllib.request.Request(
                            entry["wisurl"] + "/smsgateway/api/getsms")
                        request.add_header("Content-Type",
                                           "application/json;charset=utf-8")
                        f = urllib.request.urlopen(request, data, timeout=5)
                        resp = f.read().decode('utf-8')
                        respdata = GlobalHelper.decodeAES(resp)
                        smsen = smsen + json.loads(respdata)

                    except urllib.error.URLError as e:
                        smsgwglobals.wislogger.debug(e)
                        smsgwglobals.wislogger.debug(
                            "AJAX: getsms connect error")
                    except socket.timeout as e:
                        smsgwglobals.wislogger.debug(e)
                        smsgwglobals.wislogger.debug(
                            "AJAX: getsms socket connection timeout")

        if smsen is None or len(smsen) == 0:
            return "No SMS in Tables found"

        th = []
        tr = []

        if len(smsen) > 0:
            od = collections.OrderedDict(sorted(smsen[0].items()))
            for k, v in od.items():
                th.append(k)

        for sms in smsen:
            od = collections.OrderedDict(sorted(sms.items()))
            td = []
            for k, v in od.items():
                td.append(v)

            tr.append(td)

        str_list.append('<table id="smsTable" class="tablesorter">\n')

        str_list.append('<thead>\n')
        str_list.append('<tr>\n')
        for h in th:
            str_list.append('<th>' + h + '</th>\n')

        str_list.append('</tr>\n')
        str_list.append('</thead>\n')

        str_list.append('<tbody>\n')
        for r in tr:
            str_list.append('<tr>\n')
            for d in r:
                str_list.append('<td>' + str(d) + '</td>\n')

            str_list.append('</tr>')

        str_list.append('</tbody>\n')
        str_list.append('</table>\n')
        return ''.join(str_list)
Exemplo n.º 32
0
    def api(self, arg, **params):
        cl = cherrypy.request.headers['Content-Length']
        rawbody = cherrypy.request.body.read(int(cl))
        smsgwglobals.wislogger.debug(rawbody)
        plaintext = GlobalHelper.decodeAES(rawbody)
        smsgwglobals.wislogger.debug(plaintext)
        data = json.loads(plaintext)

        if arg == "watchdog":

            if data["run"] == "True":
                self.triggerwatchdog()
            else:
                cherrypy.response.status = 400

        if arg == "heartbeat":
            if "routingid" in data:
                smsgwglobals.wislogger.debug(data["routingid"])
                try:
                    count = wisglobals.rdb.raise_heartbeat(data["routingid"])
                    if count == 0:
                        smsgwglobals.wislogger.debug("COUNT: " + str(count))
                        cherrypy.response.status = 400
                except error.DatabaseError:
                    cherrypy.response.status = 400
            else:
                cherrypy.response.status = 400

        if arg == "receiverouting":
            try:
                wisglobals.rdb.merge_routing(data)
            except error.DatabaseError as e:
                smsgwglobals.wislogger.debug(e.message)

        if arg == "requestrouting":
            if data["get"] != "peers":
                cherrypy.response.status = 400
                return

            smsgwglobals.wislogger.debug("Sending routing table to you")
            try:
                erg = wisglobals.rdb.read_routing()
                jerg = json.dumps(erg)
                data = GlobalHelper.encodeAES(jerg)
                return data

            except error.DatabaseError as e:
                smsgwglobals.wislogger.debug(e.message)

        if arg == "managemodem":
            try:
                if data["action"] == "register":
                    smsgwglobals.wislogger.debug("managemodem register")
                    smsgwglobals.wislogger.debug(wisglobals.wisid)

                    # add wisid to data object
                    data["wisid"] = wisglobals.wisid

                    # store date in routing table
                    wisglobals.rdb.write_routing(data)

                    # call receiverouting to distribute routing
                    Helper.receiverouting()

                elif data["action"] == "unregister":
                    smsgwglobals.wislogger.debug("managemodem unregister")
                    wisglobals.rdb.change_obsolete(data["routingid"], 14)
                    Helper.receiverouting()
                else:
                    return False
            except error.DatabaseError as e:
                smsgwglobals.wislogger.debug(e.message)

        if arg == "deligatesms":
            if "sms" in data:
                smsgwglobals.wislogger.debug(data["sms"])
                try:
                    sms = Smstransfer(**data["sms"])
                    sms.smsdict["status"] = 1
                    sms.writetodb()
                    self.triggerwatchdog()
                except error.DatabaseError:
                    cherrypy.response.status = 400
            else:
                cherrypy.response.status = 400

        if arg == "router":
            if data["action"] == "status":
                smsgwglobals.wislogger.debug("API: " + data["action"])
                if wisglobals.routerThread is None:
                    cherrypy.response.status = 200
                    data = GlobalHelper.encodeAES('{"ROUTER":"noobject"}')
                    return data

                if wisglobals.routerThread.isAlive():
                    cherrypy.response.status = 200
                    data = GlobalHelper.encodeAES('{"ROUTER":"alive"}')
                    return data
                else:
                    cherrypy.response.status = 200
                    data = GlobalHelper.encodeAES('{"ROUTER":"dead"}')
                    return data

        if arg == "getsms":
            if data["get"] != "sms":
                cherrypy.response.status = 400
                return

            if "date" in data:
                date = data["date"]
                smsgwglobals.wislogger.debug("API: " + date)
            else:
                date = None

            smsgwglobals.wislogger.debug("Sending SMS Table")
            smsgwglobals.wislogger.debug("Sending SMS Table date: " + str(date))
            try:
                db = Database()
                erg = db.read_sms_date(date=date)
                jerg = json.dumps(erg)
                data = GlobalHelper.encodeAES(jerg)
                return data

            except error.DatabaseError as e:
                smsgwglobals.wislogger.debug(e.message)
Exemplo n.º 33
0
    def sendsms(self, **params):
        """ json before encoding
        {
        "smsid":"uuid.uuid1()",
        "modemid":"00436762222222",
        "targetnr":"+43200200200",
        "content":"test_sendsms200 ♠ ♣ ♥ ♦ ↙ ↺ ↻ ⇒ ä"}
        """
        # for receiving sms from WIS
        cl = cherrypy.request.headers['Content-Length']
        rawbody = cherrypy.request.body.read(int(cl))
        # smsgwglobals.pislogger.debug("/sendsms: rawbody: " + str(rawbody))
        plaintext = GlobalHelper.decodeAES(rawbody)

        try:
            # smsgwglobals.pislogger.debug("/sendsms: plaintext: " + plaintext)
            data = json.loads(plaintext)
            # adding action switch for message to PID
            data['action'] = "sendsms"
            smsgwglobals.pislogger.debug("/sendsms: dictionary: " + str(data))

        except Exception as e:
            smsgwglobals.pislogger.warning(
                "/sendsms: Invalid data received! " + str(e))
            cherrypy.response.status = 400  # Bad Request
            return

        try:
            address = PID.getclientaddress(data['modemid'])

            if address:
                # sending SMS to Pid
                PID.sendtopid(address, data)
                PID.addclientsms(address, data['smsid'])

                # Poll PIDsmstatus every 0.20 second till maxwait
                maxwaitpid = pisglobals.maxwaitpid
                now = datetime.utcnow()
                until = now + timedelta(seconds=maxwaitpid)

                while now < until:
                    status, status_code = PID.getclientsmsstatus(
                        address, data['smsid'])

                    if status == 'SUCCESS' or status == "ERROR":
                        cherrypy.response.status = 200
                        cherrypy.response.body = status_code
                        PID.removeclientsms(address, data['smsid'])
                        return str(status_code)

                    # wait for next run
                    time.sleep(0.50)
                    now = datetime.utcnow()

                # maxwaitpid reached so raise an error
                smsgwglobals.pislogger.warning("/sendsms: maxwaitpid " +
                                               "of " + str(maxwaitpid) +
                                               " seconds reached!")
                # If timeout occured - set own status code
                status_code = 1000
                cherrypy.response.status = 200
                cherrypy.response.body = status_code
                PID.removeclientsms(address, data['smsid'])
                return str(status_code)

            else:
                smsgwglobals.pislogger.warning("/sendsms: No PID for " +
                                               "modem " + data['modemid'] +
                                               " found!")
                # If no modem endpoint to send - set own status code
                status_code = 2000
                cherrypy.response.status = 200
                cherrypy.response.body = status_code
                return str(status_code)

        except Exception as e:
            smsgwglobals.pislogger.debug("/sendsms: Internal Server "
                                         "Error! " + str(e))
            cherrypy.response.status = 500  # Internal Server Error
            return
Exemplo n.º 34
0
    def send(self, sms):
        smstrans = sms["sms"]
        route = sms["route"]
        # encode to json
        jdata = json.dumps(smstrans.smsdict, default=str)
        data = GlobalHelper.encodeAES(jdata)

        request = \
            urllib.request.Request(
                route[0]["pisurl"] +
                "/sendsms")

        request.add_header("Content-Type", "application/json;charset=utf-8")

        try:
            smsgwglobals.wislogger.debug("WATCHDOG [route: " +
                                         str(self.routingid) + "] " +
                                         "Sending VIA " +
                                         smstrans.smsdict["modemid"] +
                                         route[0]["pisurl"] + "/sendsms")
            f = urllib.request.urlopen(request,
                                       data,
                                       timeout=wisglobals.pissendtimeout)
            smsgwglobals.wislogger.debug("WATCHDOG [route: " +
                                         str(self.routingid) +
                                         "] SMS send to PIS returncode:" +
                                         str(f.getcode()))
            # if all is OK set the sms status to SENT
            smstrans.smsdict["statustime"] = datetime.utcnow()
            if f.getcode() == 200:
                status_code = f.read()

                if int(status_code) == 1:
                    if smstrans.smsdict["status"] == -1:
                        smstrans.smsdict["status"] = 101
                        smsgwglobals.wislogger.debug("WATCHDOG [route: " +
                                                     str(self.routingid) +
                                                     "] SEND deligated:" +
                                                     str(smstrans.smsdict))
                    else:
                        smstrans.smsdict["status"] = 1
                        smsgwglobals.wislogger.debug("WATCHDOG [route: " +
                                                     str(self.routingid) +
                                                     "] SEND direct:" +
                                                     str(smstrans.smsdict))
                    smsgwglobals.wislogger.debug("WATCHDOG [route: " +
                                                 str(self.routingid) +
                                                 "] SEND Update DB SUCCESS:" +
                                                 str(smstrans.smsdict))
                    smstrans.updatedb()
                elif int(status_code) == 2000 or int(status_code) == 31 or int(
                        status_code) == 27 or int(status_code) == 69:
                    # PIS doesn't have modem endpoint - reprocess SMS and choose different route) - Error 2000
                    # Modem fail - reprocess SMS and choose different route) - Error 31 (can't read SMSC nummber, 99.99% - we just lost connection)
                    # Modem fail - reprocess SMS and choose different route) - Error 27 ( no money or SIM card blocked)
                    # Modem fail - reprocess SMS and choose different route) - Error 69 (can't read SMSC nummber, 99.99% - we just lost connection)
                    # BUT use same smsid (after new route will be choosed it will decrease sms_count on route (IMSI)
                    smsgwglobals.wislogger.debug("WATCHDOG [route: " +
                                                 str(self.routingid) +
                                                 "] PIS can't reach PID: " +
                                                 str(smstrans.smsdict))
                    try:
                        Helper.processsms(smstrans)
                    except apperror.NoRoutesFoundError:
                        pass
                    else:
                        # Add sms to global queue
                        wisglobals.watchdogThread.queue.put(
                            smstrans.smsdict["smsid"])
                        wisglobals.watchdogThreadNotify.set()
                else:
                    if smstrans.smsdict["status"] == 0:
                        smstrans.smsdict["status"] = int(status_code)
                        smsgwglobals.wislogger.debug("WATCHDOG [route: " +
                                                     str(self.routingid) +
                                                     "] SEND direct ERROR:" +
                                                     str(smstrans.smsdict))
                    else:
                        smstrans.smsdict["status"] = 100 + int(status_code)
                        smsgwglobals.wislogger.debug(
                            "WATCHDOG [route: " + str(self.routingid) +
                            "] SEND deligated ERROR:" + str(smstrans.smsdict))
                    smsgwglobals.wislogger.debug("WATCHDOG [route: " +
                                                 str(self.routingid) +
                                                 "] SEND Update DB ERROR:" +
                                                 str(smstrans.smsdict))
                    smstrans.updatedb()
        except urllib.error.URLError as e:
            if smstrans.smsdict["status"] == -1:
                smstrans.smsdict["status"] = 300
            else:
                smstrans.smsdict["status"] = 200

            smsgwglobals.wislogger.debug("WATCHDOG [route: " +
                                         str(self.routingid) +
                                         "] SEND EXCEPTION " +
                                         str(smstrans.smsdict))
            smstrans.updatedb()
            # set SMS to not send!!!
            smsgwglobals.wislogger.debug(e)
            smsgwglobals.wislogger.debug("WA3TCHDOG [route: " +
                                         str(self.routingid) +
                                         "] SEND Get peers NOTOK")

            # On 500 error - (probably PID/route died - try to reprocess sms)
            try:
                Helper.processsms(smstrans)
            except apperror.NoRoutesFoundError:
                pass
            else:
                # Add sms to global queue
                wisglobals.watchdogThread.queue.put(smstrans.smsdict["smsid"])
                wisglobals.watchdogThreadNotify.set()
        except socket.timeout as e:
            smstrans.smsdict["status"] = 400
            smstrans.updatedb()
            smsgwglobals.wislogger.debug(e)
            smsgwglobals.wislogger.debug("WATCHDOG [route: " +
                                         str(self.routingid) +
                                         "] SEND Socket connection timeout")

            # On 400 error - (probably PID/route died - try to reprocess sms)
            try:
                Helper.processsms(smstrans)
            except apperror.NoRoutesFoundError:
                pass
            else:
                # Add sms to global queue
                wisglobals.watchdogThread.queue.put(smstrans.smsdict["smsid"])
                wisglobals.watchdogThreadNotify.set()