Beispiel #1
0
    def GET_document(self):
        try:
            c.errors = c.errors or ErrorSet()
            # clear cookies the old fashioned way
            c.cookies = Cookies()

            code = request.GET.get('code', '')
            try:
                code = int(code)
            except ValueError:
                code = 404
            srname = request.GET.get('srname', '')
            takedown = request.GET.get('takedown', "")

            # StatusBasedRedirect will override this anyway, but we need this
            # here for pagecache to see.
            response.status_int = code

            if srname:
                c.site = Subreddit._by_name(srname)

            if request.GET.has_key('allow_framing'):
                c.allow_framing = bool(request.GET['allow_framing'] == '1')

            if code in (204, 304):
                # NEVER return a content body on 204/304 or downstream
                # caches may become very confused.
                if request.GET.has_key('x-sup-id'):
                    x_sup_id = request.GET.get('x-sup-id')
                    if '\r\n' not in x_sup_id:
                        response.headers['x-sup-id'] = x_sup_id
                return ""
            elif c.render_style not in self.allowed_render_styles:
                return str(code)
            elif c.render_style in extensions.API_TYPES:
                data = request.environ.get('extra_error_data', {'error': code})
                if request.environ.get("WANT_RAW_JSON"):
                    return scriptsafe_dumps(data)
                return websafe_json(json.dumps(data))
            elif takedown and code == 404:
                link = Link._by_fullname(takedown)
                return pages.TakedownPage(link).render()
            elif code == 403:
                return self.send403()
            elif code == 429:
                return self.send429()
            elif code == 500:
                randmin = {'admin': random.choice(self.admins)}
                failien_url = make_failien_url()
                sad_message = safemarkdown(rand_strings.sadmessages % randmin)
                return redditbroke % (failien_url, sad_message)
            elif code == 503:
                return self.send503()
            elif c.site:
                return self.send404()
            else:
                return "page not found"
        except Exception as e:
            return handle_awful_failure("ErrorController.GET_document: %r" % e)
Beispiel #2
0
    def GET_document(self):
        try:
            c.errors = c.errors or ErrorSet()
            # clear cookies the old fashioned way 
            c.cookies = Cookies()

            code =  request.GET.get('code', '')
            try:
                code = int(code)
            except ValueError:
                code = 404
            srname = request.GET.get('srname', '')
            takedown = request.GET.get('takedown', "")

            # StatusBasedRedirect will override this anyway, but we need this
            # here for pagecache to see.
            response.status_int = code

            if srname:
                c.site = Subreddit._by_name(srname)

            if request.GET.has_key('allow_framing'):
                c.allow_framing = bool(request.GET['allow_framing'] == '1')

            if code in (204, 304):
                # NEVER return a content body on 204/304 or downstream
                # caches may become very confused.
                if request.GET.has_key('x-sup-id'):
                    x_sup_id = request.GET.get('x-sup-id')
                    if '\r\n' not in x_sup_id:
                        response.headers['x-sup-id'] = x_sup_id
                return ""
            elif c.render_style not in self.allowed_render_styles:
                return str(code)
            elif c.render_style in extensions.API_TYPES:
                data = request.environ.get('extra_error_data', {'error': code})
                if request.environ.get("WANT_RAW_JSON"):
                    return scriptsafe_dumps(data)
                return websafe_json(json.dumps(data))
            elif takedown and code == 404:
                link = Link._by_fullname(takedown)
                return pages.TakedownPage(link).render()
            elif code == 403:
                return self.send403()
            elif code == 429:
                return self.send429()
            elif code == 500:
                randmin = {'admin': random.choice(self.admins)}
                failien_url = make_failien_url()
                sad_message = safemarkdown(rand_strings.sadmessages % randmin)
                return redditbroke % (failien_url, sad_message)
            elif code == 503:
                return self.send503()
            elif c.site:
                return self.send404()
            else:
                return "page not found"
        except Exception as e:
            return handle_awful_failure("ErrorController.GET_document: %r" % e)
