This file is indexed.

/usr/share/pyshared/zope/browserresource/file.py is in python-zope.browserresource 3.12.0-0ubuntu1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
##############################################################################
#
# Copyright (c) 2002 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""File-based browser resources.
"""

import os
import time
import re
try:
    from email.utils import formatdate, parsedate_tz, mktime_tz
except ImportError: # python 2.4
    from email.Utils import formatdate, parsedate_tz, mktime_tz

from zope.contenttype import guess_content_type
from zope.interface import implements, classProvides
from zope.component import adapts, getMultiAdapter
from zope.publisher.browser import BrowserView
from zope.publisher.interfaces import NotFound
from zope.publisher.interfaces.browser import IBrowserRequest
from zope.publisher.interfaces.browser import IBrowserPublisher

from zope.browserresource.resource import Resource
from zope.browserresource.interfaces import IETag
from zope.browserresource.interfaces import IFileResource
from zope.browserresource.interfaces import IResourceFactory
from zope.browserresource.interfaces import IResourceFactoryFactory


ETAG_RX = re.compile(r'[*]|(?:W/)?"(?:[^"\\]|[\\].)*"')


def parse_etags(value):
    r"""Parse a list of entity tags.

    HTTP/1.1 specifies the following syntax for If-Match/If-None-Match
    headers::

        If-Match = "If-Match" ":" ( "*" | 1#entity-tag )
        If-None-Match = "If-None-Match" ":" ( "*" | 1#entity-tag )

        entity-tag = [ weak ] opaque-tag

        weak       = "W/"
        opaque-tag = quoted-string

        quoted-string  = ( <"> *(qdtext) <"> )
        qdtext         = <any TEXT except <">>

        The backslash character ("\") may be used as a single-character
        quoting mechanism only within quoted-string and comment constructs.

    Examples:

        >>> parse_etags('*')
        ['*']

        >>> parse_etags(r' "qwerty", ,"foo",W/"bar" , "baz","\""')
        ['"qwerty"', '"foo"', 'W/"bar"', '"baz"', '"\\""']

    Ill-formed headers are ignored

        >>> parse_etags("not an etag at all")
        []

    """
    return ETAG_RX.findall(value)


def etag_matches(etag, tags):
    """Check if the entity tag matches any of the given tags.

        >>> etag_matches('"xyzzy"', ['"abc"', '"xyzzy"', 'W/"woof"'])
        True

        >>> etag_matches('"woof"', ['"abc"', 'W/"woof"'])
        False

        >>> etag_matches('"xyzzy"', ['*'])
        True

    Note that you pass quoted etags in both arguments!
    """
    for tag in tags:
        if tag == etag or tag == '*':
            return True
    return False


def quote_etag(etag):
    r"""Quote an etag value

        >>> quote_etag("foo")
        '"foo"'

    Special characters are escaped

        >>> quote_etag('"')
        '"\\""'
        >>> quote_etag('\\')
        '"\\\\"'

    """
    return '"%s"' % etag.replace('\\', '\\\\').replace('"', '\\"')


class File(object):

    def __init__(self, path, name):
        self.path = path
        self.__name__ = name
        f = open(path, 'rb')
        self.data = f.read()
        f.close()
        self.content_type = guess_content_type(path, self.data)[0]

        self.lmt = float(os.path.getmtime(path)) or time.time()
        self.lmh = formatdate(self.lmt, usegmt=True)


class FileResource(BrowserView, Resource):

    implements(IFileResource, IBrowserPublisher)

    cacheTimeout = 86400

    def publishTraverse(self, request, name):
        '''File resources can't be traversed further, so raise NotFound if
        someone tries to traverse it.

          >>> factory = FileResourceFactory(testFilePath, nullChecker, 'test.txt')
          >>> request = TestRequest()
          >>> resource = factory(request)
          >>> resource.publishTraverse(request, '_testData')
          Traceback (most recent call last):
          ...
          NotFound: Object: None, name: '_testData'

        '''
        raise NotFound(None, name)

    def browserDefault(self, request):
        '''Return a callable for processing browser requests.

          >>> factory = FileResourceFactory(testFilePath, nullChecker, 'test.txt')
          >>> request = TestRequest(REQUEST_METHOD='GET')
          >>> resource = factory(request)
          >>> view, next = resource.browserDefault(request)
          >>> view() == open(testFilePath, 'rb').read()
          True
          >>> next == ()
          True

          >>> request = TestRequest(REQUEST_METHOD='HEAD')
          >>> resource = factory(request)
          >>> view, next = resource.browserDefault(request)
          >>> view() == ''
          True
          >>> next == ()
          True

        '''
        return getattr(self, request.method), ()

    def chooseContext(self):
        '''Choose the appropriate context.

        This method can be overriden in subclasses, that need to choose
        appropriate file, based on current request or other condition,
        like, for example, i18n files.

        '''
        return self.context

    def GET(self):
        '''Return a file data for downloading with GET requests

          >>> factory = FileResourceFactory(testFilePath, nullChecker, 'test.txt')
          >>> request = TestRequest()
          >>> resource = factory(request)
          >>> resource.GET() == open(testFilePath, 'rb').read()
          True
          >>> request.response.getHeader('Content-Type') == 'text/plain'
          True

        '''

        file = self.chooseContext()
        request = self.request
        response = request.response

        etag = getMultiAdapter((self, request), IETag)(file.lmt, file.data)

        setCacheControl(response, self.cacheTimeout)

        can_return_304 = False
        all_cache_checks_passed = True

        # HTTP If-Modified-Since header handling. This is duplicated
        # from OFS.Image.Image - it really should be consolidated
        # somewhere...
        header = request.getHeader('If-Modified-Since', None)
        if header is not None:
            can_return_304 = True
            header = header.split(';')[0]
            # Some proxies seem to send invalid date strings for this
            # header. If the date string is not valid, we ignore it
            # rather than raise an error to be generally consistent
            # with common servers such as Apache (which can usually
            # understand the screwy date string as a lucky side effect
            # of the way they parse it).
            try:
                mod_since = long(mktime_tz(parsedate_tz(header)))
            except:
                mod_since = None
            if getattr(file, 'lmt', None):
                last_mod = long(file.lmt)
            else:
                last_mod = 0L
            if mod_since is None or last_mod <= 0 or last_mod > mod_since:
                all_cache_checks_passed = False

        # HTTP If-None-Match header handling
        header = request.getHeader('If-None-Match', None)
        if header is not None:
            can_return_304 = True
            tags = parse_etags(header)
            if not etag or not etag_matches(quote_etag(etag), tags):
                all_cache_checks_passed = False

        # 304 responses MUST contain ETag, if one would've been sent with
        # a 200 response
        if etag:
            response.setHeader('ETag', quote_etag(etag))

        if can_return_304 and all_cache_checks_passed:
            response.setStatus(304)
            return ''

        # 304 responses SHOULD NOT or MUST NOT include other entity headers,
        # depending on whether the conditional GET used a strong or a weak
        # validator.  We only use strong validators, which makes it SHOULD
        # NOT.
        response.setHeader('Content-Type', file.content_type)
        response.setHeader('Last-Modified', file.lmh)

        return file.data

    def HEAD(self):
        '''Return proper headers and no content for HEAD requests

          >>> factory = FileResourceFactory(testFilePath, nullChecker, 'test.txt')
          >>> request = TestRequest()
          >>> resource = factory(request)
          >>> resource.HEAD() == ''
          True
          >>> request.response.getHeader('Content-Type') == 'text/plain'
          True

        '''
        file = self.chooseContext()
        etag = getMultiAdapter((self, self.request), IETag)(file.lmt, file.data)
        response = self.request.response
        response.setHeader('Content-Type', file.content_type)
        response.setHeader('Last-Modified', file.lmh)
        if etag:
            response.setHeader('ETag', etag)
        setCacheControl(response, self.cacheTimeout)
        return ''

    # for unit tests
    def _testData(self):
        f = open(self.context.path, 'rb')
        data = f.read()
        f.close()
        return data


class FileETag(object):

    adapts(IFileResource, IBrowserRequest)
    implements(IETag)

    def __init__(self, context, request):
        self.context = context
        self.request = request

    def __call__(self, mtime, content):
        return '%s-%s' % (mtime, len(content))


def setCacheControl(response, secs=86400):
    # Cache for one day by default
    response.setHeader('Cache-Control', 'public,max-age=%s' % secs)
    t = time.time() + secs
    response.setHeader('Expires', formatdate(t, usegmt=True))


class FileResourceFactory(object):

    resourceClass = FileResource

    implements(IResourceFactory)
    classProvides(IResourceFactoryFactory)

    def __init__(self, path, checker, name):
        self.__file = File(path, name)
        self.__checker = checker
        self.__name = name

    def __call__(self, request):
        resource = self.resourceClass(self.__file, request)
        resource.__Security_checker__ = self.__checker
        resource.__name__ = self.__name
        return resource