Esempio n. 1
0
    def __init__(self):

        Plugin.__init__(self, 'unix')
        self._set_summary(_('Plugin to access some popular UNIX applications'))
        self._add_command(
            'fortune', '[<type>]',
            _('displays a random \
fortune. See "help fortune types".'))
        self._add_command(
            'ddate', None,
            _('displays the current date in the \
the discordian calendar.'))
        self._add_help_topic(
            'fortune_types',
            _('Available fortune types: \
fortunes, literature, riddles; default: all.'))

        self.wtf_path = '/usr/share/games/bsdgames/'
        self.wtf_parseable = True
        wtf_enabled = True

        if not os.path.isfile(os.path.join(self.wtf_path, 'acronyms')):
            self.wtf_parseable = False
            if self._get_output('wtf', False, False):
                log('i', 'Falling back to system\'s wtf.')
            else:
                wtf_enabled = False
                log('w', 'Couldn\'t find wtf installation; command disabled.')

        if wtf_enabled:
            self._add_command('wtf', '<acronym> [<type>]', 'tells you what \
<acronym> means.')
Esempio n. 2
0
    def __init__(self):
        Plugin.__init__(self, 'insult')
        self._set_summary(_('Plugin to insult somebody in the channel'))
        self._add_command('insult', '<nick>', _('Insults nick.'))
        self._add_command('add_insult', '<phrase>',
                          _('Adds phrase to the \
insults file.'))
        self._add_command('delete_insult', '<phrase>',
                          _('Deletes phrase \
from the insults file.'))
        self.insults = self._load_resource('insults')
        if not self.insults:
            import urllib2
            log('w', 'No insults found in your insults file. Fetching them...')
            self.insults['ins'] = []
            try:
                insults = urllib2.urlopen('http://server.austriangeekforce.' + \
                                          'net/insults.txt')
                insult = True
                while insult:
                    insult = insults.readline()[:-1]
                    if insult:
                        self._add(insult)
            except urllib2.URLError:
                log('e', 'Could not fetch insults.')
                self._add('You are dumber than someone who knows just one ' + \
                          'insult!')
                raise
Esempio n. 3
0
    def _maintain_cache(self) -> None:
        """Method responsible for maintaining ND cache entries"""

        for ip6_address in list(self.nd_cache):

            # Skip permanent entries
            if self.nd_cache[ip6_address].permanent:
                continue

            # If entry age is over maximum age then discard the entry
            if time.time() - self.nd_cache[
                    ip6_address].creation_time > config.ND_CACHE_ENTRY_MAX_AGE:
                mac_address = self.nd_cache.pop(ip6_address).mac_address
                if __debug__:
                    log(
                        "nd-c",
                        f"Discarded expir ICMPv6 ND cache entry - {ip6_address} -> {mac_address}"
                    )

            # If entry age is close to maximum age but the entry has been used since last refresh then send out request in attempt to refresh it
            elif (time.time() - self.nd_cache[ip6_address].creation_time >
                  config.ND_CACHE_ENTRY_MAX_AGE -
                  config.ND_CACHE_ENTRY_REFRESH_TIME
                  ) and self.nd_cache[ip6_address].hit_count:
                self.nd_cache[ip6_address].hit_count = 0
                self._send_icmp6_neighbor_solicitation(ip6_address)
                if __debug__:
                    log(
                        "nd-c",
                        f"Trying to refresh expiring ICMPv6 ND cache entry for {ip6_address} -> {self.nd_cache[ip6_address].mac_address}"
                    )
Esempio n. 4
0
    def __init__(self):
        
        Plugin.__init__(self, 'unix')
        self._set_summary(_('Plugin to access some popular UNIX applications'))
        self._add_command('fortune', '[<type>]', _('displays a random \
fortune. See "help fortune types".'))
        self._add_command('ddate', None, _('displays the current date in the \
the discordian calendar.'))
        self._add_help_topic('fortune_types', _('Available fortune types: \
fortunes, literature, riddles; default: all.'))
        
        self.wtf_path = '/usr/share/games/bsdgames/'
        self.wtf_parseable = True
        wtf_enabled = True
        
        if not os.path.isfile(os.path.join(self.wtf_path, 'acronyms')):
            self.wtf_parseable = False
            if self._get_output('wtf', False, False):
                log('i', 'Falling back to system\'s wtf.')
            else:
                wtf_enabled = False
                log('w', 'Couldn\'t find wtf installation; command disabled.')
        
        if wtf_enabled:
            self._add_command('wtf', '<acronym> [<type>]', 'tells you what \
<acronym> means.')
Esempio n. 5
0
def load(filename):
    try:
        data = pickle.load(open("{}".format(filename), "rb"))
        return data
    except:
        log("FAILED load file {}".format(filename))
        return None
