Ejemplo n.º 1
0
def main():
    """Run the CSjark program."""
    headers, configs = parse_args()

    # Parse config files
    for filename in configs:
        config.parse_file(filename)
    Options.prepare_for_parsing()

    # Remove excluded headers
    for path in set(Options.excludes):
        for filename in [i for i in headers if i.startswith(path)]:
            headers.remove(filename)

    # Parse all headers to create protocols
    failed = parse_headers(headers)

    # Write dissectors to disk
    protocols = cparser.StructVisitor.all_protocols
    wrote = write_dissectors_to_file(protocols)
    write_delegator_to_file()
    write_placeholders_to_file(protocols)

    # Write out a status message
    if failed:
        count = len(headers) - failed
        msg = "Successfully parsed %i out of %i files" % (count, len(headers))
    else:
        msg = "Successfully parsed all %i files" % len(headers)
    print("%s for %i platforms, created %i dissectors" % (msg, len(Options.platforms), wrote))
Ejemplo n.º 2
0
def main():
    """Run the CSjark program."""
    headers, configs = parse_args()

    # Parse config files
    for filename in configs:
        config.parse_file(filename)
    Options.prepare_for_parsing()

    # Remove excluded headers
    for path in set(Options.excludes):
        for filename in [i for i in headers if i.startswith(path)]:
            headers.remove(filename)

    # Parse all headers to create protocols
    failed = parse_headers(headers)

    # Write dissectors to disk
    protocols = cparser.StructVisitor.all_protocols
    wrote = write_dissectors_to_file(protocols)
    write_delegator_to_file()
    write_placeholders_to_file(protocols)

    # Write out a status message
    if failed:
        count = len(headers) - failed
        msg = 'Successfully parsed %i out of %i files' % (count, len(headers))
    else:
        msg = 'Successfully parsed all %i files' % len(headers)
    print("%s for %i platforms, created %i dissectors" %
          (msg, len(Options.platforms), wrote))
Ejemplo n.º 3
0
 def __init__(self):
     ''' Initializes instance variables and calculates a few constants.
         - base_rep       Representation of the language-level tokens
         - default_rep    Representation of the tokens for the default map
         - token_cats     Token category name <-> number(s) mappings
         - error_strings  Mapping of Error Message code -> description
         - message_types  Mapping of type word -> message code
         - version        Version of the protocol document
         - magic          Magic number for the Initial Message
         
         Protocol instances may also have members with capitalized names,
         as shorthand for the error codes in the protocol document.
     '''#'''
     self.__super.__init__()
     self.base_rep = None
     self.default_rep = None
     self.token_cats = {}
     self.error_strings = {}
     self.message_types = {}
     self.version = None
     self.magic = None
     
     parse_file(self.options.dcsp_file, self.parse_dcsp)
     
     # Calculated constants needed by the above classes
     self.quot_prefix = self.token_cats['Text'] << 8
     self.bignum = self.token_cats['Bignum'] << 8
     self.max_pos_int = (self.token_cats['Integers'][1] + 1) << 7
     self.max_neg_int = self.max_pos_int << 1
Ejemplo n.º 4
0
def create_protocols(headers, yml, args=None, cleanup=True):
    """Create protocols for black-box-testing."""
    # Store default options to be able to restore them later
    config.Options.platforms = set()
    o = config.Options
    defaults = (o.verbose, o.debug, o.strict, o.use_cpp,
                o.output_dir, o.output_file, o.platforms, o.delegator)

    # Parse command line arguments
    if args is None:
        args = []
    cli_args = ['-f'] + headers + ['-c', yml] + args
    headers, configs = csjark.parse_args(cli_args)

    # Parse config files
    for filename in configs:
        config.parse_file(filename)
    config.Options.prepare_for_parsing()

    # Create protocols
    csjark.parse_headers(headers)

    # Sort the protocols on name
    structs = {}
    for key, proto in cparser.StructVisitor.all_protocols.items():
        structs[proto.name] = proto.generate()

    if cleanup:
        perform_cleanup(defaults)
        return structs
    else:
        return structs, defaults
Ejemplo n.º 5
0
    def __init__(self):
        ''' Initializes instance variables and calculates a few constants.
            - base_rep       Representation of the language-level tokens
            - default_rep    Representation of the tokens for the default map
            - token_cats     Token category name <-> number(s) mappings
            - error_strings  Mapping of Error Message code -> description
            - message_types  Mapping of type word -> message code
            - version        Version of the protocol document
            - magic          Magic number for the Initial Message
            
            Protocol instances may also have members with capitalized names,
            as shorthand for the error codes in the protocol document.
        '''#'''
        self.__super.__init__()
        self.base_rep = None
        self.default_rep = None
        self.token_cats = {}
        self.error_strings = {}
        self.message_types = {}
        self.version = None
        self.magic = None

        parse_file(self.options.dcsp_file, self.parse_dcsp)

        # Calculated constants needed by the above classes
        self.quot_prefix = self.token_cats['Text'] << 8
        self.max_pos_int = (self.token_cats['Integers'][1] + 1) << 7
        self.max_neg_int = self.max_pos_int << 1