Beispiel #3
0
def _wsgi_json(start_response, status_int, message=""):
    status_message = webob.util.status_reasons[status_int]
    message = message or status_message

    start_response("%s %s" % (status_int, status_message), [("Content-Type", "application/json")])

    data = simplejson.dumps({"error": status_int, "message": message})
    return [filters.websafe_json(data).encode("utf-8")]
Beispiel #4
0
def json_respond(x):
    from pylons import c
    if get_api_subtype():
        res = JsonResponse()
        res.object = tup(x)
        res = dict(res)
    else:
        res = x or ''
    return websafe_json(simplejson.dumps(res))
Beispiel #5
0
 def iframe_api_wrapper(self, kw):
     data = simplejson.dumps(kw)
     c.response_content_type = 'text/html'
     c.response.content = (
         '<html><head><script type="text/javascript">\n'
         'parent.$.handleResponse().call('
         'parent.$("#" + window.frameElement.id).parent(), %s)\n'
         '</script></head></html>') % filters.websafe_json(data)
     return c.response
Beispiel #6
0
 def iframe_api_wrapper(self, kw):
     data = simplejson.dumps(kw)
     c.response_content_type = 'text/html'
     c.response.content = (
         '<html><head><script type="text/javascript">\n'
         'parent.$.handleResponse().call('
         'parent.$("#" + window.frameElement.id).parent(), %s)\n'
         '</script></head></html>') % filters.websafe_json(data)
     return c.response
Beispiel #7
0
def _wsgi_json(start_response, status_int, message=""):
    status_message = webob.util.status_reasons[status_int]
    message = message or status_message

    start_response("%s %s" % (status_int, status_message),
                   [("Content-Type", "application/json")])

    data = simplejson.dumps({"error": status_int, "message": message})
    return [filters.websafe_json(data).encode("utf-8")]
Beispiel #8
0
    def GET_document(self):
        try:
            c.errors = c.errors or ErrorSet()
            # clear cookies the old fashioned way
            c.cookies = Cookies()

            code = request.GET.get("code", "")
            try:
                code = int(code)
            except ValueError:
                code = 404
            srname = request.GET.get("srname", "")
            takedown = request.GET.get("takedown", "")

            # StatusBasedRedirect will override this anyway, but we need this
            # here for pagecache to see.
            response.status_int = code

            if srname:
                c.site = Subreddit._by_name(srname)

            if code in (204, 304):
                # NEVER return a content body on 204/304 or downstream
                # caches may become very confused.
                if request.GET.has_key("x-sup-id"):
                    x_sup_id = request.GET.get("x-sup-id")
                    if "\r\n" not in x_sup_id:
                        response.headers["x-sup-id"] = x_sup_id
                return ""
            elif c.render_style not in self.allowed_render_styles:
                return str(code)
            elif c.render_style in extensions.API_TYPES:
                data = request.environ.get("extra_error_data", {"error": code})
                return websafe_json(json.dumps(data))
            elif takedown and code == 404:
                link = Link._by_fullname(takedown)
                return pages.TakedownPage(link).render()
            elif code == 403:
                return self.send403()
            elif code == 429:
                return self.send429()
            elif code == 500:
                randmin = {"admin": random.choice(self.admins)}
                failien_url = make_failien_url()
                return redditbroke % (failien_url, rand_strings.sadmessages % randmin)
            elif code == 503:
                return self.send503()
            elif c.site:
                return self.send404()
            else:
                return "page not found"
        except:
            return handle_awful_failure("something really bad just happened.")