def main(cfg):
    global api_path
    api_path = cfg.api_base + "/executes"
    logger.log("Testing Executes API, api path: %s", api_path)
    conn = db.connect(cfg)

    test_asset_name = "script-test-sp-echo"

    _delete(conn, test_asset_name)

    try:
        asset_id = create_asset(cfg, test_asset_name)
        add_role(cfg, asset_id, "script", json.dumps(script_role_value))
        add_role(cfg, asset_id, "script-executor-amc", {"os": "linux"})

        rsp_msg = execute(cfg, asset_id)
        rsp_msg_json = json.loads(rsp_msg)
        if rsp_msg_json["code"] != 200:
            return logger.failed("unexpected error: " + rsp_msg)

        actual_output = str(rsp_msg_json["message"]).rstrip()
        if actual_output != expected_output:
            return logger.failed("expected: '" + expected_output +
                                 "', actual: '" + actual_output + "'")

    except Exception, x:
        #traceback.print_exc()
        return logger.failed(x.message)
Esempio n. 7
0
    def close(self) -> None:
        """Close socket"""

        stack.sockets.pop(str(self), None)

        if __debug__:
            log("socket", f"<g>[{self}]</> - Closed socket")
Esempio n. 8
0
def parse_args(arg_list):
    """
    I put command line args and their proper values together in a 
    dictionaryionary and check, if the value is valid.
    """
    dictionary = {}
    for item in arg_list:
        common_pattern = re.compile(r'^(-pn|-s|-po|-pw|-n|-npw|-ho)$')
        common_pattern = common_pattern.search(item)
        if common_pattern:
            try:
                value = arg_list[arg_list.index(item) + 1]
                dictionary[common_pattern.groups()[0]] = value
            except (KeyError, IndexError):
                log('e', 'Invalid command line argument.')

        help_pattern = re.compile(r'^(-h)$').search(item)
        if help_pattern:
            dictionary['-h'] = True
        else:
            dictionary['-h'] = False

        conf_pattern = re.compile(r'^(-cnf)$').search(item)
        if conf_pattern:
            try:
                value = arg_list[arg_list.index(item) + 1]
                dictionary[common_pattern.groups()[0]] = value
            except (KeyError, IndexError):
                log('e', 'Invalid command line argument.')
        else:
            dictionary['-cnf'] = False
    return dictionary
Esempio n. 9
0
    def send(self, data: bytes) -> int:
        """Send the data to connected remote host"""

        # 'send' call requires 'connect' call to be run prior to it

        if self._remote_ip_address.is_unspecified or self._remote_port == 0:
            raise OSError("[Errno 89] Destination address requir - [Socket has no destination address set]")

        if self._unreachable:
            self._unreachable = False
            raise ConnectionRefusedError("[Errno 111] Connection refused - [Remote host sent ICMP Unreachable]")

        tx_status = stack.packet_handler.send_udp_packet(
            local_ip_address=self._local_ip_address,
            remote_ip_address=self._remote_ip_address,
            local_port=self._local_port,
            remote_port=self._remote_port,
            data=data,
        )

        sent_data_len = len(data) if tx_status is TxStatus.PASSED_TO_TX_RING else 0

        if __debug__:
            log("socket", f"<g>[{self}]</> - <lr>Sent</> {sent_data_len} bytes of data")

        return sent_data_len
Esempio n. 10
0
    def run(self,
            duration,
            view,
            request,
            ip,
            log_time,
            entry='mobile',
            request_user_id=None,
            appendix=None):
        _version = request.get('version', 'unkown')
        _device = request.get('device', None)
        _duid = request.get('duid', None)
        _os = request.get('os', None)
        _channel = request.get('channel', None)
        _prev_str = request.get('prev', None)

        mobile_logger.log(
            entry=entry,
            duration=duration,
            ip=ip,
            log_time=log_time,
            view=view,
            request_user_id=request_user_id,
            version=_version,
            device=_device,
            duid=_duid,
            os=_os,
            channel=_channel,
            prev_str=_prev_str,
            appendix=appendix,
        )
Esempio n. 11
0
def _phtx_icmp4(
    self,
    ip4_src: Ip4Address,
    ip4_dst: Ip4Address,
    icmp4_type: int,
    icmp4_code: int = 0,
    icmp4_ec_id: Optional[int] = None,
    icmp4_ec_seq: Optional[int] = None,
    icmp4_ec_data: Optional[bytes] = None,
    icmp4_un_data: Optional[bytes] = None,
    echo_tracker: Optional[Tracker] = None,
) -> TxStatus:
    """Handle outbound ICMPv4 packets"""

    icmp4_packet_tx = Icmp4Assembler(
        type=icmp4_type,
        code=icmp4_code,
        ec_id=icmp4_ec_id,
        ec_seq=icmp4_ec_seq,
        ec_data=icmp4_ec_data,
        un_data=icmp4_un_data,
        echo_tracker=echo_tracker,
    )

    if __debug__:
        log("icmp4", f"{icmp4_packet_tx.tracker} - {icmp4_packet_tx}")

    return self._phtx_ip4(ip4_src=ip4_src,
                          ip4_dst=ip4_dst,
                          carried_packet=icmp4_packet_tx)
Esempio n. 12
0
 def join(self, msg):
     level = 29
     if self.require_level(msg.user, level):
         log('i', '%s ordered to join %s.' % (msg.user.name, msg.params))
         msg.bot.join(msg.params)
     else:
         return _('Unauthorized. Level %s required.' % level)
