Пример #1
0
def makeSelfLink(req, params):
    params2 = req.params.copy()
    for k, v in params.items():
        if v is not None:
            params2[k] = v
        else:
            with _suppress(Exception, warn=False):
                del params2[k]
    ret = _build_url_from_path_and_params(req.fullpath, params2)
    return ret
Пример #2
0
def sendAsBuffer(req, text, content_type, force=0, allow_cross_origin=False):
    stringio = _StringIO(text)
    try:
        file_length = len(stringio.buf)
    except OSError:
        error(req, 404)
        return

    ims = get_header_match(IF_MODIFIED_SINCE, req.header)
    length_match = 1
    if ims:
        length = ims.group(4)
        if length:
            with _suppress(Exception, warn=False):
                length = _string.atoi(length)
                if length != file_length:
                    length_match = 0

    ims_date = 0
    if ims:
        ims_date = parse_http_date(ims.group(1))

    try:
        import time
        mtime = _time.time()  # _os.stat (path)[stat.ST_MTIME]
    except:
        error(req, 404)
        return

    if length_match and ims_date:
        if mtime <= ims_date and not force:
            req.reply_code = 304
            return
    try:
        file = stringio
    except IOError:
        error(req, 404)
        return

    req.reply_headers['Last-Modified'] = build_http_date(mtime)
    req.reply_headers['Content-Length'] = file_length
    req.reply_headers['Content-Type'] = content_type
    if allow_cross_origin:
        req.reply_headers['Access-Control-Allow-Origin'] = '*'
    if req.command == 'GET':
        req.push(_athana.file_producer(file))
    return
Пример #3
0
 def cwd(self, path):
     p = self.normalize(self.path_module.join(self.wd, path))
     translated_path = self.translate(p)
     if not self.path_module.isdir(translated_path):
         return 0
     else:
         old_dir = _os.getcwd()
         # temporarily change to that directory, in order
         # to see if we have permission to do so.
         try:
             can = 0
             with _suppress(Exception, warn=False):
                 _os.chdir(translated_path)
                 can = 1
                 self.wd = p
         finally:
             if can:
                 _os.chdir(old_dir)
         return can
Пример #4
0
def sendFile(req,
             path,
             content_type,
             force=0,
             nginx_x_accel_redirect_enabled=True):
    if isinstance(path, unicode):
        path = path.encode("utf8")

    if isinstance(content_type, unicode):
        content_type = content_type.encode("utf8")

    x_accel_redirect = _config.get(
        "nginx.X-Accel-Redirect",
        "").lower() == "true" and nginx_x_accel_redirect_enabled
    file = None
    file_length = 0

    if not x_accel_redirect:
        try:
            file_length = _os.stat(path)[_stat.ST_SIZE]
        except OSError:
            error(req, 404)
            return

    ims = get_header_match(IF_MODIFIED_SINCE, req.header)
    length_match = 1
    if ims:
        length = ims.group(4)
        if length:
            with _suppress(Exception, warn=False):
                length = _string.atoi(length)
                if length != file_length:
                    length_match = 0

    ims_date = 0
    if ims:
        ims_date = parse_http_date(ims.group(1))

    try:
        mtime = _os.stat(path)[_stat.ST_MTIME]
    except:
        error(req, 404)
        return
    if length_match and ims_date:
        if mtime <= ims_date and not force:
            # print "File "+path+" was not modified since "+ustr(ims_date)+" (current filedate is "+ustr(mtime)+")-> 304"
            req.reply_code = 304
            return

    if not x_accel_redirect:
        try:
            file = open(path, 'rb')
        except IOError:
            error(req, 404)
            print "404"
            return

    req.reply_headers['Last-Modified'] = build_http_date(mtime)
    req.reply_headers['Content-Length'] = file_length
    req.reply_headers['Content-Type'] = content_type
    if x_accel_redirect:
        req.reply_headers['X-Accel-Redirect'] = path
    if req.command == 'GET':
        if x_accel_redirect:
            done(req)
        else:
            req.push(_athana.file_producer(file))
    return
Пример #5
0
def handle_request(handler, request, form):

    global session_cookies_live_secs, session_check_period, last_session_check_time

    act_time = _time.time()
    path, params, query, fragment = split_uri(request)

    ip = request.request_headers.get("x-forwarded-for", None)
    if ip is None:
        with _suppress(Exception, warn=False):
            ip = request.channel.addr[0]
    if ip:
        request.channel.addr = (ip, request.channel.addr[1])

    request.log()

    # COMPAT: new param style like flask
    if query is not None:
        args = _athana.AthanaHandler.parse_query(query)
    else:
        args = []
    # /COMPAT
    path = _urllib.unquote(path)
    if params is not None:
        params = _urllib.unquote(params)
    if fragment is not None:
        fragment = _urllib.unquote(fragment)

    cookies = {}
    if "cookie" in request.request_headers:
        cookiestr = request.request_headers["cookie"]
        if cookiestr.rfind(";") == len(cookiestr) - 1:
            cookiestr = cookiestr[:-1]
        items = cookiestr.split(';')
        for a in items:
            a = a.strip()
            i = a.find('=')
            if i > 0:
                key, value = a[:i], a[i + 1:]
                cookies[key] = value
            else:
                _logg.warn("corrupt cookie value: %s",
                           a.encode("string-escape"))

    request.Cookies = cookies

    sessionid = None

    if "PSESSION" in cookies:
        sessionid = cookies["PSESSION"]

    session_expiration_time = act_time - session_cookies_live_secs
    session = None
    if sessionid is None:

        if act_time - last_session_check_time > session_check_period:
            # delete all sessions with lastuse older than act_time - session_cookies_live_secs
            sessionids_to_be_deleted = [
                sid for sid in handler.sessions
                if handler.sessions[sid].lastuse < session_expiration_time
            ]
            for sid in sessionids_to_be_deleted:
                del handler.sessions[sid]
            last_session_check_time = act_time

        sessionid = handler.create_session_id()
        _logg.debug("Creating new session %s", sessionid)

    else:
        if sessionid in handler.sessions:
            session = handler.sessions[sessionid]
            if session.lastuse < session_expiration_time:
                del handler.sessions[sessionid]
                session = None
            else:
                session.use()

    if session is None:
        session = _athana.Session(sessionid)
        handler.sessions[sessionid] = session

    request['Content-Type'] = 'text/html; encoding=utf-8; charset=utf-8'

    maxlen = -1
    context = None
    global contexts
    for c in contexts:
        if path.startswith(c.name) and len(c.name) > maxlen:
            context = c
            maxlen = len(context.name)

    if context is None:
        error(request, 404)
        return

    fullpath = path
    path = path[len(context.name):]
    if len(path) == 0 or path[0] != '/':
        path = "/" + path

    request.session = session
    request.sessionid = sessionid
    request.context = context
    request.path = path
    request.fullpath = fullpath
    request.paramstring = params
    request.query = query
    request.fragment = fragment

    # COMPAT: new param style like flask
    # we don't need this for WSGI, args / form parsing is done by the WSGI app
    if not isinstance(context, _athana.WSGIContext):
        form, files = _athana.filter_out_files(form)
        try:
            request.args = make_param_dict_utf8_values(args)
            if "csrf_token" in request.args:
                form.append(('csrf_token', str(request.args["csrf_token"])))
            request.form = make_param_dict_utf8_values(form)
        except UnicodeDecodeError:
            return error(request, 400)

        if form and request.method == 'POST':
            if 'csrf_token' not in request.form:
                raise ValueError("csrf_token not in form of request path " +
                                 request.fullpath)
            else:
                session.mediatum_form.csrf_token.process_data(
                    request.form["csrf_token"].replace("!!!!!", "##"))
                session.mediatum_form.validate()

        request.csrf_token = session.mediatum_form.csrf_token
        request.files = _ImmutableMultiDict(files)
        make_legacy_params_dict(request)

    # /COMPAT
    request.request = request
    request.ip = ip
    request.uri = request.uri.replace(context.name, "/")
    request._split_uri = None

    request.channel.current_request = None

    if path == "/threadstatus":
        return _athana.thread_status(request)
    if path == "/profilingstatus":
        return _athana.profiling_status(request)

    function = context.match(path)

    if function is None:
        _logg.debug("Request %s matches no pattern (context: %s)",
                    request.path, context.name)
        request.path = _escape(request.path)
        return error(request, 404, "File %s not found" % request.path)
    if _athana.multithreading_enabled:
        handler.queuelock.acquire()
        handler.queue += [(function, request)]
        handler.queuelock.release()
    else:
        _athana.call_handler_func(function, request)
Пример #6
0
    def handle_request(self, request):

        if request.command not in self.valid_commands:
            error(request, 400)  # bad request
            return

        self.hit_counter.increment()
        path, params, query, fragment = split_uri(request)

        if '%' in path:
            path = _urllib.unquote(path)

        # strip off all leading slashes
        while path and path[0] == '/':
            path = path[1:]

        if self.filesystem.isdir(path):
            if path and path[-1] != '/':
                request['Location'] = 'http://%s/%s/' % (
                    request.channel.server.server_name, path)
                error(request, 301)
                return

            # we could also generate a directory listing here,
            # may want to move this into another method for that
            # purpose
            found = 0
            if path and path[-1] != '/':
                path = path + '/'
            for default in self.directory_defaults:
                p = path + default
                if self.filesystem.isfile(p):
                    path = p
                    found = 1
                    break
            if not found:
                error(request, 404)  # Not Found
                return

        elif not self.filesystem.isfile(path):
            error(request, 404)  # Not Found
            return

        file_length = self.filesystem.stat(path)[_stat.ST_SIZE]

        ims = get_header_match(IF_MODIFIED_SINCE, request.header)

        length_match = 1
        if ims:
            length = ims.group(4)
            if length:
                with _suppress(Exception, warn=False):
                    length = _string.atoi(length)
                    if length != file_length:
                        length_match = 0
        ims_date = 0

        if ims:
            ims_date = parse_http_date(ims.group(1))

        try:
            mtime = self.filesystem.stat(path)[_stat.ST_MTIME]
        except:
            error(request, 404)
            return

        if length_match and ims_date:
            if mtime <= ims_date:
                request.reply_code = 304
                done(request)
                self.cache_counter.increment()
                # print "File "+path+" was not modified since "+ustr(ims_date)+" (current filedate is "+ustr(mtime)+")"
                return
        try:
            file = self.filesystem.open(path, 'rb')
        except IOError:
            error(request, 404)
            return

        request['Last-Modified'] = build_http_date(mtime)
        request['Content-Length'] = file_length
        self.set_content_type(path, request)

        if request.command == 'GET':
            request.push(self.default_file_producer(file))

        self.file_counter.increment()
        done(request)