Beispiel #9
0
def responsive(res, space_compress=None):
    """
    Use in places where the template is returned as the result of the
    controller so that it becomes compatible with the page cache.
    """
    if space_compress is None:
        space_compress = not g.template_debug

    if is_api():
        res = res or u''
        if not c.allowed_callback and request.environ.get("WANT_RAW_JSON"):
            res = scriptsafe_dumps(res)
        else:
            res = websafe_json(simplejson.dumps(res))

        if c.allowed_callback:
            # Add a comment to the beginning to prevent the "Rosetta Flash"
            # XSS when an attacker controls the beginning of a resource
            res = "/**/%s(%s)" % (websafe_json(c.allowed_callback), res)
    elif space_compress:
        res = spaceCompress(res)
    return res
Beispiel #10
0
    def GET_document(self):
        try:
            c.errors = c.errors or ErrorSet()
            # clear cookies the old fashioned way 
            c.cookies = Cookies()

            code =  request.GET.get('code', '')
            try:
                code = int(code)
            except ValueError:
                code = 404
            srname = request.GET.get('srname', '')
            takedown = request.GET.get('takedown', "")
            
            if srname:
                c.site = Subreddit._by_name(srname)
            if c.render_style not in self.allowed_render_styles:
                if code not in (204, 304):
                     c.response.content = str(code)
                c.response.status_code = code
                return c.response
            elif c.render_style in extensions.API_TYPES:
                data = request.environ.get('extra_error_data', {'error': code})
                c.response.content = websafe_json(json.dumps(data))
                return c.response
            elif takedown and code == 404:
                link = Link._by_fullname(takedown)
                return pages.TakedownPage(link).render()
            elif code == 403:
                return self.send403()
            elif code == 429:
                return self.send429()
            elif code == 500:
                randmin = {'admin': rand.choice(self.admins)}
                failien_name = 'youbrokeit%d.png' % rand.randint(1, NUM_FAILIENS)
                failien_url = static(failien_name)
                return redditbroke % (failien_url, rand_strings.sadmessages % randmin)
            elif code == 503:
                return self.send503()
            elif code == 304:
                if request.GET.has_key('x-sup-id'):
                    x_sup_id = request.GET.get('x-sup-id')
                    if '\r\n' not in x_sup_id:
                        c.response.headers['x-sup-id'] = x_sup_id
                return c.response
            elif c.site:
                return self.send404()
            else:
                return "page not found"
        except:
            return handle_awful_failure("something really bad just happened.")
Beispiel #11
0
def send_broadcast(namespace, type, payload):
    """Broadcast an object to all WebSocket listeners in a namespace.

    The message type is used to differentiate between different kinds of
    payloads that may be sent. The payload will be encoded as a JSON object
    before being sent to the client.

    """
    frame = {
        "type": type,
        "payload": payload,
    }
    amqp.add_item(routing_key=namespace, body=websafe_json(json.dumps(frame)),
                  exchange=_WEBSOCKET_EXCHANGE)
Beispiel #12
0
    def GET_document(self):
        try:
            c.errors = c.errors or ErrorSet()
            # clear cookies the old fashioned way 
            c.cookies = Cookies()

            code =  request.GET.get('code', '')
            try:
                code = int(code)
            except ValueError:
                code = 404
            srname = request.GET.get('srname', '')
            takedown = request.GET.get('takedown', "")
            
            if srname:
                c.site = Subreddit._by_name(srname)

            if code in (204, 304):
                # NEVER return a content body on 204/304 or downstream
                # caches may become very confused.
                if request.GET.has_key('x-sup-id'):
                    x_sup_id = request.GET.get('x-sup-id')
                    if '\r\n' not in x_sup_id:
                        response.headers['x-sup-id'] = x_sup_id
                return ""
            elif c.render_style not in self.allowed_render_styles:
                return str(code)
            elif c.render_style in extensions.API_TYPES:
                data = request.environ.get('extra_error_data', {'error': code})
                return websafe_json(json.dumps(data))
            elif takedown and code == 404:
                link = Link._by_fullname(takedown)
                return pages.TakedownPage(link).render()
            elif code == 403:
                return self.send403()
            elif code == 429:
                return self.send429()
            elif code == 500:
                randmin = {'admin': random.choice(self.admins)}
                failien_url = make_failien_url()
                return redditbroke % (failien_url, rand_strings.sadmessages % randmin)
            elif code == 503:
                return self.send503()
            elif c.site:
                return self.send404()
            else:
                return "page not found"
        except:
            return handle_awful_failure("something really bad just happened.")
Beispiel #13
0
def send_broadcast(namespace, type, payload):
    """Broadcast an object to all WebSocket listeners in a namespace.

    The message type is used to differentiate between different kinds of
    payloads that may be sent. The payload will be encoded as a JSON object
    before being sent to the client.

    """
    frame = {
        "type": type,
        "payload": payload,
    }
    amqp.add_item(routing_key=namespace,
                  body=websafe_json(json.dumps(frame)),
                  exchange=_WEBSOCKET_EXCHANGE)
Beispiel #14
0
 def sendstring(self,string):
     '''sends a string and automatically escapes &, < and > to make sure no code injection happens'''
     c.response.headers['Content-Type'] = 'text/html; charset=UTF-8'
     c.response.content = filters.websafe_json(string)
     return c.response
Beispiel #15
0
 def use(self):
     from r2.lib.filters import SC_OFF, SC_ON, websafe_json
     escaped_json = websafe_json(self.get_source())
     return (SC_OFF + inline_script_tag.format(content=escaped_json) +
             SC_ON + "\n")
Beispiel #16
0
    def GET_document(self):
        try:
            c.errors = c.errors or ErrorSet()
            # clear cookies the old fashioned way 
            c.cookies = Cookies()

            code =  request.GET.get('code', '')
            try:
                code = int(code)
            except ValueError:
                code = 404
            srname = request.GET.get('srname', '')
            takedown = request.GET.get('takedown', '')
            error_name = request.GET.get('error_name', '')

            if isinstance(c.user, basestring):
                # somehow requests are getting here with c.user unset
                c.user_is_loggedin = False
                c.user = UnloggedUser(browser_langs=None)

            if srname:
                c.site = Subreddit._by_name(srname)

            if request.GET.has_key('allow_framing'):
                c.allow_framing = bool(request.GET['allow_framing'] == '1')

            if (error_name == 'IN_TIMEOUT' and
                    not 'usable_error_content' in request.environ):
                timeout_days_remaining = c.user.days_remaining_in_timeout

                errpage = pages.InterstitialPage(
                    _("suspended"),
                    content=pages.InTimeoutInterstitial(
                        timeout_days_remaining=timeout_days_remaining,
                    ),
                )
                request.environ['usable_error_content'] = errpage.render()

            if code in (204, 304):
                # NEVER return a content body on 204/304 or downstream
                # caches may become very confused.
                return ""
            elif c.render_style not in self.allowed_render_styles:
                return str(code)
            elif c.render_style in extensions.API_TYPES:
                data = request.environ.get('extra_error_data', {'error': code})
                message = request.GET.get('message', '')
                if message:
                    data['message'] = message
                if request.environ.get("WANT_RAW_JSON"):
                    return scriptsafe_dumps(data)
                return websafe_json(json.dumps(data))
            elif takedown and code == 404:
                link = Link._by_fullname(takedown)
                return pages.TakedownPage(link).render()
            elif code == 400:
                return self.send400()
            elif code == 403:
                return self.send403()
            elif code == 429:
                return self.send429()
            elif code == 500:
                failien_url = make_failien_url()
                sad_message = get_funny_translated_string("500_page")
                sad_message %= {'admin': random.choice(self.admins)}
                sad_message = safemarkdown(sad_message)
                return redditbroke % (failien_url, sad_message)
            elif code == 503:
                return self.send503()
            elif c.site:
                return self.send404()
            else:
                return "page not found"
        except Exception as e:
            return handle_awful_failure("ErrorController.GET_document: %r" % e)
Beispiel #17
0
def json_respond(x):
    if g.debug:
        return websafe_json(simplejson.dumps(x or '',
                                             sort_keys=True, indent=4))
    else:
        return websafe_json(simplejson.dumps(x or ''))
Beispiel #18
0
def json_respond(x):
    if g.debug:
        return websafe_json(simplejson.dumps(x or '', sort_keys=True,
                                             indent=4))
    else:
        return websafe_json(simplejson.dumps(x or ''))
Beispiel #19
0
 def api_wrapper(self, kw):
     data = simplejson.dumps(kw)
     c.response.content = filters.websafe_json(data)
     return c.response
Beispiel #20
0
 def api_wrapper(self, kw):
     data = simplejson.dumps(kw)
     return filters.websafe_json(data)
Beispiel #21
0
 def api_wrapper(self, kw):
     data = simplejson.dumps(kw)
     return filters.websafe_json(data)
Beispiel #22
0
 def api_wrapper(self, kw):
     data = simplejson.dumps(kw)
     c.response.content = filters.websafe_json(data)
     return c.response
Beispiel #23
0
 def use(self):
     from r2.lib.filters import SC_OFF, SC_ON, websafe_json
     escaped_json = websafe_json(self.get_source())
     return (SC_OFF + inline_script_tag.format(content=escaped_json) +
             SC_ON + "\n")
Beispiel #24
0
    def GET_document(self):
        try:
            c.errors = c.errors or ErrorSet()
            # clear cookies the old fashioned way 
            c.cookies = Cookies()

            code =  request.GET.get('code', '')
            try:
                code = int(code)
            except ValueError:
                code = 404
            srname = request.GET.get('srname', '')
            takedown = request.GET.get('takedown', '')
            error_name = request.GET.get('error_name', '')

            if isinstance(c.user, basestring):
                # somehow requests are getting here with c.user unset
                c.user_is_loggedin = False
                c.user = UnloggedUser(browser_langs=None)

            if srname:
                c.site = Subreddit._by_name(srname)

            if request.GET.has_key('allow_framing'):
                c.allow_framing = bool(request.GET['allow_framing'] == '1')

            if (error_name == 'IN_TIMEOUT' and
                    not 'usable_error_content' in request.environ):
                timeout_days_remaining = c.user.days_remaining_in_timeout

                errpage = pages.InterstitialPage(
                    _("suspended"),
                    content=pages.InTimeoutInterstitial(
                        timeout_days_remaining=timeout_days_remaining,
                    ),
                )
                request.environ['usable_error_content'] = errpage.render()

            if code in (204, 304):
                # NEVER return a content body on 204/304 or downstream
                # caches may become very confused.
                return ""
            elif c.render_style not in self.allowed_render_styles:
                return str(code)
            elif c.render_style in extensions.API_TYPES:
                data = request.environ.get('extra_error_data', {'error': code})
                message = request.GET.get('message', '')
                if message:
                    data['message'] = message
                if request.environ.get("WANT_RAW_JSON"):
                    return scriptsafe_dumps(data)
                return websafe_json(json.dumps(data))
            elif takedown and code == 404:
                link = Link._by_fullname(takedown)
                return pages.TakedownPage(link).render()
            elif code == 400:
                return self.send400()
            elif code == 403:
                return self.send403()
            elif code == 429:
                return self.send429()
            elif code == 500:
                failien_url = make_failien_url()
                sad_message = get_funny_translated_string("500_page")
                sad_message %= {'admin': random.choice(self.admins)}
                sad_message = safemarkdown(sad_message)
                return redditbroke % (failien_url, sad_message)
            elif code == 503:
                return self.send503()
            elif c.site:
                return self.send404()
            else:
                return "page not found"
        except Exception as e:
            return handle_awful_failure("ErrorController.GET_document: %r" % e)
Beispiel #25
0
 def sendstring(self, string):
     '''sends a string and automatically escapes &, < and > to make sure no code injection happens'''
     c.response.headers['Content-Type'] = 'text/html; charset=UTF-8'
     c.response.content = filters.websafe_json(string)
     return c.response