Esempio n. 13
0
    def service(self, s: Socket) -> None:
        """Inbound connection handler"""

        while True:
            message, remote_address = s.recvfrom()

            if __debug__:
                log(
                    "service",
                    f"Service UDP Echo: Received {len(message)} bytes from {remote_address[0]}, port {remote_address[1]}"
                )

            if b"malpka" in message.strip().lower():
                message = malpka
            elif b"malpa" in message.strip().lower():
                message = malpa
            elif b"malpi" in message.strip().lower():
                message = malpi

            s.sendto(message, remote_address)

            if __debug__:
                log(
                    "service",
                    f"Service UDP Echo: Echo'ed {len(message)} bytes back to {remote_address[0]}, port {remote_address[1]}"
                )
Esempio n. 14
0
 def join(self, msg):
     level = 29
     if self.require_level(msg.user, level):
         log('i', '%s ordered to join %s.' % (msg.user.name, msg.params))
         msg.bot.join(msg.params)
     else:
         return _('Unauthorized. Level %s required.' % level)
Esempio n. 15
0
    def __init__(self):
        """
        Initializing method
        """

        self.client = Client()

        # Check if config file exists
        if not os.path.exists(os.getcwd() + '/config.json'):
            print("Для начала нужно ввести данные для авторизации")
            self.login = input("Введите ваш логин: ")
            self.password = input("Введите ваш пароль: ")

            with open(os.getcwd() + '/config.json', 'w',
                      encoding='UTF-8') as config_file:
                config_file.write(
                    json.dumps({
                        'login': self.login,
                        'password': self.password
                    }))
                config_file.close()

            log("Файл конфигурации успешно создан")
        else:
            with open(os.getcwd() + '/config.json') as config_file:
                data = json.loads(config_file.read())
                config_file.close()

            self.login = data['login']
            self.password = data['password']
Esempio n. 16
0
    def close_recording(self):
        log("Stopped Recording", self.recording_time)

        self.current_state = 'POST_RECORDING'

        if self.recording_file is not None:

            # This basically makes sure we're not truncating
            # the recording at the end due to the buffering
            # appending the defined number of frames to our
            # recording.  It basically loops backwards through
            # the rolling buffer.
            for x in reversed(self.rolling_buffer):
                self.recording_file.write_frame(x)


            self.recording_file.close()

            Popen(["python", "post_recording.py", "-f", self.recording_filename, "-i", str(self.recording_time) ])

            self.recording_time = None
            self.recording_file = None
            self.recording_filename = None

        self.current_state = 'IDLE'
Esempio n. 17
0
def get_cycles_minimum(input_file):
    # it seems I can get all the chordless cycles with this approach
    # whoever, it is extremely slow, took about 11 minutes to get cycles
    # from residential/unclassified streets of "smaller_tsukuba.osm"
    G = ox.graph.graph_from_xml(input_file, simplify=False, retain_all=True)
    H = nx.Graph(G) # make a simple undirected graph from G

    cycles = nx.cycles.minimum_cycle_basis(H) # I think a cycle basis should get all the neighborhoods, except
                                      # we'll need to filter the cycles that are too small.

    def order_cycles(H, cycle):

        for i in range(len(cycle)-1):
            for j in range(i+1, len(cycle)):
                if H.has_edge(cycle[i], cycle[j]):
                    temp = cycle[i+1]
                    cycle[i+1] = cycle[j]
                    cycle[j] = temp
                    break

    for c in cycles:
        log("Ordering cycle...")
        order_cycles(H, c)
    log("Ordering finished.")

    return cycles
Esempio n. 18
0
 def register(self, msg):
     """
     Enables a user to authenticate and therefore reach higher levels by
     assigning a password of his choice to his user object.
     """
     if self._private_only(msg):
         return False
     log('i', 'User tries to register: ' + str(msg.user))
     if msg.user.password is not None:
         return msg.prefix + _('Sorry! Your nick is already registered.')
     elif not msg.params:
         return msg.prefix + _('You have to specify a password.')
     else:
         msg.user.password = msg.params
         log(
             'i', 'User %s registered with password %s.' %
             (msg.user.name, msg.user.password))
         if msg.user.name.lower() == configuration.superadmin:
             msg.user.level = 30
         else:
             msg.user.level = 0
         msg.user.trusted = True
         User.users.sync()
         return msg.prefix + _(
             'Your nick has been successfully registered!')
Esempio n. 19
0
def parse_args(arg_list):
    """
    I put command line args and their proper values together in a 
    dictionaryionary and check, if the value is valid.
    """
    dictionary = {}
    for item in arg_list:
        common_pattern = re.compile(r'^(-pn|-s|-po|-pw|-n|-npw|-ho)$')
        common_pattern = common_pattern.search(item)
        if common_pattern:
            try:
                value = arg_list[arg_list.index(item)+1]
                dictionary[common_pattern.groups()[0]] = value
            except (KeyError, IndexError):
                log('e', 'Invalid command line argument.')
        
        help_pattern = re.compile(r'^(-h)$').search(item)
        if help_pattern:
            dictionary['-h'] = True
        else:
            dictionary['-h'] = False
        
        conf_pattern = re.compile(r'^(-cnf)$').search(item)
        if conf_pattern:
            try:
                value = arg_list[arg_list.index(item)+1]
                dictionary[common_pattern.groups()[0]] = value
            except (KeyError, IndexError):
                log('e', 'Invalid command line argument.')
        else:
            dictionary['-cnf'] = False
    return dictionary