Ejemplo n.º 6
0
def run(path):
    global config_path
    global main_window
    config_path = path
    config.parse_file(path)

    main_window = MainWindow()
    main_window.init()
    main_window.run()
Ejemplo n.º 7
0
def create_fields():
    """Create struct config with fields rules."""
    text = '''
    Structs:
      - name: test
        cnf: sprint3.cnf
    '''
    config.parse_file(__file__, only_text=text)
    yield Options.configs['test']
    Options.configs = {}
Ejemplo n.º 8
0
def create_fields():
    """Create struct config with fields rules."""
    text = '''
    Structs:
      - name: test
        cnf: sprint3.cnf
    '''
    config.parse_file(__file__, only_text=text)
    yield Options.configs['test']
    Options.configs = {}
Ejemplo n.º 9
0
def create_structs():
    """Create structs with id and description."""
    text = '''
    Structs:
      - name: one
        id: 9
        description: a struct
      - name: two
        id: 11
    '''
    config.parse_file('test', only_text=text)
    yield Options.configs['one'], Options.configs['two']
    Options.configs = {}
Ejemplo n.º 10
0
def create_structs():
    """Create structs with id and description."""
    text = '''
    Structs:
      - name: one
        id: 9
        description: a struct
      - name: two
        id: 11
    '''
    config.parse_file('test', only_text=text)
    yield Options.configs['one'], Options.configs['two']
    Options.configs = {}
Ejemplo n.º 11
0
def create_ranges():
    """Create range rules for testing."""
    text = '''
    Structs:
      - name: test
        ranges:
          - member: percent
            min: 10
            max: 30
          - type: int
            max: 15.5
    '''
    config.parse_file('test', only_text=text)
    yield Options.configs['test']
    Options.configs = {}
Ejemplo n.º 12
0
def create_ranges():
    """Create range rules for testing."""
    text = '''
    Structs:
      - name: test
        ranges:
          - member: percent
            min: 10
            max: 30
          - type: int
            max: 15.5
    '''
    config.parse_file('test', only_text=text)
    yield Options.configs['test']
    Options.configs = {}
Ejemplo n.º 13
0
def create_bitstring():
    """Create struct config with bitstring rules."""
    text = '''
    Structs:
      - name: bitstring
        bitstrings:
          - member: flags
            1: Test
            2: [Flag, A, B]
          - type: short
            1-3: [Short, A, B, C, D, E, F, G, H]
            4: [Nih]
    '''
    config.parse_file('test', only_text=text)
    yield Options.configs['bitstring']
    Options.configs = {}
Ejemplo n.º 14
0
def create_bitstring():
    """Create struct config with bitstring rules."""
    text = '''
    Structs:
      - name: bitstring
        bitstrings:
          - member: flags
            1: Test
            2: [Flag, A, B]
          - type: short
            1-3: [Short, A, B, C, D, E, F, G, H]
            4: [Nih]
    '''
    config.parse_file('test', only_text=text)
    yield Options.configs['bitstring']
    Options.configs = {}
Ejemplo n.º 15
0
def create_rules():
    """Create configuration for different rules."""
    text = '''
    Structs:
      - name: one
        id: 9
        description: a struct
        ranges:
          - member: percent
            min: 10
            max: 30
        bitstrings:
          - member: flags
            1: Test
            2: [Flag, A, B]
        customs:
          - member: abs
            field: absolute_time
        trailers:
          - name: ber
            member: asn1_count
            size: 12
          - name: ber
            count: 1
      - name: two
        id: [11, 12, 13, 14]
        ranges:
          - type: int
            max: 15.5
        bitstrings:
          - type: short
            1-3: [Short, A, B, C, D, E, F, G, H]
            4: [Nih]
        customs:
          - type: BOOL
            field: bool
            size: 4
            abbr: bool
            name: A BOOL
        trailers:
          - name: ber
            count: 3
            size: 8
    '''
    config.parse_file('test', only_text=text)
    yield Options.configs['one'], Options.configs['two']
    Options.configs = {}
