summaryrefslogtreecommitdiff
path: root/src/pydrilla/pydrilla.py
blob: 586be19aafeb3ebb0c8c9f6f79608d788b9ee196 (about) (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
# SPDX-License-Identifier: AGPL-3.0-or-later

# Main repository logic.
#
# This file is part of Hydrilla
#
# Copyright (C) 2021 Wojtek Kosior
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
#
#
# I, Wojtek Kosior, thereby promise not to sue for violation of this
# file's license. Although I request that you do not make use this code
# in a proprietary program, I am not going to enforce this in court.

from flask import Flask, Blueprint, current_app, url_for, abort, request
from jinja2 import Environment, PackageLoader
import re
#from hashlib import sha256
import os
import pathlib
import json
import gettext
import logging

SCHEMA_VERSION = [0, 2]

strip_comment_re = re.compile(r'''
^ # match from the beginning of each line
( # catch the part before '//' comment
  (?: # this group matches either a string or a single out-of-string character
    [^"/] |
    "
    (?: # this group matches any in-a-string character
      [^"\\] |          # match any normal character
      \\[^u] |          # match any escaped character like '\f' or '\n'
      \\u[a-fA-F0-9]{4} # match an escape
    )*
    "
  )*
)
# expect either end-of-line or a comment:
# * unterminated strings will cause matching to fail
# * bad comment (with '/' instead of '//') will be indicated by second group
#   having length 1 instead of 2 or 0
(//?|$)
''', re.VERBOSE)

def strip_json_comments(text):
    processed = 0
    stripped_text = []
    for line in text.split('\n'):
        match = strip_comment_re.match(line)

        if match is None: # unterminated string
            # ignore this error, let json module report it
            stripped = line
        elif len(match[2]) == 1:
            raise json.JSONDecodeError('bad comment', text,
                                       processed + len(match[1]))
        else:
            stripped = match[1]

        stripped_text.append(stripped)
        processed += len(line) + 1

    return '\n'.join(stripped_text)

here = pathlib.Path(__file__).resolve().parent

bp = Blueprint('bp', __package__)

def load_config(config_path):
    config = {}
    to_load = [config_path]
    failures_ok = [False]

    while to_load:
        path = to_load.pop()
        can_fail = failures_ok.pop()

        try:
            with open(config_path) as config_file:
                new_config = json.loads(strip_json_comments(config_file.read()))
        except Exception as e:
            if can_fail:
                continue
            raise e from None

        config.update(new_config)

        for key, failure_ok in [('try_configs', True), ('use_configs', False)]:
            paths = new_config.get(key, [])
            paths.reverse()
            to_load.extend(paths)
            failures_ok.extend([failure_ok] * len(paths))

    for key in ['try_configs', 'use_configs']:
        if key in config:
            config.pop(key)

    return config

def get_content_file_path(path):
    if os.path.sep != '/':
        path.replace('/', os.path.sep)

    path = pathlib.Path(path)
    if path.is_absolute():
        raise ValueError(_('path_is_absolute_{}').format(path))

    return path

class MyNotImplError(NotImplementedError):
    '''Raised when a planned but not-yet-completed feature is used.'''
    def __init__(self, what, where):
        super().__init__(_('not_implemented_{what}_{where}')
                         .format(what=what, where=where))

def normalize_version(ver):
    '''
    ver is an array of integers. Strip right-most zeroes from ver.

    Returns a *new* array. Doesn't modify its argument.
    '''
    new_len = 0
    for i, num in enumerate(ver):
        if num != 0:
            new_len = i + 1

    return ver[:new_len]

def parse_version(ver_str):
    '''
    Convert ver_str into an array representation, e.g. for ver_str="4.6.13.0"
    return [4, 6, 13, 0].
    '''
    return [int(num) for num in ver_str.split('.')]

def version_string(ver, rev=None):
    '''
    ver is an array of integers. rev is an optional integer. Produce string
    representation of version (optionally with revision number), like:
        1.2.3-5
    No version normalization is performed.
    '''
    return '.'.join([str(n) for n in ver]) + ('' if rev is None else f'-{rev}')

class VersionedContentItem:
    '''Stores definitions of multiple versions of website content item.'''
    def __init__(self):
        self.uuid = None
        self.identifier = None
        self.by_version = {}
        self.known_versions = []

    def register_item(self, item):
        '''Make item queryable by version. Perform sanity checks for uuid.'''
        if self.identifier is None:
            self.identifier = item['identifier']
            self.uuid = item['uuid']
        elif self.uuid != item['uuid']:
            raise ValueError(_('uuid_mismatch_{identifier}')
                             .format(identifier=self.identifier))

        ver = item['version']
        ver_str = version_string(ver)

        if ver_str in self.by_version:
            raise ValueError(_('version_clash_{identifier}_{version}')
                             .format(identifier=self.identifier,
                                     version=ver_str))

        self.by_version[ver_str] = item
        self.known_versions.append(ver)

    def get_by_ver(self, ver=None):
        '''
        Find and return definition of the newest version of item.

        If ver is specified, instead find and return definition of that version
        of the item (or None is absent).
        '''
        ver = version_string(ver or self.known_versions[-1])

        return self.by_version.get(ver)

    def get_all(self):
        '''Return a list of all definitions of item, ordered by version.'''
        return [self.by_version[version_string(ver)]
                for ver in self.known_versions]

class PatternTreeNode:
    '''
    "Pattern Tree" is how we refer to the data structure used for querying
    Haketilo patterns. Those look like 'https://*.example.com/ab/***'. The goal
    is to make it possible for given URL to quickly retrieve all known patterns
    that match it.
    '''
    def __init__(self):
        self.wildcard_matches = [None, None, None]
        self.literal_match    = None
        self.children         = {}

    def search(self, segments):
        '''
        Yields all matches of this segments sequence against the tree that
        starts at this node. Results are produces in order from greatest to
        lowest pattern specificity.
        '''
        nodes = [self]

        for segment in segments:
            next_node = nodes[-1].children.get(segment)
            if next_node is None:
                break

            nodes.append(next_node)

        nsegments = len(segments)
        cond_literal = lambda: len(nodes)     == nsegments
        cond_wildcard = [
            lambda: len(nodes) + 1 == nsegments and segments[-1] != '*',
            lambda: len(nodes) + 1 <  nsegments,
            lambda: len(nodes) + 1 != nsegments or  segments[-1] != '***'
        ]

        while nodes:
            node = nodes.pop()

            for item, condition in [(node.literal_match, cond_literal),
                                    *zip(node.wildcard_matches, cond_wildcard)]:
                if item is not None and condition():
                    yield item

    def add(self, segments, item_instantiator):
        '''
        Make item queryable through (this branch of) the Pattern Tree. If there
        was not yet any item associated with the tree path designated by
        segments, create a new one using item_instantiator() function. Return
        all items matching this path (both the ones that existed and the ones
        just created).
        '''
        node = self

        for i, segment in enumerate(segments):
            wildcards = node.wildcard_matches

            child = node.children.get(segment) or PatternTreeNode()
            node.children[segment] = child
            node = child

        if node.literal_match is None:
            node.literal_match = item_instantiator()

        if segment not in ('*', '**', '***'):
            return [node.literal_match]

        if wildcards[len(segment) - 1] is None:
            wildcards[len(segment) - 1] = item_instantiator()

        return [node.literal_match, wildcards[len(segment) - 1]]

proto_regex  = re.compile(r'^(?P<proto>\w+)://(?P<rest>.*)$')
user_re      = r'[^/?#@]+@' # r'(?P<user>[^/?#@]+)@' # discarded for now
query_re     = r'\??[^#]*'  # r'\??(?P<query>[^#]*)' # discarded for now
domain_re    = r'(?P<domain>[^/?#]+)'
path_re      = r'(?P<path>[^?#]*)'
http_regex   = re.compile(f'{domain_re}{path_re}{query_re}.*')
ftp_regex    = re.compile(f'(?:{user_re})?{domain_re}{path_re}.*')

class UrlError(ValueError):
    pass

class DeconstructedUrl:
    '''Represents a deconstructed URL or URL pattern'''
    def __init__(self, url):
        self.url = url

        match = proto_regex.match(url)
        if not match:
            raise UrlError(_('invalid_URL_{}').format(url))

        self.proto = match.group('proto')
        if self.proto not in ('http', 'https', 'ftp'):
            raise UrlError(_('disallowed_protocol_{}').format(proto))

        if self.proto == 'ftp':
            match = ftp_regex.match(match.group('rest'))
        elif self.proto in ('http', 'https'):
            match = http_regex.match(match.group('rest'))

        if not match:
            raise UrlError(_('invalid_URL_{}').format(url))

        self.domain = match.group('domain').split('.')
        self.domain.reverse()
        self.path = [*filter(None, match.group('path').split('/'))]

class MappingItem:
    '''
    A mapping, together with one of its patterns, as stored in Pattern Tree.
    '''
    def __init__(self, pattern, mapping):
        self.pattern = pattern
        self.mapping = mapping

    def register(self, patterns_by_proto):
        '''
        Make self queryable through the Pattern Tree that starts with the
        protocols dictionary passed in the argument.
        '''
        deco = DeconstructedUrl(self.pattern)

        domain_tree = patterns_by_proto.get(deco.proto) or PatternTreeNode()
        patterns_by_proto[deco.proto] = domain_tree

        for path_tree in domain_tree.add(deco.domain, PatternTreeNode):
            for match_list in path_tree.add(deco.path, list):
                match_list.append(self)

class Content:
    '''Stores serveable website content.'''
    def __init__(self):
        self.resources = {}
        self.mappings  = {}
        self.licenses  = {}
        self.indexes   = {}
        self.definition_processors = {
            'resource': self.process_resource_or_mapping,
            'mapping': self.process_resource_or_mapping,
            'license': self.process_license
        }
        self.patterns_by_proto = {}

    @staticmethod
    def register_item(dict, item):
        '''
        Helper function used to add a versioned item definition to content
        data structures.
        '''
        identifier = item['identifier']
        versioned_item = dict.get(identifier)
        if versioned_item is None:
            versioned_item = VersionedContentItem()
            dict[identifier] = versioned_item

        versioned_item.register_item(item)

    @staticmethod
    def _process_copyright_and_license(definition):
        '''Helper function used by other process_*() methods.'''
        for field in ['copyright', 'licenses']:
            if definition[field] == 'auto':
                raise MyNotImplError(f'"{{field}}": "auto"',
                                     definition['source_name'])

    def process_resource_or_mapping(self, definition, index):
        '''
        Sanitizes, autocompletes and registers serveable mapping/resource
        definition.
        '''
        definition['version'] = normalize_version(definition['version'])

        if definition['type'] == 'resource':
            self._process_copyright_and_license(definition)
            definition['dependencies'] = definition.get('dependencies', [])
            self.register_item(self.resources, definition)
        else:
            self.register_item(self.mappings, definition)

    def process_license(self, license, index):
        '''Sanitizes and registers serveable license definition.'''
        identifier = license['identifier']
        if identifier in self.licenses:
            raise ValueError(_('license_clash_{}').format(identifier))

        self.licenses[identifier] = license

    def process_index(self, index, source_name):
        '''
        Sanitizes, autocompletes and registers data from a loaded index.json
        file.
        '''
        schema_ver = normalize_version(index['schema_version'])
        index['schema_version'] = schema_ver
        if schema_ver != SCHEMA_VERSION:
            raise ValueError('index_json_schema_mismatch_{found}_{required}'
                             .format(found=version_string(schema_ver),
                                     required=version_string(SCHEMA_VERSION)))

        if source_name in self.indexes:
            raise ValueError(_('source_name_clash_{}').format(source_name))

        index['source_name'] = source_name

        self._process_copyright_and_license(index)

        self.indexes[source_name] = index

        for definition in index['definitions']:
            try:
                definition['source_name'] = source_name
                definition['source_copyright'] = index['copyright']
                definition['source_licenses'] = index['licenses']
                processor = self.definition_processors[definition['type']]
                processor(definition, index)
            except Exception as e:
                if current_app._pydrilla_werror:
                    raise e from None
                logging.error(_('couldnt_load_definition_from_%s'), subdir_path,
                              exc_info=True)
    @staticmethod
    def all_items(versioned_items_dict):
        '''Iterator over all registered versions of all items.'''
        for versioned_item in versioned_items_dict.values():
            for item in versioned_item.by_version.values():
                yield item

    def report_missing(self):
        '''
        Use logger to print information about items that are referenced but
        were not loaded.
        '''
        def report_missing_license(object, object_type, lic):
            if object_type == 'index':
                logging.error(_('no_index_license_%(source)s_%(lic)s'),
                              source=object['source_name'], lic=lic)
                return

            ver_str = version_string(object['version'])
            kwargs = {object_type: object['identifier'], ver: ver_str, lic: lic}
            if object_type == 'resource':
                fmt = _('no_resource_license_%(resource)s_%(ver)s_%(lic)s')
            else:
                fmt = _('no_mapping_license_%(mapping)s_%(ver)s_%(lic)s')

            logging.error(fmt, **kwargs)

        for object_type, iterable in [
                ('index',    self.indexes.values()),
                ('resource', self.all_items(self.resources))
        ]:
            for object in iterable:
                to_process = [object['licenses']]
                licenses = []
                while to_process:
                    term = to_process.pop()

                    if type(term) is str:
                        if term not in ['or', 'and'] and \
                           term not in self.licenses:
                            report_missing_license(object, object_type, lic)
                        continue

                    to_process.extend(term)

        def report_missing_dependency(resource, dep):
            logging.error(_('no_dep_%(resource)s_%(ver)s_%(dep)s'),
                          dep=dep, resource=resource['identifier'],
                          ver=version_string(resource['version']))

        for resource in self.all_items(self.resources):
            for dep in resource['dependencies']:
                if dep not in self.resources:
                    report_missing_dependency(resource, dep)

        def report_missing_payload(mapping, payload):
            logging.error(_('no_payload_%(mapping)s_%(ver)s_%(payload)s'),
                          mapping=mapping['identifier'], payload=payload,
                          ver=version_string(mapping['version']))

        for mapping in self.all_items(self.mappings):
            for payload in mapping['payloads']:
                payload = payload['payload']
                if payload not in self.resources:
                    report_missing_payload(mapping, payload)

    def finalize(self):
        '''
        Initialize structures needed to serve queries. Called once after all
        data gets loaded.
        '''
        for dict in [self.resources, self.mappings]:
            for versioned_item in dict.values():
                versioned_item.known_versions.sort()

        for mapping in self.all_items(self.mappings):
            for payload in mapping['payloads']:
                pattern = payload['pattern']
                try:
                    MappingItem(pattern, mapping)\
                        .register(self.patterns_by_proto)
                except Exception as e:
                    if current_app._pydrilla_werror:
                        raise e from None
                    logging.error(
                        _('couldnt_register_%(mapping)s_%(ver)s_%(pattern)s'),
                        mapping=mapping['identifier'], pattern=pattern,
                        ver=version_string(mapping['version'])
                    )

    def query(self, url, max=0):
        '''
        Return return registered patterns and mappings (available as
        MappingItems) that match url. The maximum number of items yielded may be
        limited by using the optional max argument. Its default value, 0, causes
        no limit to be imposed.

        If multiple versions of a mapping are applicable, only the most recent
        is included in the result.
        '''
        deco = DeconstructedUrl(url)

        domain_tree = self.patterns_by_proto.get(deco.proto) \
            or PatternTreeNode()
        for path_tree in domain_tree.search(deco.domain):
            for item in path_tree.search(deco.path):
                if url[-1] == '/' or item.pattern[-1] != '/':
                    yield item
                    max -= 1
                    if max == 0:
                        return

def load_content_from_subdir(subdir_path, source_name, content):
    index_path = subdir_path / 'index.json'
    with open(index_path) as index_file:
        index = json.loads(strip_json_comments(index_file.read()))

    content.process_index(index, source_name)

def load_content(path):
    if not path.is_dir():
        raise ValueError(_('content_dir_path_not_dir'))

    content = Content()

    for subdir_path in path.iterdir():
        if not subdir_path.is_dir():
            continue
        try:
            load_content_from_subdir(subdir_path, subdir_path.name, content)
        except Exception as e:
            if current_app._pydrilla_werror:
                raise e from None
            logging.error(_('couldnt_load_content_from_%s'), subdir_path,
                          exc_info=True)

    content.report_missing()
    content.finalize()

    return content

def create_app(config_path=(here / 'config.json'), flask_config={}):
    app = Flask(__package__)
    app.config.update(flask_config)

    language = flask_config.get('lang', 'en')
    translation = gettext.translation('pydrilla', localedir=(here / 'locales'),
                                      languages=[language])

    app._pydrilla_gettext = translation.gettext

    # https://stackoverflow.com/questions/9449101/how-to-stop-flask-from-initialising-twice-in-debug-mode
    if app.debug and os.environ.get('WERKZEUG_RUN_MAIN') != 'true':
        return app

    config = load_config(config_path)
    for key in ['static_resource_uri', 'content_dir']:
        if key not in config:
            raise ValueError(_('config_key_absent_{}').format(key))

    app._pydrilla_static_resource_uri = config['static_resource_uri']
    app._pydrilla_werror = config.get('werror', False)
    if 'hydrilla_parent' in config:
        raise MyNotImplError('hydrilla_parent', config_path.name)

    content_dir = pathlib.Path(config['content_dir'])
    if not content_dir.is_absolute():
        content_dir = config_path.parent / content_dir
    with app.app_context():
        app._pydrilla_content = load_content(content_dir.resolve())

    app.register_blueprint(bp)

    return app

def _(text_key):
    return current_app._pydrilla_gettext(text_key)

def escaping_gettext(text_key):
    from markupsafe import escape

    return str(escape(_(text_key)))

def content():
    return current_app._pydrilla_content

class MyEnvironment(Environment):
    '''
    A wrapper class around jinja2.Environment that causes GNU gettext function
    (as '_' and '__') and url_for function to be passed to every call of each
    template's render() method.
    '''

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def get_template(self, *args, **kwargs):
        template = super().get_template(*args, **kwargs)
        old_render = template.render

        def new_render(*args, **kwargs):
            final_kwargs = {
                '_': escaping_gettext,
                '__': escaping_gettext,
                'url_for': url_for
            }
            final_kwargs.update(kwargs)

            return old_render(*args, **final_kwargs)

        template.render = new_render

        return template

j2env = MyEnvironment(loader=PackageLoader(__package__), autoescape=False)

indexpage = j2env.get_template('index.html')
@bp.route('/')
def index():
    return indexpage.render()

def get_resource_or_mapping(identifier, get_dict):
    ver = request.args.get('ver')
    versioned_item = get_dict().get(identifier)

    if ver == 'all':
        definition = versioned_item.get_all() if versioned_item else []
    else:
        if ver is not None:
            try:
                ver = normalize_version(parse_version(ver))
            except:
                abort(400)

        definition = versioned_item and versioned_item.get_by_ver(ver)
        if definition is None:
            abort(404)

    return json.dumps(definition)

def get_license_or_source(identifier, get_dict):
    definition = get_dict().get(identifier)
    if definition is None:
        abort(404)

    return json.dumps(definition)

for item_type, get_dict, get_item in [
        ('resource', lambda: content().resources, get_resource_or_mapping),
        ('mapping',  lambda: content().mappings,  get_resource_or_mapping),
        ('license',  lambda: content().licenses,  get_license_or_source),
        ('source',   lambda: content().indexes,   get_license_or_source)
]:
    def _get_item(identifier, get_dict=get_dict, get_item=get_item):
        return get_item(identifier, get_dict)

    bp.add_url_rule(f'/{item_type}s/<string:identifier>', item_type, _get_item)