Esempio n. 20
0
    def _remove_ip6_multicast(self, ip6_multicast: Ip6Address) -> None:
        """Remove IPv6 multicast address from the list stack listens on"""

        self.ip6_multicast.remove(ip6_multicast)
        if __debug__:
            log("stack", f"Removed IPv6 multicast {ip6_multicast}")
        self._remove_mac_multicast(ip6_multicast.multicast_mac)
Esempio n. 21
0
def compute_neighbors_MST(cycles, input):
    import lib.trigonometry as trig
    _output = "{}_neighbor_data".format(input)
    neighbor_values = helper.load(_output)

    if neighbor_values == None:
        log("Computing neighbors with MST...", "DEBUG")
        neighbor_values = {}
        for i in cycles:
            neighbor_values[i] = []

        added = [0]
        while len(added) != len(cycles):
            distances = []
            for i in range(len(cycles)):
                for j in range(len(cycles)):
                    if i in added and j not in added:
                        dist = trig.dist(*cycles[i]["centroid"],
                                         *cycles[j]["centroid"])
                        distances.append((dist, i, j))
            distances = sorted(distances)
            dist, i, j = distances.pop(0)
            neighbor_values[i].append(j)
            neighbor_values[j].append(i)
            added.append(j)
        helper.save(neighbor_values, _output)
    else:
        log("Loaded MST data from file {}".format(_output), "DEBUG")

    for i in neighbor_values:
        cycles[i]["neighbors"] = neighbor_values[i]
Esempio n. 22
0
 def set(self, msg):
     """Sets level of a user to a certain value."""
     token = msg.params.split()
     if len(token) == 2:
         level = int(token[1])
         allowed = self.require_level(msg.user, level + 1)
         if allowed:
             if token[0] in User.users:
                 old_level = User.users[token[0]].level or 0
                 User.users[token[0]].level = level
                 User.users.sync()
                 log(
                     'i', '%s changed the level of user %s from %d to %d.' %
                     (msg.user.name, token[0], old_level, level))
                 return msg.prefix + \
                     _('Changed the level of user %s from %d to %d.') % (
                     token[0], old_level, level)
             else:
                 return msg.prefix + \
                     _('User %s is not registered.' % token[0])
         else:
             return msg.prefix + \
                 _('Unauthorized. Level %d required.' % (level + 1))
     else:
         return msg.prefix + \
             _('You need to specify the username and the level.')
Esempio n. 23
0
def _phtx_arp(
    self,
    ether_src: MacAddress,
    ether_dst: MacAddress,
    arp_oper: int,
    arp_sha: MacAddress,
    arp_spa: Ip4Address,
    arp_tha: MacAddress,
    arp_tpa: Ip4Address,
    echo_tracker: Optional[Tracker] = None,
) -> None:
    """Handle outbound ARP packets"""

    # Check if IPv4 protocol support is enabled, if not then silently drop the packet
    if not config.IP4_SUPPORT:
        return

    arp_packet_tx = ArpAssembler(
        oper=arp_oper,
        sha=arp_sha,
        spa=arp_spa,
        tha=arp_tha,
        tpa=arp_tpa,
        echo_tracker=echo_tracker,
    )

    if __debug__:
        log("arp", f"{arp_packet_tx.tracker} - {arp_packet_tx}")

    self._phtx_ether(ether_src=ether_src,
                     ether_dst=ether_dst,
                     carried_packet=arp_packet_tx)
Esempio n. 24
0
def _phtx_udp(
    self,
    ip_src: IpAddress,
    ip_dst: IpAddress,
    udp_sport: int,
    udp_dport: int,
    udp_data: Optional[bytes] = None,
    echo_tracker: Optional[Tracker] = None,
) -> TxStatus:
    """Handle outbound UDP packets"""

    assert 0 < udp_sport < 65536, f"{udp_sport=}"
    assert 0 < udp_dport < 65536, f"{udp_dport=}"

    udp_packet_tx = UdpAssembler(sport=udp_sport,
                                 dport=udp_dport,
                                 data=udp_data,
                                 echo_tracker=echo_tracker)

    if __debug__:
        log("udp", f"{udp_packet_tx.tracker} - {udp_packet_tx}")

    if isinstance(ip_src, Ip6Address) and isinstance(ip_dst, Ip6Address):
        return self._phtx_ip6(ip6_src=ip_src,
                              ip6_dst=ip_dst,
                              carried_packet=udp_packet_tx)

    if isinstance(ip_src, Ip4Address) and isinstance(ip_dst, Ip4Address):
        return self._phtx_ip4(ip4_src=ip_src,
                              ip4_dst=ip_dst,
                              carried_packet=udp_packet_tx)

    return TxStatus.DROPED_UDP_UNKNOWN
Esempio n. 25
0
 def set(self, msg):
     """Sets level of a user to a certain value."""
     token = msg.params.split()
     if len(token) == 2:
         level = int(token[1])
         allowed = self.require_level(msg.user, level + 1)
         if allowed:
             if token[0] in User.users:
                 old_level = User.users[token[0]].level or 0
                 User.users[token[0]].level = level
                 User.users.sync()
                 log('i',
                     '%s changed the level of user %s from %d to %d.' % (
                     msg.user.name, token[0], old_level, level))
                 return msg.prefix + \
                     _('Changed the level of user %s from %d to %d.') % (
                     token[0], old_level, level)
             else:
                 return msg.prefix + \
                     _('User %s is not registered.' % token[0])
         else:
             return msg.prefix + \
                 _('Unauthorized. Level %d required.' % (level + 1))
     else:
         return msg.prefix + \
             _('You need to specify the username and the level.')
Esempio n. 26
0
    def __init__(self):
        Plugin.__init__(self, 'insult')
        self._set_summary(_('Plugin to insult somebody in the channel'))
        self._add_command('insult', '<nick>', _('Insults nick.'))
        self._add_command('add_insult', '<phrase>', _('Adds phrase to the \
insults file.'))
        self._add_command('delete_insult', '<phrase>', _('Deletes phrase \
from the insults file.'))
        self.insults = self._load_resource('insults')
        if not self.insults:
            import urllib2
            log('w', 'No insults found in your insults file. Fetching them...')
            self.insults['ins'] = []
            try:
                insults = urllib2.urlopen('http://server.austriangeekforce.' + \
                                          'net/insults.txt')
                insult = True
                while insult:
                    insult = insults.readline()[:-1]
                    if insult:
                        self._add(insult)
            except urllib2.URLError:
                log('e', 'Could not fetch insults.')
                self._add('You are dumber than someone who knows just one ' + \
                          'insult!')
                raise
Esempio n. 27
0
    def _send_icmp6_multicast_listener_report(self) -> None:
        """Send out ICMPv6 Multicast Listener Report for given list of addresses"""

        # Need to use set here to avoid re-using duplicate multicast entries from stack_ip6_multicast list,
        # also All Multicast Nodes address is not being advertised as this is not necessary
        if icmp6_mlr2_multicast_address_record := {
                Icmp6MulticastAddressRecord(
                    record_type=ICMP6_MART_CHANGE_TO_EXCLUDE,
                    multicast_address=_)
                for _ in self.ip6_multicast
                if _ not in {Ip6Address("ff02::1")}
        }:
            self._phtx_icmp6(
                ip6_src=self.ip6_unicast[0]
                if self.ip6_unicast else Ip6Address(0),
                ip6_dst=Ip6Address("ff02::16"),
                ip6_hop=1,
                icmp6_type=ICMP6_MLD2_REPORT,
                icmp6_mlr2_multicast_address_record=
                icmp6_mlr2_multicast_address_record,
            )
            if __debug__:
                log(
                    "stack",
                    "Sent out ICMPv6 Multicast Listener Report message for " +
                    f"{[_.multicast_address for _ in icmp6_mlr2_multicast_address_record]}"
                )
Esempio n. 28
0
    def _assign_ip6_host(self, ip6_host: Ip6Host) -> None:
        """Assign IPv6 host unicast  address to the list stack listens on"""

        self.ip6_host.append(ip6_host)
        if __debug__:
            log("stack", f"Assigned IPv6 unicast address {ip6_host}")
        self._assign_ip6_multicast(ip6_host.address.solicited_node_multicast)
Esempio n. 29
0
    def _remove_ip6_host(self, ip6_host: Ip6Host) -> None:
        """Remove IPv6 ihost unicast address from the list stack listens on"""

        self.ip6_host.remove(ip6_host)
        if __debug__:
            log("stack", f"Removed IPv6 unicast address {ip6_host}")
        self._remove_ip6_multicast(ip6_host.address.solicited_node_multicast)
Esempio n. 30
0
    def enqueue(self, packet_tx: EtherAssembler) -> None:
        """Enqueue outbound packet into TX ring"""

        self.tx_ring.append(packet_tx)
        if __debug__:
            log("rx-ring",
                f"{packet_tx.tracker}, queue len: {len(self.tx_ring)}")
        self.packet_enqueued.release()
Esempio n. 31
0
File: server.py Progetto: sumory/BTC
 def get_request(self):
     line = self.fileobj.readline()
     #print('line %s' % line)
     if not line:
         return
     logger.log('client', 'recv %s:%s %s' % (self.address[0], self.address[1], line.strip()))
     request = json.loads(line)
     return request
Esempio n. 32
0
def _testDeleteNonExisted(conn, role):
    logger.log("running DeleteNonExisted")
    _delete_data = {"modified_ts": str(role.modified_ts)}
    rsp = requests.delete(api_path + "/" + role.name, params=_delete_data)
    if not rsp.status_code == 410:
        return logger.failed("DeleteNonExisted expected {410, ...}, got code:",
                             rsp.status_code, "response:", rsp.text)
    return True
Esempio n. 33
0
 def _word_exists(self, word):
     """Checks if word exists and returns either True or False."""
     try:
         self.vault[word]
         return True
     except KeyError:
         log('w', 'No vault entry for %s.' % word)
         return False
Esempio n. 34
0
 def quit(self, msg):
     level = 30
     if self.require_level(msg.user, level):
         log('i', 'Shutdown initiated by %s' % msg.user.name)
         User.users.close()
         reactor.stop()
     else:
         return _('Unauthorized. Level %s required.' % level)
Esempio n. 35
0
 def __init__(self, name, level=None, trusted=False,):
     self.name = name.split("!")[0]
     self.hostmask = name
     self.password = None
     self.trusted = False
     self.level = 0
     User.users[self.name] = self
     log('i', 'Saved user %s into the database.' % self.name)
Esempio n. 36
0
 def quit(self, msg):
     level = 30
     if self.require_level(msg.user, level):
         log('i', 'Shutdown initiated by %s' % msg.user.name)
         User.users.close()
         reactor.stop()
     else:
         return _('Unauthorized. Level %s required.' % level)
Esempio n. 37
0
def main(cfg):
    logger.log("requesting /publicKey")
    req = requests.get(cfg.api_base + "/publicKey")
    if not req.ok:
        logger.log("expected {200, OK}, got code:", req.status_code,
                   "reponse:", req.text)

    return len(req.text) > 380 and req.text.startswith("ssh-rsa ")
Esempio n. 38
0
 def _word_exists(self, word):
     """Checks if word exists and returns either True or False."""
     try:
         self.vault[word]
         return True
     except KeyError:
         log('w', 'No vault entry for %s.' % word)
         return False
Esempio n. 39
0
    def _assign_ip6_multicast(self, ip6_multicast: Ip6Address) -> None:
        """Assign IPv6 multicast address to the list stack listens on"""

        self.ip6_multicast.append(ip6_multicast)
        if __debug__:
            log("stack", f"Assigned IPv6 multicast {ip6_multicast}")
        self._assign_mac_multicast(ip6_multicast.multicast_mac)
        for _ in range(1):
            self._send_icmp6_multicast_listener_report()
Esempio n. 40
0
    def start_recording(self):
        self.current_state = 'RECORDING'
        epoch_time = int(time.time())

        self.recording_time = epoch_time
        self.recording_filename = 'output/output_' + str(epoch_time) + '.wav'
        self.recording_file = self.recorder.open(self.recording_filename, 'wb')

        log("Started Recording", self.recording_time)
Esempio n. 41
0
File: server.py Progetto: sumory/BTC
 def call(self, method, *args):
     obj = {
         'id': 1,
         'method': method,
         'params': args,
     }
     s = json.dumps(obj) + '\n'
     logger.log('client', 'call %s:%s %s' % (self.address[0], self.address[1], s.strip()))
     self.fileobj.write(s)
     self.fileobj.flush()
Esempio n. 42
0
File: server.py Progetto: sumory/BTC
 def response(self, request_id, result):
     obj = {
         'id': request_id,
         'result': result,
         'error': None,
     }
     s = json.dumps(obj) + '\n'
     logger.log('client', 'resp %s:%s %s' % (self.address[0], self.address[1], s.strip()))
     self.fileobj.write(s)
     self.fileobj.flush()
Esempio n. 43
0
 def restart(self, msg):
     """Stops and restarts the bot."""
     level = 29
     if self.require_level(msg.user, level):
         msg.bot.msg(msg.reply_to, _('Restarting...'))
         log('w', 'Restart requested by %s.' % msg.user.name)
         reactor.stop()
         os.execl('./bot.py', *sys.argv)
     else:
         return _('Unauthorized. Level %s required.' % level)
Esempio n. 44
0
 def require_level(self, user, level):
     """
     Use this function inside a plugin to determine if the level of the
     user who invokes a keyword is sufficient. Returns True if it is
     and False otherwise.
     """
     if user.level >= level and user.trusted:
         log("i", "Permission granted to user " + str(user))
         return True
     else:
         log("i", "Permission denied to user " + str(user))
         return False
Esempio n. 45
0
def Error(ex):
  """ex is an exception"""
  print 'Content-type: text/html\n\n'
  print '<html><body><h2>Congratulations!  You found a bug in Webnote!</h2>'
  print '<p>(or perhaps the database is down)</p>'
  print ("<p>We'll try to have webnote up and running again as soon as "
         "possible</p>")
  if SHOWDEBUG:
    import cgitb
    cgitb.handler()
  print '</body></html>'
  log(str(ex))
Esempio n. 46
0
 def auth(self, msg):
     """
     If a user uses auth with the correct password he can use all
     possibilities of the level associated with his account.
     """
     if self._private_only(msg):
         return False
     log('i', 'User attempting to authenticate: ' + str(msg.user))
     if msg.params == msg.user.password:
         msg.user.trusted = True
         return msg.prefix + _("You're authenticated by now.")
     else:
         return msg.prefix + _("Passwords do NOT match. DO NOT TRY TO FOOL ME!")
Esempio n. 47
0
def monitor_block():
    print '\n\n\n%s scan blocks..' % time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
    logger.log('scan_blocks', 'scan start')

    try:
        sql = 'select * from pool_block where confirmations < 120'
        #sql = 'select * from pool_block'
        all_blocks = db.all_dict(sql)
        logger.log('scan_blocks', 'need scan for %d blocks' % len(all_blocks))



        if(len(all_blocks) != 0):

            for b in all_blocks:
                try:
                    block_hash = b['hash']
                    block_id = int(b['id'])
                    
                    rpc_block = rpc.getblock(block_hash)
                    confirmations = int(rpc_block['confirmations'])
                    
                    db.run('update pool_block set confirmations=%d where id = %d' % (confirmations, block_id))
                except Exception, e:
                    logger.log('scan_blocks', 'exception %s' %e)
    except Exception, e:
        logger.log('scan_blocks','unknown excepiton %s' %e)