Ejemplo n.º 16
0
def create_rules():
    """Create configuration for different rules."""
    text = '''
    Structs:
      - name: one
        id: 9
        description: a struct
        ranges:
          - member: percent
            min: 10
            max: 30
        bitstrings:
          - member: flags
            1: Test
            2: [Flag, A, B]
        customs:
          - member: abs
            field: absolute_time
        trailers:
          - name: ber
            member: asn1_count
            size: 12
          - name: ber
            count: 1
      - name: two
        id: [11, 12, 13, 14]
        ranges:
          - type: int
            max: 15.5
        bitstrings:
          - type: short
            1-3: [Short, A, B, C, D, E, F, G, H]
            4: [Nih]
        customs:
          - type: BOOL
            field: bool
            size: 4
            abbr: bool
            name: A BOOL
        trailers:
          - name: ber
            count: 3
            size: 8
    '''
    config.parse_file('test', only_text=text)
    yield Options.configs['one'], Options.configs['two']
    Options.configs = {}
Ejemplo n.º 17
0
def create_enum():
    """Create struct config with enum rules."""
    text = '''
    Structs:
        - name: enum
          id: 10
          description: Enum config test
          enums:
            - member: weekday
              values: {1: MONDAY, 2: TUESDAY, 3: WEDNESDAY, 4: THURSDAY, 5: FRIDAY, 6: SATURDAY, 7: SUNDAY}
            - type: int
              values: [Zero, One, Two, Three, Four, Five]
              strict: True # Disable warning if not a valid value
    '''
    config.parse_file('test', only_text=text)
    yield Options.configs['enum']
    Options.configs = {}
Ejemplo n.º 18
0
def create_enum():
    """Create struct config with enum rules."""
    text = '''
    Structs:
        - name: enum
          id: 10
          description: Enum config test
          enums:
            - member: weekday
              values: {1: MONDAY, 2: TUESDAY, 3: WEDNESDAY, 4: THURSDAY, 5: FRIDAY, 6: SATURDAY, 7: SUNDAY}
            - type: int
              values: [Zero, One, Two, Three, Four, Five]
              strict: True # Disable warning if not a valid value
    '''
    config.parse_file('test', only_text=text)
    yield Options.configs['enum']
    Options.configs = {}
Ejemplo n.º 19
0
    def __init__(self, name, rep=None, filename=None):
        self.name = name
        self.mapname = name
        self.description = ""
        self.provinces = {}
        self.ownership = {}
        self.position = {}
        self.borders = {}
        self.powers = {}
        self.homes = {}
        self.judge = "standard"
        self.start = (SPR, 0)
        self.seasons = (SPR, SUM, FAL, AUT, WIN)
        self.rep = rep or protocol.default_rep

        if filename:
            parse_file(filename, self.parse)
Ejemplo n.º 20
0
def create_trailers():
    """Create struct config with trailer rules."""
    text = '''
    Structs:
      - name: test
        trailers:
          - name: ber
            count: 3
            size: 8
          - name: ber
            member: asn1_count
            size: 12
          - name: ber
            count: 1
    '''
    config.parse_file('test', only_text=text)
    yield Options.configs['test']
    Options.configs = {}
Ejemplo n.º 21
0
def create_trailers():
    """Create struct config with trailer rules."""
    text = '''
    Structs:
      - name: test
        trailers:
          - name: ber
            count: 3
            size: 8
          - name: ber
            member: asn1_count
            size: 12
          - name: ber
            count: 1
    '''
    config.parse_file('test', only_text=text)
    yield Options.configs['test']
    Options.configs = {}
Ejemplo n.º 22
0
 def __init__(self, name, rep=None, filename=None):
     self.name = name
     self.base = None
     self.mapname = name
     self.description = ""
     self.provinces = {}
     self.ownership = {}
     self.position = {}
     self.borders = {}
     self.powers = {}
     self.homes = {}
     self.judge = "standard"
     self.start = (SPR, 0)
     self.seasons = (SPR, SUM, FAL, AUT, WIN)
     self.rep = rep or protocol.default_rep
     
     if filename:
         parse_file(filename, self.parse)
Ejemplo n.º 23
0
def create_fields():
    """Create struct config with fields rules."""
    text = '''
    Structs:
      - name: test
        customs:
          - type: time_t
            field: relative_time
          - member: abs
            field: absolute_time
          - type: BOOL
            field: bool
            size: 4
            abbr: bool
            name: A BOOL
    '''
    config.parse_file('test', only_text=text)
    yield Options.configs['test']
    Options.configs = {}
Ejemplo n.º 24
0
def create_fields():
    """Create struct config with fields rules."""
    text = '''
    Structs:
      - name: test
        customs:
          - type: time_t
            field: relative_time
          - member: abs
            field: absolute_time
          - type: BOOL
            field: bool
            size: 4
            abbr: bool
            name: A BOOL
    '''
    config.parse_file('test', only_text=text)
    yield Options.configs['test']
    Options.configs = {}