Esempio n. 48
0
def last_seen(name):
    try:
        user = User.users[name]
        delta = SeenPlugin.now() - user.last_action.time
        return _("%s was last seen: %s ago, %s" % \
                 (user.name, time_ago_in_words(delta), user.last_action))
        #return user.last_action.time
    except KeyError:
        return _("Gee... I've never seen " + name)
        log('i', "Information about unknown User requested")
        raise
    except NameError:
        log('i', "User has no action defined yet")
        raise
Esempio n. 49
0
 def _load_extended(self, section):
     extended = Storage()
     for option in [opt for opt in self.config.options(section) if
     opt.startswith('x-')]:
         try:
             (plugin, key) = option.split('-', 2)[1:]
         except ValueError:
             log('w', 'Incorrect entry "%s" in config section "%s"' % (
                 option, section))
             continue
         if not hasattr(extended, plugin):
             setattr(extended, plugin, Storage())
         setattr(getattr(extended, plugin), key, self._get(section, option))
     return extended
Esempio n. 50
0
def worker(outbox, ses):
    while True:
        data = outbox.get()
        try:
            response = sendmail(data=data, ses=ses, callback=log)
            sent.next()
        except:
            error.next()
            msg = '-'*80
            msg += '\n%s\n' % format_exc()
            msg += str(data)
            msg += '\n'
            msg += '-'*80
            log(msg)
Esempio n. 51
0
 def reload(self, msg):
     """Reloads all plugins for this connection."""
     level = 29
     if self.require_level(msg.user, level):
         log('i', '%s initiated plugin reload...' % msg.user.name)
         msg.bot.msg(msg.reply_to, _('Reloading plugins...'))
         plugs = PluginLoader().load_plugins()
         handler = PluginHandler(plugs)
         del msg.bot.plugins
         msg.bot.plugins = Set(handler.plugins.values())
         del msg.bot.factory.plugin_handler
         msg.bot.factory.plugin_handler = handler
         return _('Done.')
     else:
         return _('Unauthorized. Level %s required.' % level)
Esempio n. 52
0
 def seen(self, msg):
     params = msg.params.split()
     log('i', "You wanted to see:" + params[0])
     if len(params) != 1:
         msg.bot.msg(msg.reply_to, _("Usage: seen user"))
     else:
         try:
             if msg.user.name == params[0]:
                 return _(params[0] + \
                                 _(":Huh? You dont see yourself? WTF!?"))
             else:
                 return last_seen(params[0])
         except(KeyError, NameError):
             raise
             return _("Gee...I've never seen " + params[0])
 def mainloop(self):
     """
     This is the main loop, which checks for new bugs every minute,
     and reports any new ones to the IRC channel.
     """
     
     if not self.warmup:
         self.warmup = True
         return
     
     for project in self.projects:
         
         # Fetch new bugs
         try:
             bugs = self.get_latest_bugs(project)
         except Exception:
             log('e',
                 'Failed to fetch bugs for %s, skipping' % project)
             continue
         
         # If this is the first run for this project
         if not self.projects[project][1]:
             # Mark all recent bugs as already reported
             self.projects[project][1] = [x[0] for x in bugs]
         
         # Filter out already reported bugs
         new_bugs = [bug for bug in bugs if bug[0] not in \
             self.projects[project][1]]
         self.projects[project][1] = [x[0] for x in bugs]
         
         # Report the bugs
         for (number, desc, url, package, status, imp) in new_bugs:
             if package == 'ubuntu':
                 # Try to find the component (main/universe) of package.
                 try:
                     location = ' (%s)' % self.get_bug_location(url)
                 except Exception:
                     location = ' (?)'
             else:
                 location = ''
             
             msg = 'New bug: #%s in %s%s: "%s" [%s, %s] %s' % \
                 (number, package, location, desc, imp, status, url)
             log('i', msg)
             
             for bot, chans in self.projects[project][0].iteritems():
                 for channel in chans:
                     bot.msg(channel, str(msg))             
Esempio n. 54
0
def getblocks():

    try:
        heights = range(263534, 264609)[::-1]
        for i in heights:
            hash = rpc.getblockhash(i)
            block = rpc.getblock(hash)
            # print("%d %s %s" % (block['height'],time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(block['time'])),block['hash']))
            logger.log(
                "block",
                "%d\t%s\t%s"
                % (block["height"], time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(block["time"])), block["hash"]),
            )
    except Exception, e:
        print(e)
        logger.log("error", "%s" % e)
Esempio n. 55
0
def CreateSave():
    ret = Workspace()
    size = os.environ.get('CONTENT_LENGTH', 0)
    data = sys.stdin.read(int(size)).replace('\0', '')
    log(data)
    
    # there should be something here for catching an incomplete send
    dom = parseString(data)
    wsRoot = dom.getElementsByTagName('workspace').item(0)
    ret.name = wsRoot.getAttribute('name')
    ret.nextNoteNum = wsRoot.getAttribute('nextNoteNum')
    
    nlNotes = wsRoot.getElementsByTagName('note')

    for i in range(nlNotes.length):
      ret.notes.append(Note.Note.FromXML(nlNotes.item(i)))
    return ret
Esempio n. 56
0
    def karma(self, msg):
        """
        If parameters given, returns a summary of first parameter's karma. IF
        not you can see some pretty stats."""
        if len(msg.msg.split(' ')) > 1:
            word = msg.msg.split(' ')[1].lower()
            if self._word_exists(word):
                pos = self.vault[word][0]
                neg = self.vault[word][1]
                sum = self.vault[word][2]
                if sum > 99:
                    comment = _('%s is far too good! Practice Evil, my friend.'
                     %  word)
                elif 100 > sum > 0:
                    comment = _('What a nice %s, so many good deeds...') % word
                elif sum == 0:
                    comment = _('The ultimate way to Nirvana.')
                elif -50 < sum < 0:
                    comment = _('Such a bad boy.')
                elif -49 < sum:
                    comment = _('%s seems to be an evil genius in training.' %
                                word)
                return _('Karma statistics for %s: +%i -%i => %i -- %s' % 
                          (word, pos, neg, sum, comment))
            else:
                return _('%s has no karma recordings yet.' % word)
        else:
            highest = ['None', 0]
            lowest = ['None', 0]
            pos = 0
            neg = 0
            sum = 0
            for k, v in self.vault.items():
                log('i', '%s#%s' % (str(k), str(v)))
                if v[2] > highest[1]:
                    highest = [k, v[2]]
                if v[2] < lowest[1]:
                    lowest = [k, v[2]]
                pos += v[0]
                neg += v[1]
                sum += v[2]
            return _('I keep track of %i people\'s karma. Overall I noticed \
%i positive and %i negative karma points. %s is the most well behaved I \
know. %s seems to have a Bachelor\'s degree in Darkness. The common karma of \
all people I know is %i.' % (len(self.vault), pos, neg, highest[0], lowest[0],
                            sum))
Esempio n. 57
0
    def _create_connection(self, conn):
        # Initialize variables
        channels = []
        port = 0
        
        # Server and Port
        server = self._get(conn, 'server') or None
        if not server:
            log('e', 'No server defined for connection "%s".' % conn)
            return False
        if ':' in server:
            server, port = server.split(':')
        
        # Channels
        if not self.config.has_option(conn, 'channels'):
            log('w', 'Connection "%s" has no channel definition.' % conn)
        for channel in self._get(conn, 'channels').split(' '):
            if not channel.startswith('#'):
                log('w', 'Channel "%s" doesn\'t start with a hash (#); \
ignoring.' % channel)
            channels.append(channel)
        if not len(channels):
            log('e', 'No valid channel defined for connection "%s".' % conn)
            return False
        
        # Create the connection class
        connection = IRCConnection(server)
        connection.name = conn
        connection.port = int(port) or 6667
        connection.ssl = self._get(conn, 'ssl') or False
        connection.password = self._get(conn, 'password') or None
        connection.host = self._get(conn, 'host') or 'localhost'
        connection.nick = self._get(conn, 'nick') or 'p1tr'
        connection.realname = self._get(conn, 'realname') or 'P1tr IRC Bot'
        connection.nickpw = self._get(conn, 'nickpw') or None
        connection.channels = channels
        connection.signal_char = (self._get(conn, 'signal') or '*')[0]
        
        # Load X-* values for this connection
        connection.extended = self._load_extended(conn)
        
        # Save it
        self.servers.append(connection)
        log('i', 'Loaded configuration for connection "%s".' % conn)
        return connection
Esempio n. 58
0
 def _load_resource(self, title):
     """
     Returns a shelve if it can be opened, otherwise None.
     Example usage in a plugin: self.data = self._load_resource('info')
     This creates data/pluginname_info, where everything you write to
     self.data is stored. After adding information to self.data it is
     recommended to to self.data.sync() to write changes to the file.
     In case you need the resource just for a limited time you can close
     it using self._close_resource(self.data). This does the sync() for
     you.
     """
     try:
         res = shelve.open(os.path.join("data", "%s_%s" % (self.name, title)), protocol=0, writeback=True)
         return res
     except anydbm.error:
         log("e", "Unable to open resource file:")
         raise
         return None
Esempio n. 59
0
def load_language(lcode=None):
    """
    Installs language lcode; if not given the language from the configuration
    file will be installed. Useful for language changes at runtime.
    Returns a tuple; first item is the new language; second item is a arg_list of
    all available languages.
    """
    langs = {}
    for language in ['ca', 'da', 'de', 'en', 'es', 'fr', 'hi', 'la',
                    'ru', 'sv', 'tr']:
        langs[language] = gettext.translation('p1tr', './locale',
            languages=[language])
    if lcode:
        log('i', 'Lang "%s" loaded.' % lcode)
        langs[lcode].install()
    else:
        conf_lang = configuration.language
        log('i', 'Loaded language "%s" (specified in the config file).' % \
        conf_lang)
        langs[conf_lang].install()
    return (lcode or conf_lang, langs.keys())