Ejemplo n.º 25
0
 def read_syntax(self):
     levels = parse_file(self.options.syntax_file, self.parse_syntax_file)
     
     if levels:
         # Expand press levels to be useful to the Game class
         for i,name in levels:
             self.press_levels[i] = name
             self.press_levels[str(i)] = i
             self.press_levels[name.lower()] = i
     else:
         # Set reasonable press levels if the file is unparsable
         for i in range(0, 200, 10) + [8000]:
             self.press_levels[i] = str(i)
             self.press_levels[str(i)] = i
Ejemplo n.º 26
0
    def read_syntax(self):
        levels = parse_file(self.options.syntax_file, self.parse_syntax_file)

        if levels:
            # Expand press levels to be useful to the Game class
            for i, name in levels:
                self.press_levels[i] = name
                self.press_levels[str(i)] = i
                self.press_levels[name.lower()] = i
        else:
            # Set reasonable press levels if the file is unparsable
            for i in range(0, 200, 10) + [8000]:
                self.press_levels[i] = str(i)
                self.press_levels[str(i)] = i
Ejemplo n.º 27
0
def get_url_from_datadir(datadir):
    configfile = os.path.join(datadir, "tuxcoin.conf")

    try:
        cfg = config.parse_file(configfile)
    except IOError:
        return craft_url("http", "localhost", 8332)

    proto = cfg["protocol"] if "protocol" in cfg else "http"
    ip = cfg["rpcconnect"] if "rpcconnect" in cfg else "localhost"
    try:
        port = cfg["rpcport"]
    except KeyError:
        # If both regtest and testnet are set, tuxcoind will not run.
        if "regtest" in cfg and cfg["regtest"] == "1":
            port = 42075
        elif "testnet" in cfg and cfg["testnet"] == "1":
            port = 42075
        else:
            port = 42072

    return craft_url(proto, ip, port)
Ejemplo n.º 28
0
def get_auth_from_datadir(datadir):
    def craft_auth_from_credentials(user, password):
        details = ":".join([user, password])
        return base64.b64encode(bytes(details, "utf-8")).decode("utf-8")

    def get_auth_from_cookiefile(cookiefile):
        # Raises IOError if file does not exist
        with open(cookiefile, "r") as f:
            return base64.b64encode(bytes(f.readline(),
                                          "utf-8")).decode("utf-8")

    cookiefile = os.path.join(datadir, ".cookie")

    try:
        return get_auth_from_cookiefile(cookiefile)
    except FileNotFoundError:
        print("cookiefile not found, falling back to password authentication")
        # Fall back to credential-based authentication
        configfile = os.path.join(datadir, "tuxcoin.conf")

        try:
            cfg = config.parse_file(configfile)
        except IOError:
            print("configuration file not found; aborting.")
            raise

        try:
            rpcuser = cfg["rpcuser"]
            rpcpassword = cfg["rpcpassword"]
        except KeyError:
            if not ("rpcuser" in cfg):
                print("rpcuser not in configuration file.")
            if not ("rpcpassword" in cfg):
                print("rpcpassword not in configuration file.")
            raise

        return craft_auth_from_credentials(rpcuser, rpcpassword)
Ejemplo n.º 29
0
    def get_answer(self, key):
        if key in answers.keys():
            r = random.randint(0, len(answers[key]) - 1)
            return answers[key][r]
        else:
            r = random.randint(0, len(answers['unknown_command']) - 1)
            return answers['unknown_command'][r]


def login():
    try:
        print("Logging in...")
        client = Martzi(username, password, logging_level=30)
        print("Logged in successfully!")
        print("Listening...")
        client.listen()
    except Exception as e:
        print("Couldn't login to facebook!")
        print(e)
        exit()


VERSION = 0.2
print('Welcome to Matrzi v' + str(VERSION))

(username, password) = config.get_credentials()
subreddit = config.parse_file('subreddits.txt')
answers = config.parse_file('answers.txt')
login()
Ejemplo n.º 30
0
                    "--version",
                    action="store_true",
                    help="output version information and exit")

    return ap.parse_args()


if __name__ == '__main__':
    args = parse_args()

    if args.version:
        print_version()
        sys.exit(0)

    try:
        cfg = config.parse_file(args.config)
    except Exception as e:
        die("Failed to read configuration file: " + str(e))

    for c in cfg:
        for o in c.options:
            if o.name == "exec":
                if args.verbose:
                    print("Executing '{}'.".format(o.value))
                code, stderr = shell_exec(o.value, c.path)
                if code or stderr:
                    die("failed: {}: {}", code, stderr)

        filters = []
        for o in c.options:
            if o.name in ["include", "exclude"]: