annotate roundup/cgi/client.py @ 6693:9a1f5e496e6c

issue2551203 - Add support for CORS preflight request Add support for unauthenticated CORS preflight and fix headers for CORS. client.py: pass through unauthenticated CORS preflight to rest backend. Normal rest OPTION handlers (including tracker defined extensions) can see and handle the request. make some error cases return error json with crrect mime type rather than plain text tracebacks. create new functions to verify origin and referer that filter using allowed origins setting. remove tracker base url from error message is referer is not at an allowed origin. rest.py: fix up OPTION methods handlers to include Access-Control-Allow-Methods that are the same as the Allow header. set cache to one week for all Access-Control headers for CORS preflight only. remove self.client.setHeader("Access-Control-Allow-Origin", "*") and set Access-Control-Allow-Origin to the client supplied origin if it passes allowed origin checks. Required for CORS otherwise data isn't available to caller. Set for all responses. set Vary header now includes Origin as responses can differ based on Origin for all responses. set Access-Control-Allow-Credentials to true on all responses. test_liveserver.py: run server with setting to enforce origin csrf header check run server with setting to enforce x-requested-with csrf header check run server with setting for allowed_api_origins requests now set required csrf headers test preflight request on collections check new headers and Origin is no longer '*' rewrite all compression checks to use a single method with argument to use different compression methods. Reduce a lot of code duplication and makes updating for new headers easier. test_cgi: test new error messages in client.py account for new headers test preflight and new code paths
author John Rouillard <rouilj@ieee.org>
date Tue, 07 Jun 2022 09:39:35 -0400
parents ab2ed11c021e
children 6b636fb29740
Ignore whitespace changes - Everywhere: Within whitespace: At end of lines:
rev   line source
2005
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
1 """WWW request handler (also used in the stand-alone server).
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
2 """
2005
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
3 __docformat__ = 'restructuredtext'
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
4
5201
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
5 import logging
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
6 logger = logging.getLogger('roundup')
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
7
4362
74476eaac38a more modernisation
Richard Jones <richard@users.sourceforge.net>
parents: 4344
diff changeset
8 import base64, binascii, cgi, codecs, mimetypes, os
5201
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
9 import quopri, re, stat, sys, time
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
10 import socket, errno, hashlib
4980
13f8f88ad984 Replace rfc822 imports with email package (issue2550870)
John Kristensen <john@jerrykan.com>
parents: 4979
diff changeset
11 import email.utils
4543
d16d9bf655d8 - fix handling of traceback mails to the roundup admin
Ralf Schlatterbeck <schlatterbeck@users.sourceforge.net>
parents: 4530
diff changeset
12 from traceback import format_exc
2233
3d9bb1a052d1 fix random seeding for forking server
Richard Jones <richard@users.sourceforge.net>
parents: 2230
diff changeset
13
5488
52cb53eedf77 reworked random number use
Christof Meerwald <cmeerw@cmeerw.org>
parents: 5475
diff changeset
14 import roundup.anypy.random_ as random_
52cb53eedf77 reworked random number use
Christof Meerwald <cmeerw@cmeerw.org>
parents: 5475
diff changeset
15 if not random_.is_weak:
5201
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
16 logger.debug("Importing good random generator")
5488
52cb53eedf77 reworked random number use
Christof Meerwald <cmeerw@cmeerw.org>
parents: 5475
diff changeset
17 else:
5201
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
18 logger.warning("**SystemRandom not available. Using poor random generator")
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
19
4638
1ebc5f16aeda Ignore OpenSSL.SSL.SysCallError similar to IOError.
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4623
diff changeset
20 try:
1ebc5f16aeda Ignore OpenSSL.SSL.SysCallError similar to IOError.
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4623
diff changeset
21 from OpenSSL.SSL import SysCallError
1ebc5f16aeda Ignore OpenSSL.SSL.SysCallError similar to IOError.
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4623
diff changeset
22 except ImportError:
5429
daa19de102a2 Python 3 preparation: make fallback SysCallError an actual exception class.
Joseph Myers <jsm@polyomino.org.uk>
parents: 5422
diff changeset
23 class SysCallError(Exception):
daa19de102a2 Python 3 preparation: make fallback SysCallError an actual exception class.
Joseph Myers <jsm@polyomino.org.uk>
parents: 5422
diff changeset
24 pass
4638
1ebc5f16aeda Ignore OpenSSL.SSL.SysCallError similar to IOError.
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4623
diff changeset
25
5837
883c9e90b403 Fix problem with cgi.escape being depricated a different way. This way
John Rouillard <rouilj@ieee.org>
parents: 5804
diff changeset
26 from roundup.anypy.html import html_escape
5802
0e6d45413e88 catching last couple of cgi.escape references.
John Rouillard <rouilj@ieee.org>
parents: 5775
diff changeset
27
2004
1782fe36e7b8 Move out parts of client.py to new modules:
Johannes Gijsbers <jlgijsbers@users.sourceforge.net>
parents: 1987
diff changeset
28 from roundup import roundupdb, date, hyperdb, password
2557
ff02e9851592 translator object must be Roundup Translation Service...
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2514
diff changeset
29 from roundup.cgi import templating, cgitb, TranslationService
5073
d0aa596daca8 Remove 'import *' statement from cgi/client.py
John Kristensen <john@jerrykan.com>
parents: 5044
diff changeset
30 from roundup.cgi import actions
5218
44f7e6b958fe Added tests for csrf with xmlrpc.
John Rouillard <rouilj@ieee.org>
parents: 5212
diff changeset
31 from roundup.exceptions import LoginError, Reject, RejectRaw, \
44f7e6b958fe Added tests for csrf with xmlrpc.
John Rouillard <rouilj@ieee.org>
parents: 5212
diff changeset
32 Unauthorised, UsageError
5073
d0aa596daca8 Remove 'import *' statement from cgi/client.py
John Kristensen <john@jerrykan.com>
parents: 5044
diff changeset
33 from roundup.cgi.exceptions import (
6588
91ab3e0ffcd0 Summary: Add test cases for sqlite fts
John Rouillard <rouilj@ieee.org>
parents: 6550
diff changeset
34 FormError, IndexerQueryError, NotFound, NotModified, Redirect,
91ab3e0ffcd0 Summary: Add test cases for sqlite fts
John Rouillard <rouilj@ieee.org>
parents: 6550
diff changeset
35 SendFile, SendStaticFile, DetectorError, SeriousError)
2004
1782fe36e7b8 Move out parts of client.py to new modules:
Johannes Gijsbers <jlgijsbers@users.sourceforge.net>
parents: 1987
diff changeset
36 from roundup.cgi.form_parser import FormParser
5493
725266c03eab updated mailgw to no longer use mimetools based on jerrykan's patch
Christof Meerwald <cmeerw@cmeerw.org>
parents: 5488
diff changeset
37 from roundup.mailer import Mailer, MessageSendError
3427
198fe87b0254 add language detection (patch [SF#1360321])
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3396
diff changeset
38 from roundup.cgi import accept_language
4079
edf526c91412 * Refactor XMLRPC interface.
Stefan Seefeld <stefan@seefeld.name>
parents: 4077
diff changeset
39 from roundup import xmlrpc
5556
d75aa88c2a99 Added RestInstance and calling rest from client.py
Chau Nguyen <dangchau1991@yahoo.com>
parents: 5555
diff changeset
40 from roundup import rest
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
41
4362
74476eaac38a more modernisation
Richard Jones <richard@users.sourceforge.net>
parents: 4344
diff changeset
42 from roundup.anypy.cookie_ import CookieError, BaseCookie, SimpleCookie, \
74476eaac38a more modernisation
Richard Jones <richard@users.sourceforge.net>
parents: 4344
diff changeset
43 get_cookie_date
74476eaac38a more modernisation
Richard Jones <richard@users.sourceforge.net>
parents: 4344
diff changeset
44 from roundup.anypy import http_
74476eaac38a more modernisation
Richard Jones <richard@users.sourceforge.net>
parents: 4344
diff changeset
45 from roundup.anypy import urllib_
5408
e46ce04d5bbc Python 3 preparation: update xmlrpclib / SimpleXMLRPCServer imports.
Joseph Myers <jsm@polyomino.org.uk>
parents: 5395
diff changeset
46 from roundup.anypy import xmlrpc_
4362
74476eaac38a more modernisation
Richard Jones <richard@users.sourceforge.net>
parents: 4344
diff changeset
47
5422
a0ed8d5d744f Python 3 preparation: update email module names.
Joseph Myers <jsm@polyomino.org.uk>
parents: 5417
diff changeset
48 from email.mime.base import MIMEBase
a0ed8d5d744f Python 3 preparation: update email module names.
Joseph Myers <jsm@polyomino.org.uk>
parents: 5417
diff changeset
49 from email.mime.text import MIMEText
a0ed8d5d744f Python 3 preparation: update email module names.
Joseph Myers <jsm@polyomino.org.uk>
parents: 5417
diff changeset
50 from email.mime.multipart import MIMEMultipart
4979
f1a2bd1dea77 issue2550877: Writing headers with the email module will use continuation_ws = ' ' now for python 2.5 and 2.6 when importing anypy.email_.
Bernhard Reiter <bernhard@intevation.de>
parents: 4962
diff changeset
51 import roundup.anypy.email_
4543
d16d9bf655d8 - fix handling of traceback mails to the roundup admin
Ralf Schlatterbeck <schlatterbeck@users.sourceforge.net>
parents: 4530
diff changeset
52
6458
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
53 from roundup.anypy.strings import s2b, b2s, bs2b, uchr, is_us
5417
c749d6795bc2 Python 3 preparation: unichr.
Joseph Myers <jsm@polyomino.org.uk>
parents: 5408
diff changeset
54
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
55 def initialiseSecurity(security):
2005
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
56 '''Create some Permissions and Roles on the security object
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
57
2005
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
58 This function is directly invoked by security.Security.__init__()
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
59 as a part of the Security object instantiation.
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
60 '''
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
61 p = security.addPermission(name="Web Access",
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
62 description="User may access the web interface")
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
63 security.addPermissionToRole('Admin', p)
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
64
5879
94a7669677ae add permissions to control user of rest and xmlrpc API interfaces.
John Rouillard <rouilj@ieee.org>
parents: 5878
diff changeset
65 p = security.addPermission(name="Rest Access",
94a7669677ae add permissions to control user of rest and xmlrpc API interfaces.
John Rouillard <rouilj@ieee.org>
parents: 5878
diff changeset
66 description="User may access the rest interface")
94a7669677ae add permissions to control user of rest and xmlrpc API interfaces.
John Rouillard <rouilj@ieee.org>
parents: 5878
diff changeset
67 security.addPermissionToRole('Admin', p)
94a7669677ae add permissions to control user of rest and xmlrpc API interfaces.
John Rouillard <rouilj@ieee.org>
parents: 5878
diff changeset
68
94a7669677ae add permissions to control user of rest and xmlrpc API interfaces.
John Rouillard <rouilj@ieee.org>
parents: 5878
diff changeset
69 p = security.addPermission(name="Xmlrpc Access",
94a7669677ae add permissions to control user of rest and xmlrpc API interfaces.
John Rouillard <rouilj@ieee.org>
parents: 5878
diff changeset
70 description="User may access the xmlrpc interface")
94a7669677ae add permissions to control user of rest and xmlrpc API interfaces.
John Rouillard <rouilj@ieee.org>
parents: 5878
diff changeset
71 security.addPermissionToRole('Admin', p)
94a7669677ae add permissions to control user of rest and xmlrpc API interfaces.
John Rouillard <rouilj@ieee.org>
parents: 5878
diff changeset
72
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
73 # doing Role stuff through the web - make sure Admin can
3276
3124e578db02 Email fixes:
Richard Jones <richard@users.sourceforge.net>
parents: 3069
diff changeset
74 # TODO: deprecate this and use a property-based control
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
75 p = security.addPermission(name="Web Roles",
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
76 description="User may manipulate user Roles through the web")
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
77 security.addPermissionToRole('Admin', p)
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
78
4880
ca692423e401 Different approach to fix XSS in issue2550817
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4851
diff changeset
79 def add_message(msg_list, msg, escape=True):
ca692423e401 Different approach to fix XSS in issue2550817
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4851
diff changeset
80 if escape:
5804
8f50e00532e7 html.escape(string, quote=...) sets quote to True not False by
John Rouillard <rouilj@ieee.org>
parents: 5802
diff changeset
81 msg = html_escape(msg, quote=False).replace('\n', '<br />\n')
4880
ca692423e401 Different approach to fix XSS in issue2550817
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4851
diff changeset
82 else:
ca692423e401 Different approach to fix XSS in issue2550817
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4851
diff changeset
83 msg = msg.replace('\n', '<br />\n')
ca692423e401 Different approach to fix XSS in issue2550817
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4851
diff changeset
84 msg_list.append (msg)
ca692423e401 Different approach to fix XSS in issue2550817
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4851
diff changeset
85 return msg_list # for unittests
3916
57ad3e2c2545 handle bad cookies
Justus Pendleton <jpend@users.sourceforge.net>
parents: 3900
diff changeset
86
4880
ca692423e401 Different approach to fix XSS in issue2550817
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4851
diff changeset
87 default_err_msg = ''"""<html><head><title>An error has occurred</title></head>
3554
5e70726a86dd fixed schema migration problem when Class keys were removed
Richard Jones <richard@users.sourceforge.net>
parents: 3551
diff changeset
88 <body><h1>An error has occurred</h1>
3551
3c70ab03c917 translate error message shown instead of tracebacks, add page title
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3548
diff changeset
89 <p>A problem was encountered processing your request.
3c70ab03c917 translate error message shown instead of tracebacks, add page title
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3548
diff changeset
90 The tracker maintainers have been notified of the problem.</p>
4065
1e28d58c6d1c Uniformly use """...""" instead of '''...''' for comments.
Stefan Seefeld <stefan@seefeld.name>
parents: 4064
diff changeset
91 </body></html>"""
3548
61d48244e7a8 login may now be for a single session
Richard Jones <richard@users.sourceforge.net>
parents: 3494
diff changeset
92
5356
91954be46a66 A real fix for the problem where:
John Rouillard <rouilj@ieee.org>
parents: 5350
diff changeset
93 def seed_pseudorandom():
91954be46a66 A real fix for the problem where:
John Rouillard <rouilj@ieee.org>
parents: 5350
diff changeset
94 '''A function to seed the default pseudorandom random number generator
91954be46a66 A real fix for the problem where:
John Rouillard <rouilj@ieee.org>
parents: 5350
diff changeset
95 which is used to (at minimum):
91954be46a66 A real fix for the problem where:
John Rouillard <rouilj@ieee.org>
parents: 5350
diff changeset
96 * generate part of email message-id
91954be46a66 A real fix for the problem where:
John Rouillard <rouilj@ieee.org>
parents: 5350
diff changeset
97 * generate OTK for password reset
91954be46a66 A real fix for the problem where:
John Rouillard <rouilj@ieee.org>
parents: 5350
diff changeset
98 * generate the temp recovery password
91954be46a66 A real fix for the problem where:
John Rouillard <rouilj@ieee.org>
parents: 5350
diff changeset
99
91954be46a66 A real fix for the problem where:
John Rouillard <rouilj@ieee.org>
parents: 5350
diff changeset
100 This function limits the scope of the 'import random' call
91954be46a66 A real fix for the problem where:
John Rouillard <rouilj@ieee.org>
parents: 5350
diff changeset
101 as the random identifier is used throughout the code and
91954be46a66 A real fix for the problem where:
John Rouillard <rouilj@ieee.org>
parents: 5350
diff changeset
102 can refer to SystemRandom.
91954be46a66 A real fix for the problem where:
John Rouillard <rouilj@ieee.org>
parents: 5350
diff changeset
103 '''
91954be46a66 A real fix for the problem where:
John Rouillard <rouilj@ieee.org>
parents: 5350
diff changeset
104 import random
91954be46a66 A real fix for the problem where:
John Rouillard <rouilj@ieee.org>
parents: 5350
diff changeset
105 random.seed()
3916
57ad3e2c2545 handle bad cookies
Justus Pendleton <jpend@users.sourceforge.net>
parents: 3900
diff changeset
106
57ad3e2c2545 handle bad cookies
Justus Pendleton <jpend@users.sourceforge.net>
parents: 3900
diff changeset
107 class LiberalCookie(SimpleCookie):
4065
1e28d58c6d1c Uniformly use """...""" instead of '''...''' for comments.
Stefan Seefeld <stefan@seefeld.name>
parents: 4064
diff changeset
108 """ Python's SimpleCookie throws an exception if the cookie uses invalid
3916
57ad3e2c2545 handle bad cookies
Justus Pendleton <jpend@users.sourceforge.net>
parents: 3900
diff changeset
109 syntax. Other applications on the same server may have done precisely
57ad3e2c2545 handle bad cookies
Justus Pendleton <jpend@users.sourceforge.net>
parents: 3900
diff changeset
110 this, preventing roundup from working through no fault of roundup.
57ad3e2c2545 handle bad cookies
Justus Pendleton <jpend@users.sourceforge.net>
parents: 3900
diff changeset
111 Numerous other python apps have run into the same problem:
57ad3e2c2545 handle bad cookies
Justus Pendleton <jpend@users.sourceforge.net>
parents: 3900
diff changeset
112
57ad3e2c2545 handle bad cookies
Justus Pendleton <jpend@users.sourceforge.net>
parents: 3900
diff changeset
113 trac: http://trac.edgewall.org/ticket/2256
57ad3e2c2545 handle bad cookies
Justus Pendleton <jpend@users.sourceforge.net>
parents: 3900
diff changeset
114 mailman: http://bugs.python.org/issue472646
57ad3e2c2545 handle bad cookies
Justus Pendleton <jpend@users.sourceforge.net>
parents: 3900
diff changeset
115
57ad3e2c2545 handle bad cookies
Justus Pendleton <jpend@users.sourceforge.net>
parents: 3900
diff changeset
116 This particular implementation comes from trac's solution to the
57ad3e2c2545 handle bad cookies
Justus Pendleton <jpend@users.sourceforge.net>
parents: 3900
diff changeset
117 problem. Unfortunately it requires some hackery in SimpleCookie's
57ad3e2c2545 handle bad cookies
Justus Pendleton <jpend@users.sourceforge.net>
parents: 3900
diff changeset
118 internals to provide a more liberal __set method.
4065
1e28d58c6d1c Uniformly use """...""" instead of '''...''' for comments.
Stefan Seefeld <stefan@seefeld.name>
parents: 4064
diff changeset
119 """
3916
57ad3e2c2545 handle bad cookies
Justus Pendleton <jpend@users.sourceforge.net>
parents: 3900
diff changeset
120 def load(self, rawdata, ignore_parse_errors=True):
57ad3e2c2545 handle bad cookies
Justus Pendleton <jpend@users.sourceforge.net>
parents: 3900
diff changeset
121 if ignore_parse_errors:
57ad3e2c2545 handle bad cookies
Justus Pendleton <jpend@users.sourceforge.net>
parents: 3900
diff changeset
122 self.bad_cookies = []
57ad3e2c2545 handle bad cookies
Justus Pendleton <jpend@users.sourceforge.net>
parents: 3900
diff changeset
123 self._BaseCookie__set = self._loose_set
57ad3e2c2545 handle bad cookies
Justus Pendleton <jpend@users.sourceforge.net>
parents: 3900
diff changeset
124 SimpleCookie.load(self, rawdata)
57ad3e2c2545 handle bad cookies
Justus Pendleton <jpend@users.sourceforge.net>
parents: 3900
diff changeset
125 if ignore_parse_errors:
57ad3e2c2545 handle bad cookies
Justus Pendleton <jpend@users.sourceforge.net>
parents: 3900
diff changeset
126 self._BaseCookie__set = self._strict_set
57ad3e2c2545 handle bad cookies
Justus Pendleton <jpend@users.sourceforge.net>
parents: 3900
diff changeset
127 for key in self.bad_cookies:
57ad3e2c2545 handle bad cookies
Justus Pendleton <jpend@users.sourceforge.net>
parents: 3900
diff changeset
128 del self[key]
57ad3e2c2545 handle bad cookies
Justus Pendleton <jpend@users.sourceforge.net>
parents: 3900
diff changeset
129
57ad3e2c2545 handle bad cookies
Justus Pendleton <jpend@users.sourceforge.net>
parents: 3900
diff changeset
130 _strict_set = BaseCookie._BaseCookie__set
57ad3e2c2545 handle bad cookies
Justus Pendleton <jpend@users.sourceforge.net>
parents: 3900
diff changeset
131
57ad3e2c2545 handle bad cookies
Justus Pendleton <jpend@users.sourceforge.net>
parents: 3900
diff changeset
132 def _loose_set(self, key, real_value, coded_value):
57ad3e2c2545 handle bad cookies
Justus Pendleton <jpend@users.sourceforge.net>
parents: 3900
diff changeset
133 try:
57ad3e2c2545 handle bad cookies
Justus Pendleton <jpend@users.sourceforge.net>
parents: 3900
diff changeset
134 self._strict_set(key, real_value, coded_value)
57ad3e2c2545 handle bad cookies
Justus Pendleton <jpend@users.sourceforge.net>
parents: 3900
diff changeset
135 except CookieError:
57ad3e2c2545 handle bad cookies
Justus Pendleton <jpend@users.sourceforge.net>
parents: 3900
diff changeset
136 self.bad_cookies.append(key)
57ad3e2c2545 handle bad cookies
Justus Pendleton <jpend@users.sourceforge.net>
parents: 3900
diff changeset
137 dict.__setitem__(self, key, None)
57ad3e2c2545 handle bad cookies
Justus Pendleton <jpend@users.sourceforge.net>
parents: 3900
diff changeset
138
57ad3e2c2545 handle bad cookies
Justus Pendleton <jpend@users.sourceforge.net>
parents: 3900
diff changeset
139
3989
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
140 class Session:
4065
1e28d58c6d1c Uniformly use """...""" instead of '''...''' for comments.
Stefan Seefeld <stefan@seefeld.name>
parents: 4064
diff changeset
141 """
3989
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
142 Needs DB to be already opened by client
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
143
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
144 Session attributes at instantiation:
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
145
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
146 - "client" - reference to client for add_cookie function
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
147 - "session_db" - session DB manager
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
148 - "cookie_name" - name of the cookie with session id
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
149 - "_sid" - session id for current user
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
150 - "_data" - session data cache
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
151
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
152 session = Session(client)
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
153 session.set(name=value)
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
154 value = session.get(name)
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
155
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
156 session.destroy() # delete current session
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
157 session.clean_up() # clean up session table
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
158
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
159 session.update(set_cookie=True, expire=3600*24*365)
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
160 # refresh session expiration time, setting persistent
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
161 # cookie if needed to last for 'expire' seconds
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
162
4065
1e28d58c6d1c Uniformly use """...""" instead of '''...''' for comments.
Stefan Seefeld <stefan@seefeld.name>
parents: 4064
diff changeset
163 """
3989
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
164
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
165 def __init__(self, client):
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
166 self._data = {}
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
167 self._sid = None
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
168
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
169 self.client = client
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
170 self.session_db = client.db.getSessionManager()
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
171
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
172 # parse cookies for session id
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
173 self.cookie_name = 'roundup_session_%s' % \
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
174 re.sub('[^a-zA-Z]', '', client.instance.config.TRACKER_NAME)
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
175 cookies = LiberalCookie(client.env.get('HTTP_COOKIE', ''))
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
176 if self.cookie_name in cookies:
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
177 if not self.session_db.exists(cookies[self.cookie_name].value):
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
178 self._sid = None
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
179 # remove old cookie
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
180 self.client.add_cookie(self.cookie_name, None)
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
181 else:
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
182 self._sid = cookies[self.cookie_name].value
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
183 self._data = self.session_db.getall(self._sid)
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
184
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
185 def _gen_sid(self):
4065
1e28d58c6d1c Uniformly use """...""" instead of '''...''' for comments.
Stefan Seefeld <stefan@seefeld.name>
parents: 4064
diff changeset
186 """ generate a unique session key """
3989
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
187 while 1:
6082
a3221c686736 changing the sid after checking for collisions defeats the purpose
Christof Meerwald <cmeerw@cmeerw.org>
parents: 6053
diff changeset
188 s = b2s(binascii.b2a_base64(random_.token_bytes(32)).strip()).rstrip('=')
3989
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
189 if not self.session_db.exists(s):
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
190 break
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
191
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
192 return s
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
193
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
194 def clean_up(self):
4065
1e28d58c6d1c Uniformly use """...""" instead of '''...''' for comments.
Stefan Seefeld <stefan@seefeld.name>
parents: 4064
diff changeset
195 """Remove expired sessions"""
3989
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
196 self.session_db.clean()
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
197
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
198 def destroy(self):
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
199 self.client.add_cookie(self.cookie_name, None)
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
200 self._data = {}
6147
f35ca71c9f2e fixed logout action when there is no session
Christof Meerwald <cmeerw@cmeerw.org>
parents: 6082
diff changeset
201 if self._sid:
f35ca71c9f2e fixed logout action when there is no session
Christof Meerwald <cmeerw@cmeerw.org>
parents: 6082
diff changeset
202 self.session_db.destroy(self._sid)
f35ca71c9f2e fixed logout action when there is no session
Christof Meerwald <cmeerw@cmeerw.org>
parents: 6082
diff changeset
203 self.session_db.commit()
3989
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
204
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
205 def get(self, name, default=None):
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
206 return self._data.get(name, default)
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
207
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
208 def set(self, **kwargs):
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
209 self._data.update(kwargs)
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
210 if not self._sid:
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
211 self._sid = self._gen_sid()
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
212 self.session_db.set(self._sid, **self._data)
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
213 # add session cookie
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
214 self.update(set_cookie=True)
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
215
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
216 # XXX added when patching 1.4.4 for backward compatibility
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
217 # XXX remove
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
218 self.client.session = self._sid
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
219 else:
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
220 self.session_db.set(self._sid, **self._data)
5319
62de601bdf6f Fix commits although a Reject exception is raised
Ralf Schlatterbeck <rsc@runtux.com>
parents: 5248
diff changeset
221 self.session_db.commit()
3989
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
222
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
223 def update(self, set_cookie=False, expire=None):
4065
1e28d58c6d1c Uniformly use """...""" instead of '''...''' for comments.
Stefan Seefeld <stefan@seefeld.name>
parents: 4064
diff changeset
224 """ update timestamp in db to avoid expiration
3989
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
225
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
226 if 'set_cookie' is True, set cookie with 'expire' seconds lifetime
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
227 if 'expire' is None - session will be closed with the browser
4648
e645820e8556 Clean up whitespace in client.py
Ezio Melotti <ezio.melotti@gmail.com>
parents: 4640
diff changeset
228
3989
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
229 XXX the session can be purged within a week even if a cookie
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
230 lifetime is longer
4065
1e28d58c6d1c Uniformly use """...""" instead of '''...''' for comments.
Stefan Seefeld <stefan@seefeld.name>
parents: 4064
diff changeset
231 """
3989
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
232 self.session_db.updateTimestamp(self._sid)
5319
62de601bdf6f Fix commits although a Reject exception is raised
Ralf Schlatterbeck <rsc@runtux.com>
parents: 5248
diff changeset
233 self.session_db.commit()
3989
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
234
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
235 if set_cookie:
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
236 self.client.add_cookie(self.cookie_name, self._sid, expire=expire)
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
237
5775
17e110426ad7 issue2551046: Attempts to attach file or create large message fail
John Rouillard <rouilj@ieee.org>
parents: 5696
diff changeset
238 # import from object as well so it's a new style object and I can use super()
17e110426ad7 issue2551046: Attempts to attach file or create large message fail
John Rouillard <rouilj@ieee.org>
parents: 5696
diff changeset
239 class BinaryFieldStorage(cgi.FieldStorage, object):
5656
d26d2590cd8c Implement different workaround for https://bugs.python.org/issue27777
John Rouillard <rouilj@ieee.org>
parents: 5655
diff changeset
240 '''This class works around the bug https://bugs.python.org/issue27777.
3989
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
241
5656
d26d2590cd8c Implement different workaround for https://bugs.python.org/issue27777
John Rouillard <rouilj@ieee.org>
parents: 5655
diff changeset
242 cgi.FieldStorage must save all data as binary/bytes. This is
d26d2590cd8c Implement different workaround for https://bugs.python.org/issue27777
John Rouillard <rouilj@ieee.org>
parents: 5655
diff changeset
243 needed for handling json and xml data blobs under python
d26d2590cd8c Implement different workaround for https://bugs.python.org/issue27777
John Rouillard <rouilj@ieee.org>
parents: 5655
diff changeset
244 3. Under python 2, str and binary are interchangable, not so
d26d2590cd8c Implement different workaround for https://bugs.python.org/issue27777
John Rouillard <rouilj@ieee.org>
parents: 5655
diff changeset
245 under 3.
d26d2590cd8c Implement different workaround for https://bugs.python.org/issue27777
John Rouillard <rouilj@ieee.org>
parents: 5655
diff changeset
246 '''
d26d2590cd8c Implement different workaround for https://bugs.python.org/issue27777
John Rouillard <rouilj@ieee.org>
parents: 5655
diff changeset
247 def make_file(self, mode=None):
d26d2590cd8c Implement different workaround for https://bugs.python.org/issue27777
John Rouillard <rouilj@ieee.org>
parents: 5655
diff changeset
248 ''' work around https://bugs.python.org/issue27777 '''
d26d2590cd8c Implement different workaround for https://bugs.python.org/issue27777
John Rouillard <rouilj@ieee.org>
parents: 5655
diff changeset
249 import tempfile
5671
f60c44563c3a Adjust make_file override to use binary files only when needed.
Joseph Myers <jsm@polyomino.org.uk>
parents: 5666
diff changeset
250 if self.length >= 0:
f60c44563c3a Adjust make_file override to use binary files only when needed.
Joseph Myers <jsm@polyomino.org.uk>
parents: 5666
diff changeset
251 return tempfile.TemporaryFile("wb+")
5775
17e110426ad7 issue2551046: Attempts to attach file or create large message fail
John Rouillard <rouilj@ieee.org>
parents: 5696
diff changeset
252 return super(BinaryFieldStorage, self).make_file()
3989
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
253
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
254 class Client:
4065
1e28d58c6d1c Uniformly use """...""" instead of '''...''' for comments.
Stefan Seefeld <stefan@seefeld.name>
parents: 4064
diff changeset
255 """Instantiate to handle one CGI request.
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
256
1244
8dd4f736370b merge from maintenance branch
Richard Jones <richard@users.sourceforge.net>
parents: 1236
diff changeset
257 See inner_main for request processing.
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
258
1244
8dd4f736370b merge from maintenance branch
Richard Jones <richard@users.sourceforge.net>
parents: 1236
diff changeset
259 Client attributes at instantiation:
2005
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
260
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
261 - "path" is the PATH_INFO inside the instance (with no leading '/')
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
262 - "base" is the base URL for the instance
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
263 - "form" is the cgi form, an instance of FieldStorage from the standard
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
264 cgi module
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
265 - "additional_headers" is a dictionary of additional HTTP headers that
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
266 should be sent to the client
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
267 - "response_code" is the HTTP response code to send to the client
2557
ff02e9851592 translator object must be Roundup Translation Service...
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2514
diff changeset
268 - "translator" is TranslationService instance
5201
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
269 - "client-nonce" is a unique value for this client connection. Can be
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
270 used as a nonce for CSP headers and to sign javascript code
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
271 presented to the browser. This is different from the CSRF nonces
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
272 and can not be used for anti-csrf measures.
1244
8dd4f736370b merge from maintenance branch
Richard Jones <richard@users.sourceforge.net>
parents: 1236
diff changeset
273
8dd4f736370b merge from maintenance branch
Richard Jones <richard@users.sourceforge.net>
parents: 1236
diff changeset
274 During the processing of a request, the following attributes are used:
2005
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
275
4648
e645820e8556 Clean up whitespace in client.py
Ezio Melotti <ezio.melotti@gmail.com>
parents: 4640
diff changeset
276 - "db"
4880
ca692423e401 Different approach to fix XSS in issue2550817
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4851
diff changeset
277 - "_error_message" holds a list of error messages
ca692423e401 Different approach to fix XSS in issue2550817
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4851
diff changeset
278 - "_ok_message" holds a list of OK messages
3989
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
279 - "session" is deprecated in favor of session_api (XXX remove)
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
280 - "session_api" is the interface to store data in session
2005
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
281 - "user" is the current user's name
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
282 - "userid" is the current user's id
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
283 - "template" is the current :template context
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
284 - "classname" is the current class context name
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
285 - "nodeid" is the current context item id
1244
8dd4f736370b merge from maintenance branch
Richard Jones <richard@users.sourceforge.net>
parents: 1236
diff changeset
286
4880
ca692423e401 Different approach to fix XSS in issue2550817
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4851
diff changeset
287 Note: _error_message and _ok_message should not be modified
ca692423e401 Different approach to fix XSS in issue2550817
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4851
diff changeset
288 directly, use add_ok_message and add_error_message, these, by
ca692423e401 Different approach to fix XSS in issue2550817
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4851
diff changeset
289 default, escape the message added to avoid XSS security issues.
ca692423e401 Different approach to fix XSS in issue2550817
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4851
diff changeset
290
1244
8dd4f736370b merge from maintenance branch
Richard Jones <richard@users.sourceforge.net>
parents: 1236
diff changeset
291 User Identification:
3989
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
292 Users that are absent in session data are anonymous and are logged
5201
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
293 in as that user. This typically gives them all Permissions assigned
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
294 to the Anonymous Role.
1244
8dd4f736370b merge from maintenance branch
Richard Jones <richard@users.sourceforge.net>
parents: 1236
diff changeset
295
5201
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
296 Every user is assigned a session. "session_api" is the interface
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
297 to work with session data.
1420
3ac43c62a250 implemented extension to form parsing...
Richard Jones <richard@users.sourceforge.net>
parents: 1417
diff changeset
298
3ac43c62a250 implemented extension to form parsing...
Richard Jones <richard@users.sourceforge.net>
parents: 1417
diff changeset
299 Special form variables:
3ac43c62a250 implemented extension to form parsing...
Richard Jones <richard@users.sourceforge.net>
parents: 1417
diff changeset
300 Note that in various places throughout this code, special form
3ac43c62a250 implemented extension to form parsing...
Richard Jones <richard@users.sourceforge.net>
parents: 1417
diff changeset
301 variables of the form :<name> are used. The colon (":") part may
1436
2f6647cf5345 bugger, dropping support for "+" special char
Richard Jones <richard@users.sourceforge.net>
parents: 1435
diff changeset
302 actually be one of either ":" or "@".
4065
1e28d58c6d1c Uniformly use """...""" instead of '''...''' for comments.
Stefan Seefeld <stefan@seefeld.name>
parents: 4064
diff changeset
303 """
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
304
2279
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
305 # charset used for data storage and form templates
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
306 # Note: must be in lower case for comparisons!
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
307 # XXX take this from instance.config?
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
308 STORAGE_CHARSET = 'utf-8'
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
309
1421
90bb11eb40dc oops, forgot the templating :)
Richard Jones <richard@users.sourceforge.net>
parents: 1420
diff changeset
310 #
1420
3ac43c62a250 implemented extension to form parsing...
Richard Jones <richard@users.sourceforge.net>
parents: 1417
diff changeset
311 # special form variables
1421
90bb11eb40dc oops, forgot the templating :)
Richard Jones <richard@users.sourceforge.net>
parents: 1420
diff changeset
312 #
1436
2f6647cf5345 bugger, dropping support for "+" special char
Richard Jones <richard@users.sourceforge.net>
parents: 1435
diff changeset
313 FV_TEMPLATE = re.compile(r'[@:]template')
2f6647cf5345 bugger, dropping support for "+" special char
Richard Jones <richard@users.sourceforge.net>
parents: 1435
diff changeset
314 FV_OK_MESSAGE = re.compile(r'[@:]ok_message')
2f6647cf5345 bugger, dropping support for "+" special char
Richard Jones <richard@users.sourceforge.net>
parents: 1435
diff changeset
315 FV_ERROR_MESSAGE = re.compile(r'[@:]error_message')
1421
90bb11eb40dc oops, forgot the templating :)
Richard Jones <richard@users.sourceforge.net>
parents: 1420
diff changeset
316
90bb11eb40dc oops, forgot the templating :)
Richard Jones <richard@users.sourceforge.net>
parents: 1420
diff changeset
317 # Note: index page stuff doesn't appear here:
90bb11eb40dc oops, forgot the templating :)
Richard Jones <richard@users.sourceforge.net>
parents: 1420
diff changeset
318 # columns, sort, sortdir, filter, group, groupdir, search_text,
90bb11eb40dc oops, forgot the templating :)
Richard Jones <richard@users.sourceforge.net>
parents: 1420
diff changeset
319 # pagesize, startwith
1420
3ac43c62a250 implemented extension to form parsing...
Richard Jones <richard@users.sourceforge.net>
parents: 1417
diff changeset
320
3760
b8f52d030f1a ignore common network errors, like "Connection reset by peer"
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3736
diff changeset
321 # list of network error codes that shouldn't be reported to tracker admin
b8f52d030f1a ignore common network errors, like "Connection reset by peer"
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3736
diff changeset
322 # (error descriptions from FreeBSD intro(2))
b8f52d030f1a ignore common network errors, like "Connection reset by peer"
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3736
diff changeset
323 IGNORE_NET_ERRORS = (
b8f52d030f1a ignore common network errors, like "Connection reset by peer"
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3736
diff changeset
324 # A write on a pipe, socket or FIFO for which there is
b8f52d030f1a ignore common network errors, like "Connection reset by peer"
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3736
diff changeset
325 # no process to read the data.
b8f52d030f1a ignore common network errors, like "Connection reset by peer"
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3736
diff changeset
326 errno.EPIPE,
b8f52d030f1a ignore common network errors, like "Connection reset by peer"
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3736
diff changeset
327 # A connection was forcibly closed by a peer.
b8f52d030f1a ignore common network errors, like "Connection reset by peer"
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3736
diff changeset
328 # This normally results from a loss of the connection
b8f52d030f1a ignore common network errors, like "Connection reset by peer"
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3736
diff changeset
329 # on the remote socket due to a timeout or a reboot.
b8f52d030f1a ignore common network errors, like "Connection reset by peer"
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3736
diff changeset
330 errno.ECONNRESET,
b8f52d030f1a ignore common network errors, like "Connection reset by peer"
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3736
diff changeset
331 # Software caused connection abort. A connection abort
b8f52d030f1a ignore common network errors, like "Connection reset by peer"
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3736
diff changeset
332 # was caused internal to your host machine.
b8f52d030f1a ignore common network errors, like "Connection reset by peer"
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3736
diff changeset
333 errno.ECONNABORTED,
b8f52d030f1a ignore common network errors, like "Connection reset by peer"
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3736
diff changeset
334 # A connect or send request failed because the connected party
b8f52d030f1a ignore common network errors, like "Connection reset by peer"
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3736
diff changeset
335 # did not properly respond after a period of time.
b8f52d030f1a ignore common network errors, like "Connection reset by peer"
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3736
diff changeset
336 errno.ETIMEDOUT,
b8f52d030f1a ignore common network errors, like "Connection reset by peer"
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3736
diff changeset
337 )
b8f52d030f1a ignore common network errors, like "Connection reset by peer"
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3736
diff changeset
338
6458
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
339 # Cache_Control[key] = Cache-Control header value
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
340 # Key can be explicitly file basename - value applied to just that file
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
341 # takes precedence over mime type.
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
342 # Key can be mime type - all files of that mimetype will get the value
6546
c58c7cd31243 issue2550991 - Some mechanism to set expiration header or max age for static resources
John Rouillard <rouilj@ieee.org>
parents: 6544
diff changeset
343 Cache_Control = {
c58c7cd31243 issue2550991 - Some mechanism to set expiration header or max age for static resources
John Rouillard <rouilj@ieee.org>
parents: 6544
diff changeset
344 'application/javascript': "public, max-age=1209600", # 2 weeks
c58c7cd31243 issue2550991 - Some mechanism to set expiration header or max age for static resources
John Rouillard <rouilj@ieee.org>
parents: 6544
diff changeset
345 'text/css': "public, max-age=4838400", # 8 weeks/2 months
c58c7cd31243 issue2550991 - Some mechanism to set expiration header or max age for static resources
John Rouillard <rouilj@ieee.org>
parents: 6544
diff changeset
346 }
6458
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
347
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
348 # list of valid http compression (Content-Encoding) algorithms
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
349 # we have available
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
350 compressors = []
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
351 try:
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
352 # Only one provided by standard library
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
353 import gzip
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
354 compressors.append('gzip')
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
355 except ImportError:
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
356 pass
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
357 try:
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
358 import brotli
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
359 compressors.append('br')
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
360 except ImportError:
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
361 pass
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
362 try:
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
363 import zstd
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
364 compressors.append('zstd')
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
365 except ImportError:
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
366 pass
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
367
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
368 # mime types of files that are already compressed and should not be
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
369 # compressed on the fly. Can be extended/reduced using interfaces.py.
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
370 # This excludes types from being compressed. Should we have a list
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
371 # of mime types we should compress? write_html() calls compress_encode
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
372 # which uses this without a content-type so that's an issue.
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
373 # Also for text based data, might have charset too so need to parse
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
374 # content-type.
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
375 precompressed_mime_types = [ "image/png", "image/jpeg" ]
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
376
2467
76ead526113d client instances may be used as translation engines.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2366
diff changeset
377 def __init__(self, instance, request, env, form=None, translator=None):
5356
91954be46a66 A real fix for the problem where:
John Rouillard <rouilj@ieee.org>
parents: 5350
diff changeset
378 # re-seed the random number generator. Is this is an instance of
91954be46a66 A real fix for the problem where:
John Rouillard <rouilj@ieee.org>
parents: 5350
diff changeset
379 # random.SystemRandom it has no effect.
5488
52cb53eedf77 reworked random number use
Christof Meerwald <cmeerw@cmeerw.org>
parents: 5475
diff changeset
380 random_.seed()
5356
91954be46a66 A real fix for the problem where:
John Rouillard <rouilj@ieee.org>
parents: 5350
diff changeset
381 # So we also seed the pseudorandom random source obtained from
91954be46a66 A real fix for the problem where:
John Rouillard <rouilj@ieee.org>
parents: 5350
diff changeset
382 # import random
91954be46a66 A real fix for the problem where:
John Rouillard <rouilj@ieee.org>
parents: 5350
diff changeset
383 # to make sure that every forked copy of the client will return
91954be46a66 A real fix for the problem where:
John Rouillard <rouilj@ieee.org>
parents: 5350
diff changeset
384 # new random numbers.
91954be46a66 A real fix for the problem where:
John Rouillard <rouilj@ieee.org>
parents: 5350
diff changeset
385 seed_pseudorandom()
2230
ca2664e095be disable forking server when os.fork() not available [SF#938586]
Richard Jones <richard@users.sourceforge.net>
parents: 2183
diff changeset
386 self.start = time.time()
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
387 self.instance = instance
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
388 self.request = request
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
389 self.env = env
6658
408fd477761f Add i18n object to roundupdb.Database
Ralf Schlatterbeck <rsc@runtux.com>
parents: 6656
diff changeset
390 if translator is not None :
408fd477761f Add i18n object to roundupdb.Database
Ralf Schlatterbeck <rsc@runtux.com>
parents: 6656
diff changeset
391 self.setTranslator(translator)
408fd477761f Add i18n object to roundupdb.Database
Ralf Schlatterbeck <rsc@runtux.com>
parents: 6656
diff changeset
392 # XXX we should set self.language to "translator"'s language,
408fd477761f Add i18n object to roundupdb.Database
Ralf Schlatterbeck <rsc@runtux.com>
parents: 6656
diff changeset
393 # but how to get it ?
408fd477761f Add i18n object to roundupdb.Database
Ralf Schlatterbeck <rsc@runtux.com>
parents: 6656
diff changeset
394 self.language = ""
408fd477761f Add i18n object to roundupdb.Database
Ralf Schlatterbeck <rsc@runtux.com>
parents: 6656
diff changeset
395 else :
408fd477761f Add i18n object to roundupdb.Database
Ralf Schlatterbeck <rsc@runtux.com>
parents: 6656
diff changeset
396 self.setTranslator(TranslationService.NullTranslationService())
408fd477761f Add i18n object to roundupdb.Database
Ralf Schlatterbeck <rsc@runtux.com>
parents: 6656
diff changeset
397 self.language = "" # as is the default from determine_language
408fd477761f Add i18n object to roundupdb.Database
Ralf Schlatterbeck <rsc@runtux.com>
parents: 6656
diff changeset
398
1799
071ea6fc803f Extracted duplicated mail-sending code...
Johannes Gijsbers <jlgijsbers@users.sourceforge.net>
parents: 1798
diff changeset
399 self.mailer = Mailer(instance.config)
5166
232c74973a56 issue1408570: fix that form values are lost
Ralf Schlatterbeck <rsc@runtux.com>
parents: 5165
diff changeset
400 # If True the form contents wins over the database contents when
232c74973a56 issue1408570: fix that form values are lost
Ralf Schlatterbeck <rsc@runtux.com>
parents: 5165
diff changeset
401 # rendering html properties. This is set when an error occurs so
232c74973a56 issue1408570: fix that form values are lost
Ralf Schlatterbeck <rsc@runtux.com>
parents: 5165
diff changeset
402 # that we don't lose submitted form contents.
232c74973a56 issue1408570: fix that form values are lost
Ralf Schlatterbeck <rsc@runtux.com>
parents: 5165
diff changeset
403 self.form_wins = False
1004
5f12d3259f31 logout works better now
Richard Jones <richard@users.sourceforge.net>
parents: 1003
diff changeset
404
1157
26c8cb2162d7 fixed various URL / base URL issues
Richard Jones <richard@users.sourceforge.net>
parents: 1153
diff changeset
405 # save off the path
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
406 self.path = env['PATH_INFO']
1004
5f12d3259f31 logout works better now
Richard Jones <richard@users.sourceforge.net>
parents: 1003
diff changeset
407
1398
b3e1e9ab0500 fixed cookie path to use TRACKER_WEB [SF#667020]
Richard Jones <richard@users.sourceforge.net>
parents: 1393
diff changeset
408 # this is the base URL for this tracker
1157
26c8cb2162d7 fixed various URL / base URL issues
Richard Jones <richard@users.sourceforge.net>
parents: 1153
diff changeset
409 self.base = self.instance.config.TRACKER_WEB
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
410
4586
b21bb66de6ff Mark cookies HttpOnly and -- if https is used -- secure.
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4578
diff changeset
411 # should cookies be secure?
b21bb66de6ff Mark cookies HttpOnly and -- if https is used -- secure.
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4578
diff changeset
412 self.secure = self.base.startswith ('https')
b21bb66de6ff Mark cookies HttpOnly and -- if https is used -- secure.
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4578
diff changeset
413
6249
3b62c35e824d client.py fix comment typo
John Rouillard <rouilj@ieee.org>
parents: 6211
diff changeset
414 # check the tracker_web setting
2183
ac24a9c74cca be paranoid about TRACKER_WEB
Richard Jones <richard@users.sourceforge.net>
parents: 2137
diff changeset
415 if not self.base.endswith('/'):
ac24a9c74cca be paranoid about TRACKER_WEB
Richard Jones <richard@users.sourceforge.net>
parents: 2137
diff changeset
416 self.base = self.base + '/'
ac24a9c74cca be paranoid about TRACKER_WEB
Richard Jones <richard@users.sourceforge.net>
parents: 2137
diff changeset
417
1398
b3e1e9ab0500 fixed cookie path to use TRACKER_WEB [SF#667020]
Richard Jones <richard@users.sourceforge.net>
parents: 1393
diff changeset
418 # this is the "cookie path" for this tracker (ie. the path part of
b3e1e9ab0500 fixed cookie path to use TRACKER_WEB [SF#667020]
Richard Jones <richard@users.sourceforge.net>
parents: 1393
diff changeset
419 # the "base" url)
4362
74476eaac38a more modernisation
Richard Jones <richard@users.sourceforge.net>
parents: 4344
diff changeset
420 self.cookie_path = urllib_.urlparse(self.base)[2]
2946
661028d24cd2 support for multiple cookie headers in single http response;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2942
diff changeset
421 # cookies to set in http responce
661028d24cd2 support for multiple cookie headers in single http response;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2942
diff changeset
422 # {(path, name): (value, expire)}
3989
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
423 self._cookies = {}
1398
b3e1e9ab0500 fixed cookie path to use TRACKER_WEB [SF#667020]
Richard Jones <richard@users.sourceforge.net>
parents: 1393
diff changeset
424
5201
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
425 # define a unique nonce. Can be used for Content Security Policy
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
426 # nonces for scripts.
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
427 self.client_nonce = self._gen_nonce()
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
428
1157
26c8cb2162d7 fixed various URL / base URL issues
Richard Jones <richard@users.sourceforge.net>
parents: 1153
diff changeset
429 # see if we need to re-parse the environment for the form (eg Zope)
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
430 if form is None:
5608
5df309febe49 Path to support OPTIONS verb when using rest interface via
John Rouillard <rouilj@ieee.org>
parents: 5603
diff changeset
431 # cgi.FieldStorage doesn't special case OPTIONS, DELETE or
5df309febe49 Path to support OPTIONS verb when using rest interface via
John Rouillard <rouilj@ieee.org>
parents: 5603
diff changeset
432 # PATCH verbs. They are processed like POST. So FieldStorage
5df309febe49 Path to support OPTIONS verb when using rest interface via
John Rouillard <rouilj@ieee.org>
parents: 5603
diff changeset
433 # hangs on these verbs trying to read posted data that
5df309febe49 Path to support OPTIONS verb when using rest interface via
John Rouillard <rouilj@ieee.org>
parents: 5603
diff changeset
434 # will never arrive.
5df309febe49 Path to support OPTIONS verb when using rest interface via
John Rouillard <rouilj@ieee.org>
parents: 5603
diff changeset
435 # If not defined, set CONTENT_LENGTH to 0 so it doesn't
5df309febe49 Path to support OPTIONS verb when using rest interface via
John Rouillard <rouilj@ieee.org>
parents: 5603
diff changeset
436 # hang reading the data.
5df309febe49 Path to support OPTIONS verb when using rest interface via
John Rouillard <rouilj@ieee.org>
parents: 5603
diff changeset
437 if self.env['REQUEST_METHOD'] in ['OPTIONS', 'DELETE', 'PATCH']:
5df309febe49 Path to support OPTIONS verb when using rest interface via
John Rouillard <rouilj@ieee.org>
parents: 5603
diff changeset
438 if 'CONTENT_LENGTH' not in self.env:
5df309febe49 Path to support OPTIONS verb when using rest interface via
John Rouillard <rouilj@ieee.org>
parents: 5603
diff changeset
439 self.env['CONTENT_LENGTH'] = 0
5df309febe49 Path to support OPTIONS verb when using rest interface via
John Rouillard <rouilj@ieee.org>
parents: 5603
diff changeset
440 logger.debug("Setting CONTENT_LENGTH to 0 for method: %s",
5df309febe49 Path to support OPTIONS verb when using rest interface via
John Rouillard <rouilj@ieee.org>
parents: 5603
diff changeset
441 self.env['REQUEST_METHOD'])
5df309febe49 Path to support OPTIONS verb when using rest interface via
John Rouillard <rouilj@ieee.org>
parents: 5603
diff changeset
442
5653
ba67e397f063 Fix string/bytes issues under python 3.
John Rouillard <rouilj@ieee.org>
parents: 5624
diff changeset
443 # cgi.FieldStorage must save all data as
5656
d26d2590cd8c Implement different workaround for https://bugs.python.org/issue27777
John Rouillard <rouilj@ieee.org>
parents: 5655
diff changeset
444 # binary/bytes. Subclass BinaryFieldStorage does this.
d26d2590cd8c Implement different workaround for https://bugs.python.org/issue27777
John Rouillard <rouilj@ieee.org>
parents: 5655
diff changeset
445 # It's a workaround for a bug in cgi.FieldStorage. See class
d26d2590cd8c Implement different workaround for https://bugs.python.org/issue27777
John Rouillard <rouilj@ieee.org>
parents: 5655
diff changeset
446 # def for details.
d26d2590cd8c Implement different workaround for https://bugs.python.org/issue27777
John Rouillard <rouilj@ieee.org>
parents: 5655
diff changeset
447 self.form = BinaryFieldStorage(fp=request.rfile, environ=env)
5554
a06a88ed38ae Fake a list property to prevent "Error: not indexable".
martin.v.loewis <martin.v.loewis>
parents: 5549
diff changeset
448 # In some case (e.g. content-type application/xml), cgi
a06a88ed38ae Fake a list property to prevent "Error: not indexable".
martin.v.loewis <martin.v.loewis>
parents: 5549
diff changeset
449 # will not parse anything. Fake a list property in this case
a06a88ed38ae Fake a list property to prevent "Error: not indexable".
martin.v.loewis <martin.v.loewis>
parents: 5549
diff changeset
450 if self.form.list is None:
a06a88ed38ae Fake a list property to prevent "Error: not indexable".
martin.v.loewis <martin.v.loewis>
parents: 5549
diff changeset
451 self.form.list = []
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
452 else:
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
453 self.form = form
1157
26c8cb2162d7 fixed various URL / base URL issues
Richard Jones <richard@users.sourceforge.net>
parents: 1153
diff changeset
454
26c8cb2162d7 fixed various URL / base URL issues
Richard Jones <richard@users.sourceforge.net>
parents: 1153
diff changeset
455 # turn debugging on/off
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
456 try:
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
457 self.debug = int(env.get("ROUNDUP_DEBUG", 0))
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
458 except ValueError:
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
459 # someone gave us a non-int debug level, turn it off
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
460 self.debug = 0
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
461
1157
26c8cb2162d7 fixed various URL / base URL issues
Richard Jones <richard@users.sourceforge.net>
parents: 1153
diff changeset
462 # flag to indicate that the HTTP headers have been sent
26c8cb2162d7 fixed various URL / base URL issues
Richard Jones <richard@users.sourceforge.net>
parents: 1153
diff changeset
463 self.headers_done = 0
26c8cb2162d7 fixed various URL / base URL issues
Richard Jones <richard@users.sourceforge.net>
parents: 1153
diff changeset
464
1120
c26471971d18 Exposed the Batch mechanism through the top-level "utils" variable.
Richard Jones <richard@users.sourceforge.net>
parents: 1103
diff changeset
465 # additional headers to send with the request - must be registered
c26471971d18 Exposed the Batch mechanism through the top-level "utils" variable.
Richard Jones <richard@users.sourceforge.net>
parents: 1103
diff changeset
466 # before the first write
c26471971d18 Exposed the Batch mechanism through the top-level "utils" variable.
Richard Jones <richard@users.sourceforge.net>
parents: 1103
diff changeset
467 self.additional_headers = {}
c26471971d18 Exposed the Batch mechanism through the top-level "utils" variable.
Richard Jones <richard@users.sourceforge.net>
parents: 1103
diff changeset
468 self.response_code = 200
c26471971d18 Exposed the Batch mechanism through the top-level "utils" variable.
Richard Jones <richard@users.sourceforge.net>
parents: 1103
diff changeset
469
2947
e611be5ee6c4 initialize self.charset early to enable html output for tracebacks...
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2946
diff changeset
470 # default character set
e611be5ee6c4 initialize self.charset early to enable html output for tracebacks...
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2946
diff changeset
471 self.charset = self.STORAGE_CHARSET
e611be5ee6c4 initialize self.charset early to enable html output for tracebacks...
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2946
diff changeset
472
3989
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
473 # parse cookies (used for charset lookups)
3916
57ad3e2c2545 handle bad cookies
Justus Pendleton <jpend@users.sourceforge.net>
parents: 3900
diff changeset
474 # use our own LiberalCookie to handle bad apps on the same
57ad3e2c2545 handle bad cookies
Justus Pendleton <jpend@users.sourceforge.net>
parents: 3900
diff changeset
475 # server that have set cookies that are out of spec
57ad3e2c2545 handle bad cookies
Justus Pendleton <jpend@users.sourceforge.net>
parents: 3900
diff changeset
476 self.cookie = LiberalCookie(self.env.get('HTTP_COOKIE', ''))
2279
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
477
2928
81c99c857b57 applied patch [SF#1067690]
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2923
diff changeset
478 self.user = None
81c99c857b57 applied patch [SF#1067690]
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2923
diff changeset
479 self.userid = None
2948
deda13909085 factor out get_action_class so it may be called from other places
Richard Jones <richard@users.sourceforge.net>
parents: 2947
diff changeset
480 self.nodeid = None
deda13909085 factor out get_action_class so it may be called from other places
Richard Jones <richard@users.sourceforge.net>
parents: 2947
diff changeset
481 self.classname = None
deda13909085 factor out get_action_class so it may be called from other places
Richard Jones <richard@users.sourceforge.net>
parents: 2947
diff changeset
482 self.template = None
2928
81c99c857b57 applied patch [SF#1067690]
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2923
diff changeset
483
5201
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
484 def _gen_nonce(self):
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
485 """ generate a unique nonce """
5488
52cb53eedf77 reworked random number use
Christof Meerwald <cmeerw@cmeerw.org>
parents: 5475
diff changeset
486 n = b2s(base64.b32encode(random_.token_bytes(40)))
5201
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
487 return n
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
488
2467
76ead526113d client instances may be used as translation engines.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2366
diff changeset
489 def setTranslator(self, translator=None):
76ead526113d client instances may be used as translation engines.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2366
diff changeset
490 """Replace the translation engine
76ead526113d client instances may be used as translation engines.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2366
diff changeset
491
76ead526113d client instances may be used as translation engines.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2366
diff changeset
492 'translator'
2557
ff02e9851592 translator object must be Roundup Translation Service...
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2514
diff changeset
493 is TranslationService instance.
ff02e9851592 translator object must be Roundup Translation Service...
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2514
diff changeset
494 It must define methods 'translate' (TAL-compatible i18n),
ff02e9851592 translator object must be Roundup Translation Service...
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2514
diff changeset
495 'gettext' and 'ngettext' (gettext-compatible i18n).
2467
76ead526113d client instances may be used as translation engines.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2366
diff changeset
496
2557
ff02e9851592 translator object must be Roundup Translation Service...
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2514
diff changeset
497 If omitted, create default TranslationService.
2467
76ead526113d client instances may be used as translation engines.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2366
diff changeset
498 """
76ead526113d client instances may be used as translation engines.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2366
diff changeset
499 if translator is None:
2808
18c28d22b3b5 pass tracker home directory to get_translation()
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2800
diff changeset
500 translator = TranslationService.get_translation(
2923
29563959c026 language defaults to config option TRACKER_LANGUAGE
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2906
diff changeset
501 language=self.instance.config["TRACKER_LANGUAGE"],
2808
18c28d22b3b5 pass tracker home directory to get_translation()
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2800
diff changeset
502 tracker_home=self.instance.config["TRACKER_HOME"])
2467
76ead526113d client instances may be used as translation engines.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2366
diff changeset
503 self.translator = translator
76ead526113d client instances may be used as translation engines.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2366
diff changeset
504 self._ = self.gettext = translator.gettext
76ead526113d client instances may be used as translation engines.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2366
diff changeset
505 self.ngettext = translator.ngettext
76ead526113d client instances may be used as translation engines.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2366
diff changeset
506
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
507 def main(self):
4065
1e28d58c6d1c Uniformly use """...""" instead of '''...''' for comments.
Stefan Seefeld <stefan@seefeld.name>
parents: 4064
diff changeset
508 """ Wrap the real main in a try/finally so we always close off the db.
1e28d58c6d1c Uniformly use """...""" instead of '''...''' for comments.
Stefan Seefeld <stefan@seefeld.name>
parents: 4064
diff changeset
509 """
5924
b40059d7036f issue2550925 strip HTTP_PROXY environment variable
John Rouillard <rouilj@ieee.org>
parents: 5881
diff changeset
510
b40059d7036f issue2550925 strip HTTP_PROXY environment variable
John Rouillard <rouilj@ieee.org>
parents: 5881
diff changeset
511 # strip HTTP_PROXY issue2550925 in case
b40059d7036f issue2550925 strip HTTP_PROXY environment variable
John Rouillard <rouilj@ieee.org>
parents: 5881
diff changeset
512 # PROXY header is set.
b40059d7036f issue2550925 strip HTTP_PROXY environment variable
John Rouillard <rouilj@ieee.org>
parents: 5881
diff changeset
513 if 'HTTP_PROXY' in self.env:
b40059d7036f issue2550925 strip HTTP_PROXY environment variable
John Rouillard <rouilj@ieee.org>
parents: 5881
diff changeset
514 del(self.env['HTTP_PROXY'])
b40059d7036f issue2550925 strip HTTP_PROXY environment variable
John Rouillard <rouilj@ieee.org>
parents: 5881
diff changeset
515 if 'HTTP_PROXY' in os.environ:
b40059d7036f issue2550925 strip HTTP_PROXY environment variable
John Rouillard <rouilj@ieee.org>
parents: 5881
diff changeset
516 del(os.environ['HTTP_PROXY'])
b40059d7036f issue2550925 strip HTTP_PROXY environment variable
John Rouillard <rouilj@ieee.org>
parents: 5881
diff changeset
517
5603
79da1ca2f94b Make xmlrpc and rest APIs configurable
Ralf Schlatterbeck <rsc@runtux.com>
parents: 5568
diff changeset
518 xmlrpc_enabled = self.instance.config.WEB_ENABLE_XMLRPC
79da1ca2f94b Make xmlrpc and rest APIs configurable
Ralf Schlatterbeck <rsc@runtux.com>
parents: 5568
diff changeset
519 rest_enabled = self.instance.config.WEB_ENABLE_REST
1133
36ec30d286ea Cleaned up CHANGES/TODO
Richard Jones <richard@users.sourceforge.net>
parents: 1130
diff changeset
520 try:
5603
79da1ca2f94b Make xmlrpc and rest APIs configurable
Ralf Schlatterbeck <rsc@runtux.com>
parents: 5568
diff changeset
521 if xmlrpc_enabled and self.path == 'xmlrpc':
4079
edf526c91412 * Refactor XMLRPC interface.
Stefan Seefeld <stefan@seefeld.name>
parents: 4077
diff changeset
522 self.handle_xmlrpc()
5603
79da1ca2f94b Make xmlrpc and rest APIs configurable
Ralf Schlatterbeck <rsc@runtux.com>
parents: 5568
diff changeset
523 elif rest_enabled and (self.path == 'rest' or
79da1ca2f94b Make xmlrpc and rest APIs configurable
Ralf Schlatterbeck <rsc@runtux.com>
parents: 5568
diff changeset
524 self.path[:5] == 'rest/'):
5556
d75aa88c2a99 Added RestInstance and calling rest from client.py
Chau Nguyen <dangchau1991@yahoo.com>
parents: 5555
diff changeset
525 self.handle_rest()
4079
edf526c91412 * Refactor XMLRPC interface.
Stefan Seefeld <stefan@seefeld.name>
parents: 4077
diff changeset
526 else:
edf526c91412 * Refactor XMLRPC interface.
Stefan Seefeld <stefan@seefeld.name>
parents: 4077
diff changeset
527 self.inner_main()
1133
36ec30d286ea Cleaned up CHANGES/TODO
Richard Jones <richard@users.sourceforge.net>
parents: 1130
diff changeset
528 finally:
36ec30d286ea Cleaned up CHANGES/TODO
Richard Jones <richard@users.sourceforge.net>
parents: 1130
diff changeset
529 if hasattr(self, 'db'):
36ec30d286ea Cleaned up CHANGES/TODO
Richard Jones <richard@users.sourceforge.net>
parents: 1130
diff changeset
530 self.db.close()
4079
edf526c91412 * Refactor XMLRPC interface.
Stefan Seefeld <stefan@seefeld.name>
parents: 4077
diff changeset
531
edf526c91412 * Refactor XMLRPC interface.
Stefan Seefeld <stefan@seefeld.name>
parents: 4077
diff changeset
532
edf526c91412 * Refactor XMLRPC interface.
Stefan Seefeld <stefan@seefeld.name>
parents: 4077
diff changeset
533 def handle_xmlrpc(self):
4919
24209344b507 Link /xmlrpc to docs if accessed with browser
anatoly techtonik <techtonik@gmail.com>
parents: 4903
diff changeset
534 if self.env.get('CONTENT_TYPE') != 'text/xml':
5437
a1971da1c5da Python 3 preparation: send bytes to socket in cgi/client.py.
Joseph Myers <jsm@polyomino.org.uk>
parents: 5430
diff changeset
5456
0fb04e717de0 fix encoding in handle_xmlrpc
Christof Meerwald <cmeerw@cmeerw.org>
parents: 5441
diff changeset
537 b"XML-RPC interface</a>.")
4919
24209344b507 Link /xmlrpc to docs if accessed with browser
anatoly techtonik <techtonik@gmail.com>
parents: 4903
diff changeset
538 return
4079
edf526c91412 * Refactor XMLRPC interface.
Stefan Seefeld <stefan@seefeld.name>
parents: 4077
diff changeset
539
edf526c91412 * Refactor XMLRPC interface.
Stefan Seefeld <stefan@seefeld.name>
parents: 4077
diff changeset
540 # Pull the raw XML out of the form. The "value" attribute
edf526c91412 * Refactor XMLRPC interface.
Stefan Seefeld <stefan@seefeld.name>
parents: 4077
diff changeset
541 # will be the raw content of the POST request.
edf526c91412 * Refactor XMLRPC interface.
Stefan Seefeld <stefan@seefeld.name>
parents: 4077
diff changeset
542 assert self.form.file
edf526c91412 * Refactor XMLRPC interface.
Stefan Seefeld <stefan@seefeld.name>
parents: 4077
diff changeset
543 input = self.form.value
edf526c91412 * Refactor XMLRPC interface.
Stefan Seefeld <stefan@seefeld.name>
parents: 4077
diff changeset
544 # So that the rest of Roundup can query the form in the
edf526c91412 * Refactor XMLRPC interface.
Stefan Seefeld <stefan@seefeld.name>
parents: 4077
diff changeset
545 # usual way, we create an empty list of fields.
edf526c91412 * Refactor XMLRPC interface.
Stefan Seefeld <stefan@seefeld.name>
parents: 4077
diff changeset
546 self.form.list = []
edf526c91412 * Refactor XMLRPC interface.
Stefan Seefeld <stefan@seefeld.name>
parents: 4077
diff changeset
547
edf526c91412 * Refactor XMLRPC interface.
Stefan Seefeld <stefan@seefeld.name>
parents: 4077
diff changeset
548 # Set the charset and language, since other parts of
edf526c91412 * Refactor XMLRPC interface.
Stefan Seefeld <stefan@seefeld.name>
parents: 4077
diff changeset
549 # Roundup may depend upon that.
edf526c91412 * Refactor XMLRPC interface.
Stefan Seefeld <stefan@seefeld.name>
parents: 4077
diff changeset
550 self.determine_charset()
6658
408fd477761f Add i18n object to roundupdb.Database
Ralf Schlatterbeck <rsc@runtux.com>
parents: 6656
diff changeset
551 if self.instance.config["WEB_TRANSLATE_XMLRPC"] :
408fd477761f Add i18n object to roundupdb.Database
Ralf Schlatterbeck <rsc@runtux.com>
parents: 6656
diff changeset
552 self.determine_language()
4079
edf526c91412 * Refactor XMLRPC interface.
Stefan Seefeld <stefan@seefeld.name>
parents: 4077
diff changeset
553 # Open the database as the correct user.
5878
1b57d8f3eb97 Add rudimentery experiment JSON Web Token (jwt) support
John Rouillard <rouilj@ieee.org>
parents: 5847
diff changeset
554 try:
1b57d8f3eb97 Add rudimentery experiment JSON Web Token (jwt) support
John Rouillard <rouilj@ieee.org>
parents: 5847
diff changeset
555 self.determine_user()
5881
9938c40e03bc Add "rest" and "xmlrpc" values for database tx_Source property
John Rouillard <rouilj@ieee.org>
parents: 5879
diff changeset
556 self.db.tx_Source = "xmlrpc"
6658
408fd477761f Add i18n object to roundupdb.Database
Ralf Schlatterbeck <rsc@runtux.com>
parents: 6656
diff changeset
557 self.db.i18n = self.translator
5878
1b57d8f3eb97 Add rudimentery experiment JSON Web Token (jwt) support
John Rouillard <rouilj@ieee.org>
parents: 5847
diff changeset
558 except LoginError as msg:
1b57d8f3eb97 Add rudimentery experiment JSON Web Token (jwt) support
John Rouillard <rouilj@ieee.org>
parents: 5847
diff changeset
559 output = xmlrpc_.client.dumps(
5879
94a7669677ae add permissions to control user of rest and xmlrpc API interfaces.
John Rouillard <rouilj@ieee.org>
parents: 5878
diff changeset
560 xmlrpc_.client.Fault(401, "%s" % msg),
5878
1b57d8f3eb97 Add rudimentery experiment JSON Web Token (jwt) support
John Rouillard <rouilj@ieee.org>
parents: 5847
diff changeset
561 allow_none=True)
5879
94a7669677ae add permissions to control user of rest and xmlrpc API interfaces.
John Rouillard <rouilj@ieee.org>
parents: 5878
diff changeset
562 self.setHeader("Content-Type", "text/xml")
94a7669677ae add permissions to control user of rest and xmlrpc API interfaces.
John Rouillard <rouilj@ieee.org>
parents: 5878
diff changeset
563 self.setHeader("Content-Length", str(len(output)))
94a7669677ae add permissions to control user of rest and xmlrpc API interfaces.
John Rouillard <rouilj@ieee.org>
parents: 5878
diff changeset
564 self.write(s2b(output))
94a7669677ae add permissions to control user of rest and xmlrpc API interfaces.
John Rouillard <rouilj@ieee.org>
parents: 5878
diff changeset
565 return
5878
1b57d8f3eb97 Add rudimentery experiment JSON Web Token (jwt) support
John Rouillard <rouilj@ieee.org>
parents: 5847
diff changeset
566
5879
94a7669677ae add permissions to control user of rest and xmlrpc API interfaces.
John Rouillard <rouilj@ieee.org>
parents: 5878
diff changeset
567 if not self.db.security.hasPermission('Xmlrpc Access', self.userid):
94a7669677ae add permissions to control user of rest and xmlrpc API interfaces.
John Rouillard <rouilj@ieee.org>
parents: 5878
diff changeset
568 output = xmlrpc_.client.dumps(
94a7669677ae add permissions to control user of rest and xmlrpc API interfaces.
John Rouillard <rouilj@ieee.org>
parents: 5878
diff changeset
569 xmlrpc_.client.Fault(403, "Forbidden"),
94a7669677ae add permissions to control user of rest and xmlrpc API interfaces.
John Rouillard <rouilj@ieee.org>
parents: 5878
diff changeset
570 allow_none=True)
94a7669677ae add permissions to control user of rest and xmlrpc API interfaces.
John Rouillard <rouilj@ieee.org>
parents: 5878
diff changeset
571 self.setHeader("Content-Type", "text/xml")
94a7669677ae add permissions to control user of rest and xmlrpc API interfaces.
John Rouillard <rouilj@ieee.org>
parents: 5878
diff changeset
572 self.setHeader("Content-Length", str(len(output)))
94a7669677ae add permissions to control user of rest and xmlrpc API interfaces.
John Rouillard <rouilj@ieee.org>
parents: 5878
diff changeset
573 self.write(s2b(output))
94a7669677ae add permissions to control user of rest and xmlrpc API interfaces.
John Rouillard <rouilj@ieee.org>
parents: 5878
diff changeset
574 return
94a7669677ae add permissions to control user of rest and xmlrpc API interfaces.
John Rouillard <rouilj@ieee.org>
parents: 5878
diff changeset
575
4327
095d92109cc7 allow Anonymous users to log in, and register
Richard Jones <richard@users.sourceforge.net>
parents: 4326
diff changeset
576 self.check_anonymous_access()
4079
edf526c91412 * Refactor XMLRPC interface.
Stefan Seefeld <stefan@seefeld.name>
parents: 4077
diff changeset
577
5220
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
578 try:
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
579 # coverting from function returning true/false to
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
580 # raising exceptions
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
581 # Call csrf with xmlrpc checks enabled.
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
582 # It will return True if everything is ok,
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
583 # raises exception on check failure.
6681
ab2ed11c021e issue2551205: Add support for specifying valid origins for api: xmlrpc/rest
John Rouillard <rouilj@ieee.org>
parents: 6658
diff changeset
584 csrf_ok = self.handle_csrf(api=True)
5248
198b6e810c67 Use Python-3-compatible 'as' syntax for except statements
Eric S. Raymond <esr@thyrsus.com>
parents: 5231
diff changeset
585 except (Unauthorised, UsageError) as msg:
5220
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
586 # report exception back to server
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
587 exc_type, exc_value, exc_tb = sys.exc_info()
5408
e46ce04d5bbc Python 3 preparation: update xmlrpclib / SimpleXMLRPCServer imports.
Joseph Myers <jsm@polyomino.org.uk>
parents: 5395
diff changeset
588 output = xmlrpc_.client.dumps(
e46ce04d5bbc Python 3 preparation: update xmlrpclib / SimpleXMLRPCServer imports.
Joseph Myers <jsm@polyomino.org.uk>
parents: 5395
diff changeset
589 xmlrpc_.client.Fault(1, "%s:%s" % (exc_type, exc_value)),
5220
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
590 allow_none=True)
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
591 csrf_ok = False # we had an error, failed check
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
592
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
593 if csrf_ok == True:
5201
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
594 handler = xmlrpc.RoundupDispatcher(self.db,
4083
bbab97f8ffb2 XMLRPC improvements:
Stefan Seefeld <stefan@seefeld.name>
parents: 4079
diff changeset
595 self.instance.actions,
bbab97f8ffb2 XMLRPC improvements:
Stefan Seefeld <stefan@seefeld.name>
parents: 4079
diff changeset
596 self.translator,
4079
edf526c91412 * Refactor XMLRPC interface.
Stefan Seefeld <stefan@seefeld.name>
parents: 4077
diff changeset
597 allow_none=True)
5474
4c9192393cd9 encoding fixes
Christof Meerwald <cmeerw@cmeerw.org>
parents: 5456
diff changeset
598 output = handler.dispatch(input)
4079
edf526c91412 * Refactor XMLRPC interface.
Stefan Seefeld <stefan@seefeld.name>
parents: 4077
diff changeset
599
edf526c91412 * Refactor XMLRPC interface.
Stefan Seefeld <stefan@seefeld.name>
parents: 4077
diff changeset
600 self.setHeader("Content-Type", "text/xml")
edf526c91412 * Refactor XMLRPC interface.
Stefan Seefeld <stefan@seefeld.name>
parents: 4077
diff changeset
601 self.setHeader("Content-Length", str(len(output)))
edf526c91412 * Refactor XMLRPC interface.
Stefan Seefeld <stefan@seefeld.name>
parents: 4077
diff changeset
602 self.write(output)
4648
e645820e8556 Clean up whitespace in client.py
Ezio Melotti <ezio.melotti@gmail.com>
parents: 4640
diff changeset
603
5556
d75aa88c2a99 Added RestInstance and calling rest from client.py
Chau Nguyen <dangchau1991@yahoo.com>
parents: 5555
diff changeset
604 def handle_rest(self):
d75aa88c2a99 Added RestInstance and calling rest from client.py
Chau Nguyen <dangchau1991@yahoo.com>
parents: 5555
diff changeset
605 # Set the charset and language
d75aa88c2a99 Added RestInstance and calling rest from client.py
Chau Nguyen <dangchau1991@yahoo.com>
parents: 5555
diff changeset
606 self.determine_charset()
6658
408fd477761f Add i18n object to roundupdb.Database
Ralf Schlatterbeck <rsc@runtux.com>
parents: 6656
diff changeset
607 if self.instance.config["WEB_TRANSLATE_REST"] :
408fd477761f Add i18n object to roundupdb.Database
Ralf Schlatterbeck <rsc@runtux.com>
parents: 6656
diff changeset
608 self.determine_language()
5556
d75aa88c2a99 Added RestInstance and calling rest from client.py
Chau Nguyen <dangchau1991@yahoo.com>
parents: 5555
diff changeset
609 # Open the database as the correct user.
d75aa88c2a99 Added RestInstance and calling rest from client.py
Chau Nguyen <dangchau1991@yahoo.com>
parents: 5555
diff changeset
610 # TODO: add everything to RestfulDispatcher
5666
d660d1c1ba63 Handle LoginError in rest code. Stop standard "an error occurred check
John Rouillard <rouilj@ieee.org>
parents: 5657
diff changeset
611 try:
d660d1c1ba63 Handle LoginError in rest code. Stop standard "an error occurred check
John Rouillard <rouilj@ieee.org>
parents: 5657
diff changeset
612 self.determine_user()
5881
9938c40e03bc Add "rest" and "xmlrpc" values for database tx_Source property
John Rouillard <rouilj@ieee.org>
parents: 5879
diff changeset
613 self.db.tx_Source = "rest"
6658
408fd477761f Add i18n object to roundupdb.Database
Ralf Schlatterbeck <rsc@runtux.com>
parents: 6656
diff changeset
614 self.db.i18n = self.translator
5666
d660d1c1ba63 Handle LoginError in rest code. Stop standard "an error occurred check
John Rouillard <rouilj@ieee.org>
parents: 5657
diff changeset
615 except LoginError as err:
d660d1c1ba63 Handle LoginError in rest code. Stop standard "an error occurred check
John Rouillard <rouilj@ieee.org>
parents: 5657
diff changeset
616 self.response_code = http_.client.UNAUTHORIZED
5878
1b57d8f3eb97 Add rudimentery experiment JSON Web Token (jwt) support
John Rouillard <rouilj@ieee.org>
parents: 5847
diff changeset
617 output = s2b("Invalid Login - %s"%str(err))
5666
d660d1c1ba63 Handle LoginError in rest code. Stop standard "an error occurred check
John Rouillard <rouilj@ieee.org>
parents: 5657
diff changeset
618 self.setHeader("Content-Length", str(len(output)))
d660d1c1ba63 Handle LoginError in rest code. Stop standard "an error occurred check
John Rouillard <rouilj@ieee.org>
parents: 5657
diff changeset
619 self.setHeader("Content-Type", "text/plain")
d660d1c1ba63 Handle LoginError in rest code. Stop standard "an error occurred check
John Rouillard <rouilj@ieee.org>
parents: 5657
diff changeset
620 self.write(output)
d660d1c1ba63 Handle LoginError in rest code. Stop standard "an error occurred check
John Rouillard <rouilj@ieee.org>
parents: 5657
diff changeset
621 return
d660d1c1ba63 Handle LoginError in rest code. Stop standard "an error occurred check
John Rouillard <rouilj@ieee.org>
parents: 5657
diff changeset
622
6693
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
623 # allow preflight request even if unauthenticated
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
624 if ( self.env['REQUEST_METHOD'] == "OPTIONS"
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
625 and self.request.headers.get ("Access-Control-Request-Headers")
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
626 and self.request.headers.get ("Access-Control-Request-Method")
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
627 and self.request.headers.get ("Origin")
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
628 ):
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
629 # verify Origin is allowed
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
630 if not self.is_origin_header_ok(api=True):
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
631 # Use code 400 as 401 and 403 imply that authentication
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
632 # is needed or authenticates person is not authorized.
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
633 # Preflight doesn't do authentication.
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
634 self.response_code = 400
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
635 msg = self._("Client is not allowed to use Rest Interface.")
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
636 output = s2b(
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
637 '{ "error": { "status": 400, "msg": "%s" } }'%msg )
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
638 self.setHeader("Content-Length", str(len(output)))
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
639 self.setHeader("Content-Type", "application/json")
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
640 self.write(output)
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
641 return
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
642
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
643 # Call rest library to handle the pre-flight request
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
644 handler = rest.RestfulInstance(self, self.db)
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
645 output = handler.dispatch(self.env['REQUEST_METHOD'],
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
646 self.path, self.form)
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
647
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
648 elif not self.db.security.hasPermission('Rest Access', self.userid):
5879
94a7669677ae add permissions to control user of rest and xmlrpc API interfaces.
John Rouillard <rouilj@ieee.org>
parents: 5878
diff changeset
649 self.response_code = 403
6504
e162845193c4 Eliminate hang with unauthorized use of REST interface.
John Rouillard <rouilj@ieee.org>
parents: 6467
diff changeset
650 output = s2b('{ "error": { "status": 403, "msg": "Forbidden." } }')
e162845193c4 Eliminate hang with unauthorized use of REST interface.
John Rouillard <rouilj@ieee.org>
parents: 6467
diff changeset
651 self.setHeader("Content-Length", str(len(output)))
e162845193c4 Eliminate hang with unauthorized use of REST interface.
John Rouillard <rouilj@ieee.org>
parents: 6467
diff changeset
652 self.setHeader("Content-Type", "application/json")
e162845193c4 Eliminate hang with unauthorized use of REST interface.
John Rouillard <rouilj@ieee.org>
parents: 6467
diff changeset
653 self.write(output)
5879
94a7669677ae add permissions to control user of rest and xmlrpc API interfaces.
John Rouillard <rouilj@ieee.org>
parents: 5878
diff changeset
654 return
94a7669677ae add permissions to control user of rest and xmlrpc API interfaces.
John Rouillard <rouilj@ieee.org>
parents: 5878
diff changeset
655
5556
d75aa88c2a99 Added RestInstance and calling rest from client.py
Chau Nguyen <dangchau1991@yahoo.com>
parents: 5555
diff changeset
656 self.check_anonymous_access()
d75aa88c2a99 Added RestInstance and calling rest from client.py
Chau Nguyen <dangchau1991@yahoo.com>
parents: 5555
diff changeset
657
5696
b67636bc87d0 Add CSRF protection to rest code path. Follow same model as for
John Rouillard <rouilj@ieee.org>
parents: 5671
diff changeset
658 try:
6681
ab2ed11c021e issue2551205: Add support for specifying valid origins for api: xmlrpc/rest
John Rouillard <rouilj@ieee.org>
parents: 6658
diff changeset
659 # Call csrf with api (xmlrpc, rest) checks enabled.
5696
b67636bc87d0 Add CSRF protection to rest code path. Follow same model as for
John Rouillard <rouilj@ieee.org>
parents: 5671
diff changeset
660 # It will return True if everything is ok,
b67636bc87d0 Add CSRF protection to rest code path. Follow same model as for
John Rouillard <rouilj@ieee.org>
parents: 5671
diff changeset
661 # raises exception on check failure.
6681
ab2ed11c021e issue2551205: Add support for specifying valid origins for api: xmlrpc/rest
John Rouillard <rouilj@ieee.org>
parents: 6658
diff changeset
662 csrf_ok = self.handle_csrf(api=True)
5696
b67636bc87d0 Add CSRF protection to rest code path. Follow same model as for
John Rouillard <rouilj@ieee.org>
parents: 5671
diff changeset
663 except (Unauthorised, UsageError) as msg:
b67636bc87d0 Add CSRF protection to rest code path. Follow same model as for
John Rouillard <rouilj@ieee.org>
parents: 5671
diff changeset
664 # FIXME should return what the client requests
b67636bc87d0 Add CSRF protection to rest code path. Follow same model as for
John Rouillard <rouilj@ieee.org>
parents: 5671
diff changeset
665 # via accept header.
6693
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
666 output = s2b('{ "error": { "status": 400, "msg": "%s"}}'% str(msg))
5696
b67636bc87d0 Add CSRF protection to rest code path. Follow same model as for
John Rouillard <rouilj@ieee.org>
parents: 5671
diff changeset
667 self.response_code = 400
b67636bc87d0 Add CSRF protection to rest code path. Follow same model as for
John Rouillard <rouilj@ieee.org>
parents: 5671
diff changeset
668 self.setHeader("Content-Length", str(len(output)))
6693
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
669 self.setHeader("Content-Type", "application/json")
5696
b67636bc87d0 Add CSRF protection to rest code path. Follow same model as for
John Rouillard <rouilj@ieee.org>
parents: 5671
diff changeset
670 self.write(output)
b67636bc87d0 Add CSRF protection to rest code path. Follow same model as for
John Rouillard <rouilj@ieee.org>
parents: 5671
diff changeset
671 csrf_ok = False # we had an error, failed check
b67636bc87d0 Add CSRF protection to rest code path. Follow same model as for
John Rouillard <rouilj@ieee.org>
parents: 5671
diff changeset
672 return
5556
d75aa88c2a99 Added RestInstance and calling rest from client.py
Chau Nguyen <dangchau1991@yahoo.com>
parents: 5555
diff changeset
673
5696
b67636bc87d0 Add CSRF protection to rest code path. Follow same model as for
John Rouillard <rouilj@ieee.org>
parents: 5671
diff changeset
674 # With the return above the if will never be false,
b67636bc87d0 Add CSRF protection to rest code path. Follow same model as for
John Rouillard <rouilj@ieee.org>
parents: 5671
diff changeset
675 # Keeping the if so we can remove return to pass
b67636bc87d0 Add CSRF protection to rest code path. Follow same model as for
John Rouillard <rouilj@ieee.org>
parents: 5671
diff changeset
676 # output though and format output according to accept
b67636bc87d0 Add CSRF protection to rest code path. Follow same model as for
John Rouillard <rouilj@ieee.org>
parents: 5671
diff changeset
677 # header.
b67636bc87d0 Add CSRF protection to rest code path. Follow same model as for
John Rouillard <rouilj@ieee.org>
parents: 5671
diff changeset
678 if csrf_ok == True:
b67636bc87d0 Add CSRF protection to rest code path. Follow same model as for
John Rouillard <rouilj@ieee.org>
parents: 5671
diff changeset
679 # Call rest library to handle the request
b67636bc87d0 Add CSRF protection to rest code path. Follow same model as for
John Rouillard <rouilj@ieee.org>
parents: 5671
diff changeset
680 handler = rest.RestfulInstance(self, self.db)
b67636bc87d0 Add CSRF protection to rest code path. Follow same model as for
John Rouillard <rouilj@ieee.org>
parents: 5671
diff changeset
681 output = handler.dispatch(self.env['REQUEST_METHOD'],
b67636bc87d0 Add CSRF protection to rest code path. Follow same model as for
John Rouillard <rouilj@ieee.org>
parents: 5671
diff changeset
682 self.path, self.form)
b67636bc87d0 Add CSRF protection to rest code path. Follow same model as for
John Rouillard <rouilj@ieee.org>
parents: 5671
diff changeset
683
b67636bc87d0 Add CSRF protection to rest code path. Follow same model as for
John Rouillard <rouilj@ieee.org>
parents: 5671
diff changeset
684 # type header set by rest handler
5556
d75aa88c2a99 Added RestInstance and calling rest from client.py
Chau Nguyen <dangchau1991@yahoo.com>
parents: 5555
diff changeset
685 # self.setHeader("Content-Type", "text/xml")
6509
1fc765ef6379 Fix 204 responses, hangs and crashes with REST.
John Rouillard <rouilj@ieee.org>
parents: 6504
diff changeset
686 if self.response_code == 204: # no body with 204
1fc765ef6379 Fix 204 responses, hangs and crashes with REST.
John Rouillard <rouilj@ieee.org>
parents: 6504
diff changeset
687 self.write("")
1fc765ef6379 Fix 204 responses, hangs and crashes with REST.
John Rouillard <rouilj@ieee.org>
parents: 6504
diff changeset
688 else:
1fc765ef6379 Fix 204 responses, hangs and crashes with REST.
John Rouillard <rouilj@ieee.org>
parents: 6504
diff changeset
689 self.setHeader("Content-Length", str(len(output)))
1fc765ef6379 Fix 204 responses, hangs and crashes with REST.
John Rouillard <rouilj@ieee.org>
parents: 6504
diff changeset
690 self.write(output)
5556
d75aa88c2a99 Added RestInstance and calling rest from client.py
Chau Nguyen <dangchau1991@yahoo.com>
parents: 5555
diff changeset
691
4880
ca692423e401 Different approach to fix XSS in issue2550817
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4851
diff changeset
692 def add_ok_message(self, msg, escape=True):
ca692423e401 Different approach to fix XSS in issue2550817
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4851
diff changeset
693 add_message(self._ok_message, msg, escape)
ca692423e401 Different approach to fix XSS in issue2550817
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4851
diff changeset
694
ca692423e401 Different approach to fix XSS in issue2550817
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4851
diff changeset
695 def add_error_message(self, msg, escape=True):
ca692423e401 Different approach to fix XSS in issue2550817
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4851
diff changeset
696 add_message(self._error_message, msg, escape)
5166
232c74973a56 issue1408570: fix that form values are lost
Ralf Schlatterbeck <rsc@runtux.com>
parents: 5165
diff changeset
697 # Want to interpret form values when rendering when an error
232c74973a56 issue1408570: fix that form values are lost
Ralf Schlatterbeck <rsc@runtux.com>
parents: 5165
diff changeset
698 # occurred:
232c74973a56 issue1408570: fix that form values are lost
Ralf Schlatterbeck <rsc@runtux.com>
parents: 5165
diff changeset
699 self.form_wins = True
4880
ca692423e401 Different approach to fix XSS in issue2550817
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4851
diff changeset
700
1133
36ec30d286ea Cleaned up CHANGES/TODO
Richard Jones <richard@users.sourceforge.net>
parents: 1130
diff changeset
701 def inner_main(self):
4065
1e28d58c6d1c Uniformly use """...""" instead of '''...''' for comments.
Stefan Seefeld <stefan@seefeld.name>
parents: 4064
diff changeset
702 """Process a request.
2005
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
703
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
704 The most common requests are handled like so:
1054
3d8ea16347aa more explanatory docstring
Richard Jones <richard@users.sourceforge.net>
parents: 1053
diff changeset
705
3427
198fe87b0254 add language detection (patch [SF#1360321])
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3396
diff changeset
706 1. look for charset and language preferences, set up user locale
198fe87b0254 add language detection (patch [SF#1360321])
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3396
diff changeset
707 see determine_charset, determine_language
198fe87b0254 add language detection (patch [SF#1360321])
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3396
diff changeset
708 2. figure out who we are, defaulting to the "anonymous" user
2005
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
709 see determine_user
3427
198fe87b0254 add language detection (patch [SF#1360321])
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3396
diff changeset
710 3. figure out what the request is for - the context
2005
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
711 see determine_context
3427
198fe87b0254 add language detection (patch [SF#1360321])
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3396
diff changeset
712 4. handle any requested action (item edit, search, ...)
2005
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
713 see handle_action
3427
198fe87b0254 add language detection (patch [SF#1360321])
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3396
diff changeset
714 5. render a template, resulting in HTML output
2005
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
715
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
716 In some situations, exceptions occur:
1054
3d8ea16347aa more explanatory docstring
Richard Jones <richard@users.sourceforge.net>
parents: 1053
diff changeset
717
2005
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
718 - HTTP Redirect (generally raised by an action)
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
719 - SendFile (generally raised by determine_context)
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
720 serve up a FileClass "content" property
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
721 - SendStaticFile (generally raised by determine_context)
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
722 serve up a file from the tracker "html" directory
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
723 - Unauthorised (generally raised by an action)
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
724 the action is cancelled, the request is rendered and an error
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
725 message is displayed indicating that permission was not
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
726 granted for the action to take place
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
727 - templating.Unauthorised (templating action not permitted)
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
728 raised by an attempted rendering of a template when the user
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
729 doesn't have permission
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
730 - NotFound (raised wherever it needs to be)
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
731 percolates up to the CGI interface that called the client
4065
1e28d58c6d1c Uniformly use """...""" instead of '''...''' for comments.
Stefan Seefeld <stefan@seefeld.name>
parents: 4064
diff changeset
732 """
4880
ca692423e401 Different approach to fix XSS in issue2550817
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4851
diff changeset
733 self._ok_message = []
ca692423e401 Different approach to fix XSS in issue2550817
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4851
diff changeset
734 self._error_message = []
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
735 try:
2279
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
736 self.determine_charset()
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
737
4109
3f3f44e3534c Address issue2550528.
Stefan Seefeld <stefan@seefeld.name>
parents: 4088
diff changeset
738 try:
3f3f44e3534c Address issue2550528.
Stefan Seefeld <stefan@seefeld.name>
parents: 4088
diff changeset
739 # make sure we're identified (even anonymously)
3f3f44e3534c Address issue2550528.
Stefan Seefeld <stefan@seefeld.name>
parents: 4088
diff changeset
740 self.determine_user()
2938
463902a0fbbb determine user before context:
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2937
diff changeset
741
4109
3f3f44e3534c Address issue2550528.
Stefan Seefeld <stefan@seefeld.name>
parents: 4088
diff changeset
742 # figure out the context and desired content template
3f3f44e3534c Address issue2550528.
Stefan Seefeld <stefan@seefeld.name>
parents: 4088
diff changeset
743 self.determine_context()
3f3f44e3534c Address issue2550528.
Stefan Seefeld <stefan@seefeld.name>
parents: 4088
diff changeset
744
6658
408fd477761f Add i18n object to roundupdb.Database
Ralf Schlatterbeck <rsc@runtux.com>
parents: 6656
diff changeset
745 self.determine_language()
408fd477761f Add i18n object to roundupdb.Database
Ralf Schlatterbeck <rsc@runtux.com>
parents: 6656
diff changeset
746 self.db.i18n = self.translator
408fd477761f Add i18n object to roundupdb.Database
Ralf Schlatterbeck <rsc@runtux.com>
parents: 6656
diff changeset
747
4326
d51a9c498dc4 Fix "Web Access" permission check to allow serving of static files to Anonymous again
Richard Jones <richard@users.sourceforge.net>
parents: 4291
diff changeset
748 # if we've made it this far the context is to a bit of
d51a9c498dc4 Fix "Web Access" permission check to allow serving of static files to Anonymous again
Richard Jones <richard@users.sourceforge.net>
parents: 4291
diff changeset
749 # Roundup's real web interface (not a file being served up)
d51a9c498dc4 Fix "Web Access" permission check to allow serving of static files to Anonymous again
Richard Jones <richard@users.sourceforge.net>
parents: 4291
diff changeset
750 # so do the Anonymous Web Acess check now
4327
095d92109cc7 allow Anonymous users to log in, and register
Richard Jones <richard@users.sourceforge.net>
parents: 4326
diff changeset
751 self.check_anonymous_access()
4326
d51a9c498dc4 Fix "Web Access" permission check to allow serving of static files to Anonymous again
Richard Jones <richard@users.sourceforge.net>
parents: 4291
diff changeset
752
5201
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
753 # check for a valid csrf token identifying the right user
5220
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
754 csrf_ok = True
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
755 try:
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
756 # coverting from function returning true/false to
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
757 # raising exceptions
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
758 csrf_ok = self.handle_csrf()
5248
198b6e810c67 Use Python-3-compatible 'as' syntax for except statements
Eric S. Raymond <esr@thyrsus.com>
parents: 5231
diff changeset
759 except (UsageError, Unauthorised) as msg:
5220
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
760 csrf_ok = False
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
761 self.form_wins = True
5475
da22ff1c3501 use .args for exception information
Christof Meerwald <cmeerw@cmeerw.org>
parents: 5474
diff changeset
762 self._error_message = msg.args
5220
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
763
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
764 if csrf_ok:
5201
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
765 # csrf checks pass. Run actions etc.
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
766 # possibly handle a form submit action (may change
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
767 # self.classname and self.template, and may also
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
768 # append error/ok_messages)
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
769 html = self.handle_action()
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
770 else:
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
771 html = None
1697
c9f67f2f7ba7 don't open the database for static files
Richard Jones <richard@users.sourceforge.net>
parents: 1692
diff changeset
772
4109
3f3f44e3534c Address issue2550528.
Stefan Seefeld <stefan@seefeld.name>
parents: 4088
diff changeset
773 if html:
3f3f44e3534c Address issue2550528.
Stefan Seefeld <stefan@seefeld.name>
parents: 4088
diff changeset
774 self.write_html(html)
3f3f44e3534c Address issue2550528.
Stefan Seefeld <stefan@seefeld.name>
parents: 4088
diff changeset
775 return
2045
d124af927369 Forward-porting of fixes from the maintenance branch.
Richard Jones <richard@users.sourceforge.net>
parents: 2032
diff changeset
776
4109
3f3f44e3534c Address issue2550528.
Stefan Seefeld <stefan@seefeld.name>
parents: 4088
diff changeset
777 # now render the page
3f3f44e3534c Address issue2550528.
Stefan Seefeld <stefan@seefeld.name>
parents: 4088
diff changeset
778 # we don't want clients caching our dynamic pages
3f3f44e3534c Address issue2550528.
Stefan Seefeld <stefan@seefeld.name>
parents: 4088
diff changeset
779 self.additional_headers['Cache-Control'] = 'no-cache'
3f3f44e3534c Address issue2550528.
Stefan Seefeld <stefan@seefeld.name>
parents: 4088
diff changeset
780 # Pragma: no-cache makes Mozilla and its ilk
3f3f44e3534c Address issue2550528.
Stefan Seefeld <stefan@seefeld.name>
parents: 4088
diff changeset
781 # double-load all pages!!
3f3f44e3534c Address issue2550528.
Stefan Seefeld <stefan@seefeld.name>
parents: 4088
diff changeset
782 # self.additional_headers['Pragma'] = 'no-cache'
1579
07a6b8587bc2 removed Pragma: no-cache...
Richard Jones <richard@users.sourceforge.net>
parents: 1562
diff changeset
783
4109
3f3f44e3534c Address issue2550528.
Stefan Seefeld <stefan@seefeld.name>
parents: 4088
diff changeset
784 # pages with messages added expire right now
3f3f44e3534c Address issue2550528.
Stefan Seefeld <stefan@seefeld.name>
parents: 4088
diff changeset
785 # simple views may be cached for a small amount of time
3f3f44e3534c Address issue2550528.
Stefan Seefeld <stefan@seefeld.name>
parents: 4088
diff changeset
786 # TODO? make page expire time configurable
3f3f44e3534c Address issue2550528.
Stefan Seefeld <stefan@seefeld.name>
parents: 4088
diff changeset
787 # <rj> always expire pages, as IE just doesn't seem to do the
3f3f44e3534c Address issue2550528.
Stefan Seefeld <stefan@seefeld.name>
parents: 4088
diff changeset
788 # right thing here :(
3f3f44e3534c Address issue2550528.
Stefan Seefeld <stefan@seefeld.name>
parents: 4088
diff changeset
789 date = time.time() - 1
4880
ca692423e401 Different approach to fix XSS in issue2550817
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4851
diff changeset
790 #if self._error_message or self._ok_message:
4109
3f3f44e3534c Address issue2550528.
Stefan Seefeld <stefan@seefeld.name>
parents: 4088
diff changeset
791 # date = time.time() - 1
3f3f44e3534c Address issue2550528.
Stefan Seefeld <stefan@seefeld.name>
parents: 4088
diff changeset
792 #else:
3f3f44e3534c Address issue2550528.
Stefan Seefeld <stefan@seefeld.name>
parents: 4088
diff changeset
793 # date = time.time() + 5
4980
13f8f88ad984 Replace rfc822 imports with email package (issue2550870)
John Kristensen <john@jerrykan.com>
parents: 4979
diff changeset
794 self.additional_headers['Expires'] = \
13f8f88ad984 Replace rfc822 imports with email package (issue2550870)
John Kristensen <john@jerrykan.com>
parents: 4979
diff changeset
795 email.utils.formatdate(date, usegmt=True)
1552
68ef6deefcf1 cgi fixes
Richard Jones <richard@users.sourceforge.net>
parents: 1538
diff changeset
796
4109
3f3f44e3534c Address issue2550528.
Stefan Seefeld <stefan@seefeld.name>
parents: 4088
diff changeset
797 # render the content
3896
fca0365521fc ignore client shutdown exceptions when sending responses
Justus Pendleton <jpend@users.sourceforge.net>
parents: 3867
diff changeset
798 self.write_html(self.renderContext())
5248
198b6e810c67 Use Python-3-compatible 'as' syntax for except statements
Eric S. Raymond <esr@thyrsus.com>
parents: 5231
diff changeset
799 except SendFile as designator:
4109
3f3f44e3534c Address issue2550528.
Stefan Seefeld <stefan@seefeld.name>
parents: 4088
diff changeset
800 # The call to serve_file may result in an Unauthorised
3f3f44e3534c Address issue2550528.
Stefan Seefeld <stefan@seefeld.name>
parents: 4088
diff changeset
801 # exception or a NotModified exception. Those
3f3f44e3534c Address issue2550528.
Stefan Seefeld <stefan@seefeld.name>
parents: 4088
diff changeset
802 # exceptions will be handled by the outermost set of
3f3f44e3534c Address issue2550528.
Stefan Seefeld <stefan@seefeld.name>
parents: 4088
diff changeset
803 # exception handlers.
6658
408fd477761f Add i18n object to roundupdb.Database
Ralf Schlatterbeck <rsc@runtux.com>
parents: 6656
diff changeset
804 self.determine_language()
408fd477761f Add i18n object to roundupdb.Database
Ralf Schlatterbeck <rsc@runtux.com>
parents: 6656
diff changeset
805 self.db.i18n = self.translator
408fd477761f Add i18n object to roundupdb.Database
Ralf Schlatterbeck <rsc@runtux.com>
parents: 6656
diff changeset
806
4109
3f3f44e3534c Address issue2550528.
Stefan Seefeld <stefan@seefeld.name>
parents: 4088
diff changeset
807 self.serve_file(designator)
5248
198b6e810c67 Use Python-3-compatible 'as' syntax for except statements
Eric S. Raymond <esr@thyrsus.com>
parents: 5231
diff changeset
808 except SendStaticFile as file:
4109
3f3f44e3534c Address issue2550528.
Stefan Seefeld <stefan@seefeld.name>
parents: 4088
diff changeset
809 self.serve_static_file(str(file))
3896
fca0365521fc ignore client shutdown exceptions when sending responses
Justus Pendleton <jpend@users.sourceforge.net>
parents: 3867
diff changeset
810 except IOError:
3900
182ba3207899 wrap comment to less than 75 chars
Justus Pendleton <jpend@users.sourceforge.net>
parents: 3898
diff changeset
811 # IOErrors here are due to the client disconnecting before
4638
1ebc5f16aeda Ignore OpenSSL.SSL.SysCallError similar to IOError.
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4623
diff changeset
812 # receiving the reply.
1ebc5f16aeda Ignore OpenSSL.SSL.SysCallError similar to IOError.
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4623
diff changeset
813 pass
1ebc5f16aeda Ignore OpenSSL.SSL.SysCallError similar to IOError.
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4623
diff changeset
814 except SysCallError:
1ebc5f16aeda Ignore OpenSSL.SSL.SysCallError similar to IOError.
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4623
diff changeset
815 # OpenSSL.SSL.SysCallError is similar to IOError above
3896
fca0365521fc ignore client shutdown exceptions when sending responses
Justus Pendleton <jpend@users.sourceforge.net>
parents: 3867
diff changeset
816 pass
2230
ca2664e095be disable forking server when os.fork() not available [SF#938586]
Richard Jones <richard@users.sourceforge.net>
parents: 2183
diff changeset
817
5248
198b6e810c67 Use Python-3-compatible 'as' syntax for except statements
Eric S. Raymond <esr@thyrsus.com>
parents: 5231
diff changeset
818 except SeriousError as message:
2279
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
819 self.write_html(str(message))
5248
198b6e810c67 Use Python-3-compatible 'as' syntax for except statements
Eric S. Raymond <esr@thyrsus.com>
parents: 5231
diff changeset
820 except Redirect as url:
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
821 # let's redirect - if the url isn't None, then we need to do
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
822 # the headers, otherwise the headers have been set before the
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
823 # exception was raised
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
824 if url:
3736
a2d22d0de0bc WSGI support via roundup.cgi.wsgi_handler
Richard Jones <richard@users.sourceforge.net>
parents: 3687
diff changeset
825 self.additional_headers['Location'] = str(url)
1120
c26471971d18 Exposed the Batch mechanism through the top-level "utils" variable.
Richard Jones <richard@users.sourceforge.net>
parents: 1103
diff changeset
826 self.response_code = 302
2279
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
827 self.write_html('Redirecting to <a href="%s">%s</a>'%(url, url))
5248
198b6e810c67 Use Python-3-compatible 'as' syntax for except statements
Eric S. Raymond <esr@thyrsus.com>
parents: 5231
diff changeset
828 except LoginError as message:
4265
e24a6ca34448 Improve login failure response.
Stefan Seefeld <stefan@seefeld.name>
parents: 4264
diff changeset
829 # The user tried to log in, but did not provide a valid
e24a6ca34448 Improve login failure response.
Stefan Seefeld <stefan@seefeld.name>
parents: 4264
diff changeset
830 # username and password. If we support HTTP
e24a6ca34448 Improve login failure response.
Stefan Seefeld <stefan@seefeld.name>
parents: 4264
diff changeset
831 # authorization, send back a response that will cause the
e24a6ca34448 Improve login failure response.
Stefan Seefeld <stefan@seefeld.name>
parents: 4264
diff changeset
832 # browser to prompt the user again.
e24a6ca34448 Improve login failure response.
Stefan Seefeld <stefan@seefeld.name>
parents: 4264
diff changeset
833 if self.instance.config.WEB_HTTP_AUTH:
4362
74476eaac38a more modernisation
Richard Jones <richard@users.sourceforge.net>
parents: 4344
diff changeset
834 self.response_code = http_.client.UNAUTHORIZED
4265
e24a6ca34448 Improve login failure response.
Stefan Seefeld <stefan@seefeld.name>
parents: 4264
diff changeset
835 realm = self.instance.config.TRACKER_NAME
e24a6ca34448 Improve login failure response.
Stefan Seefeld <stefan@seefeld.name>
parents: 4264
diff changeset
836 self.setHeader("WWW-Authenticate",
e24a6ca34448 Improve login failure response.
Stefan Seefeld <stefan@seefeld.name>
parents: 4264
diff changeset
837 "Basic realm=\"%s\"" % realm)
e24a6ca34448 Improve login failure response.
Stefan Seefeld <stefan@seefeld.name>
parents: 4264
diff changeset
838 else:
4362
74476eaac38a more modernisation
Richard Jones <richard@users.sourceforge.net>
parents: 4344
diff changeset
839 self.response_code = http_.client.FORBIDDEN
4898
850551a1568b Fix issue2550843 (AttributeError: 'Unauthorised' object has no attribute 'replace')
Thomas Arendsen Hein <thomas@intevation.de>
parents: 4880
diff changeset
840 self.renderFrontPage(str(message))
5248
198b6e810c67 Use Python-3-compatible 'as' syntax for except statements
Eric S. Raymond <esr@thyrsus.com>
parents: 5231
diff changeset
841 except Unauthorised as message:
1977
f96592a7c357 changes to support the new templating Unauthorised exception.
Richard Jones <richard@users.sourceforge.net>
parents: 1973
diff changeset
842 # users may always see the front page
4064
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
843 self.response_code = 403
4898
850551a1568b Fix issue2550843 (AttributeError: 'Unauthorised' object has no attribute 'replace')
Thomas Arendsen Hein <thomas@intevation.de>
parents: 4880
diff changeset
844 self.renderFrontPage(str(message))
4109
3f3f44e3534c Address issue2550528.
Stefan Seefeld <stefan@seefeld.name>
parents: 4088
diff changeset
845 except NotModified:
3f3f44e3534c Address issue2550528.
Stefan Seefeld <stefan@seefeld.name>
parents: 4088
diff changeset
846 # send the 304 response
3f3f44e3534c Address issue2550528.
Stefan Seefeld <stefan@seefeld.name>
parents: 4088
diff changeset
847 self.response_code = 304
3f3f44e3534c Address issue2550528.
Stefan Seefeld <stefan@seefeld.name>
parents: 4088
diff changeset
848 self.header()
5248
198b6e810c67 Use Python-3-compatible 'as' syntax for except statements
Eric S. Raymond <esr@thyrsus.com>
parents: 5231
diff changeset
849 except NotFound as e:
5165
a86860224d80 issue2550755: exceptions.NotFound(msg) msg is not reported to user in cgi.
John Rouillard <rouilj@ieee.org>
parents: 5154
diff changeset
850 if self.response_code == 400:
a86860224d80 issue2550755: exceptions.NotFound(msg) msg is not reported to user in cgi.
John Rouillard <rouilj@ieee.org>
parents: 5154
diff changeset
851 # We can't find a parameter (e.g. property name
a86860224d80 issue2550755: exceptions.NotFound(msg) msg is not reported to user in cgi.
John Rouillard <rouilj@ieee.org>
parents: 5154
diff changeset
852 # incorrect). Tell the user what was raised.
a86860224d80 issue2550755: exceptions.NotFound(msg) msg is not reported to user in cgi.
John Rouillard <rouilj@ieee.org>
parents: 5154
diff changeset
853 # Do not change to the 404 template since the
a86860224d80 issue2550755: exceptions.NotFound(msg) msg is not reported to user in cgi.
John Rouillard <rouilj@ieee.org>
parents: 5154
diff changeset
854 # base url is valid just query args are not.
a86860224d80 issue2550755: exceptions.NotFound(msg) msg is not reported to user in cgi.
John Rouillard <rouilj@ieee.org>
parents: 5154
diff changeset
855 # copy the page format from SeriousError _str_ exception.
a86860224d80 issue2550755: exceptions.NotFound(msg) msg is not reported to user in cgi.
John Rouillard <rouilj@ieee.org>
parents: 5154
diff changeset
856 error_page = """
a86860224d80 issue2550755: exceptions.NotFound(msg) msg is not reported to user in cgi.
John Rouillard <rouilj@ieee.org>
parents: 5154
diff changeset
857 <html><head><title>Roundup issue tracker: An error has occurred</title>
a86860224d80 issue2550755: exceptions.NotFound(msg) msg is not reported to user in cgi.
John Rouillard <rouilj@ieee.org>
parents: 5154
diff changeset
858 <link rel="stylesheet" type="text/css" href="@@file/style.css">
a86860224d80 issue2550755: exceptions.NotFound(msg) msg is not reported to user in cgi.
John Rouillard <rouilj@ieee.org>
parents: 5154
diff changeset
859 </head>
a86860224d80 issue2550755: exceptions.NotFound(msg) msg is not reported to user in cgi.
John Rouillard <rouilj@ieee.org>
parents: 5154
diff changeset
860 <body class="body" marginwidth="0" marginheight="0">
a86860224d80 issue2550755: exceptions.NotFound(msg) msg is not reported to user in cgi.
John Rouillard <rouilj@ieee.org>
parents: 5154
diff changeset
861 <p class="error-message">%s</p>
a86860224d80 issue2550755: exceptions.NotFound(msg) msg is not reported to user in cgi.
John Rouillard <rouilj@ieee.org>
parents: 5154
diff changeset
862 </body></html>
a86860224d80 issue2550755: exceptions.NotFound(msg) msg is not reported to user in cgi.
John Rouillard <rouilj@ieee.org>
parents: 5154
diff changeset
863 """
a86860224d80 issue2550755: exceptions.NotFound(msg) msg is not reported to user in cgi.
John Rouillard <rouilj@ieee.org>
parents: 5154
diff changeset
864 self.write_html(error_page%str(e))
a86860224d80 issue2550755: exceptions.NotFound(msg) msg is not reported to user in cgi.
John Rouillard <rouilj@ieee.org>
parents: 5154
diff changeset
865 else:
a86860224d80 issue2550755: exceptions.NotFound(msg) msg is not reported to user in cgi.
John Rouillard <rouilj@ieee.org>
parents: 5154
diff changeset
866 self.response_code = 404
a86860224d80 issue2550755: exceptions.NotFound(msg) msg is not reported to user in cgi.
John Rouillard <rouilj@ieee.org>
parents: 5154
diff changeset
867 self.template = '404'
a86860224d80 issue2550755: exceptions.NotFound(msg) msg is not reported to user in cgi.
John Rouillard <rouilj@ieee.org>
parents: 5154
diff changeset
868 try:
a86860224d80 issue2550755: exceptions.NotFound(msg) msg is not reported to user in cgi.
John Rouillard <rouilj@ieee.org>
parents: 5154
diff changeset
869 cl = self.db.getclass(self.classname)
a86860224d80 issue2550755: exceptions.NotFound(msg) msg is not reported to user in cgi.
John Rouillard <rouilj@ieee.org>
parents: 5154
diff changeset
870 self.write_html(self.renderContext())
a86860224d80 issue2550755: exceptions.NotFound(msg) msg is not reported to user in cgi.
John Rouillard <rouilj@ieee.org>
parents: 5154
diff changeset
871 except KeyError:
a86860224d80 issue2550755: exceptions.NotFound(msg) msg is not reported to user in cgi.
John Rouillard <rouilj@ieee.org>
parents: 5154
diff changeset
872 # we can't map the URL to a class we know about
a86860224d80 issue2550755: exceptions.NotFound(msg) msg is not reported to user in cgi.
John Rouillard <rouilj@ieee.org>
parents: 5154
diff changeset
873 # reraise the NotFound and let roundup_server
a86860224d80 issue2550755: exceptions.NotFound(msg) msg is not reported to user in cgi.
John Rouillard <rouilj@ieee.org>
parents: 5154
diff changeset
874 # handle it
a86860224d80 issue2550755: exceptions.NotFound(msg) msg is not reported to user in cgi.
John Rouillard <rouilj@ieee.org>
parents: 5154
diff changeset
875 raise NotFound(e)
5248
198b6e810c67 Use Python-3-compatible 'as' syntax for except statements
Eric S. Raymond <esr@thyrsus.com>
parents: 5231
diff changeset
876 except FormError as e:
4880
ca692423e401 Different approach to fix XSS in issue2550817
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4851
diff changeset
877 self.add_error_message(self._('Form Error: ') + str(e))
2279
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
878 self.write_html(self.renderContext())
4640
70b1cb9034c3 Ignore IOError and SysCallError also in outer try/except.
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4638
diff changeset
879 except IOError:
70b1cb9034c3 Ignore IOError and SysCallError also in outer try/except.
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4638
diff changeset
880 # IOErrors here are due to the client disconnecting before
70b1cb9034c3 Ignore IOError and SysCallError also in outer try/except.
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4638
diff changeset
881 # receiving the reply.
70b1cb9034c3 Ignore IOError and SysCallError also in outer try/except.
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4638
diff changeset
882 # may happen during write_html and serve_file, too.
70b1cb9034c3 Ignore IOError and SysCallError also in outer try/except.
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4638
diff changeset
883 pass
70b1cb9034c3 Ignore IOError and SysCallError also in outer try/except.
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4638
diff changeset
884 except SysCallError:
70b1cb9034c3 Ignore IOError and SysCallError also in outer try/except.
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4638
diff changeset
885 # OpenSSL.SSL.SysCallError is similar to IOError above
70b1cb9034c3 Ignore IOError and SysCallError also in outer try/except.
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4638
diff changeset
886 # may happen during write_html and serve_file, too.
70b1cb9034c3 Ignore IOError and SysCallError also in outer try/except.
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4638
diff changeset
887 pass
5079
65fef7858606 issue2550826 IOError in detector causes apache 'premature end of script headers' error
John Rouillard <rouilj@ieee.org>
parents: 5073
diff changeset
888 except DetectorError as e:
65fef7858606 issue2550826 IOError in detector causes apache 'premature end of script headers' error
John Rouillard <rouilj@ieee.org>
parents: 5073
diff changeset
889 if not self.instance.config.WEB_DEBUG:
65fef7858606 issue2550826 IOError in detector causes apache 'premature end of script headers' error
John Rouillard <rouilj@ieee.org>
parents: 5073
diff changeset
890 # run when we are not in debug mode, so errors
65fef7858606 issue2550826 IOError in detector causes apache 'premature end of script headers' error
John Rouillard <rouilj@ieee.org>
parents: 5073
diff changeset
891 # go to admin too.
65fef7858606 issue2550826 IOError in detector causes apache 'premature end of script headers' error
John Rouillard <rouilj@ieee.org>
parents: 5073
diff changeset
892 self.send_error_to_admin(e.subject, e.html, e.txt)
65fef7858606 issue2550826 IOError in detector causes apache 'premature end of script headers' error
John Rouillard <rouilj@ieee.org>
parents: 5073
diff changeset
893 self.write_html(e.html)
65fef7858606 issue2550826 IOError in detector causes apache 'premature end of script headers' error
John Rouillard <rouilj@ieee.org>
parents: 5073
diff changeset
894 else:
65fef7858606 issue2550826 IOError in detector causes apache 'premature end of script headers' error
John Rouillard <rouilj@ieee.org>
parents: 5073
diff changeset
895 # in debug mode, only write error to screen.
65fef7858606 issue2550826 IOError in detector causes apache 'premature end of script headers' error
John Rouillard <rouilj@ieee.org>
parents: 5073
diff changeset
896 self.write_html(e.html)
6509
1fc765ef6379 Fix 204 responses, hangs and crashes with REST.
John Rouillard <rouilj@ieee.org>
parents: 6504
diff changeset
897 except Exception as e:
4264
b1e614c6759f Improve error reporting.
Stefan Seefeld <stefan@seefeld.name>
parents: 4263
diff changeset
898 # Something has gone badly wrong. Therefore, we should
b1e614c6759f Improve error reporting.
Stefan Seefeld <stefan@seefeld.name>
parents: 4263
diff changeset
899 # make sure that the response code indicates failure.
4362
74476eaac38a more modernisation
Richard Jones <richard@users.sourceforge.net>
parents: 4344
diff changeset
900 if self.response_code == http_.client.OK:
74476eaac38a more modernisation
Richard Jones <richard@users.sourceforge.net>
parents: 4344
diff changeset
901 self.response_code = http_.client.INTERNAL_SERVER_ERROR
4264
b1e614c6759f Improve error reporting.
Stefan Seefeld <stefan@seefeld.name>
parents: 4263
diff changeset
902 # Help the administrator work out what went wrong.
b1e614c6759f Improve error reporting.
Stefan Seefeld <stefan@seefeld.name>
parents: 4263
diff changeset
903 html = ("<h1>Traceback</h1>"
b1e614c6759f Improve error reporting.
Stefan Seefeld <stefan@seefeld.name>
parents: 4263
diff changeset
904 + cgitb.html(i18n=self.translator)
b1e614c6759f Improve error reporting.
Stefan Seefeld <stefan@seefeld.name>
parents: 4263
diff changeset
905 + ("<h1>Environment Variables</h1><table>%s</table>"
b1e614c6759f Improve error reporting.
Stefan Seefeld <stefan@seefeld.name>
parents: 4263
diff changeset
906 % cgitb.niceDict("", self.env)))
b1e614c6759f Improve error reporting.
Stefan Seefeld <stefan@seefeld.name>
parents: 4263
diff changeset
907 if not self.instance.config.WEB_DEBUG:
b1e614c6759f Improve error reporting.
Stefan Seefeld <stefan@seefeld.name>
parents: 4263
diff changeset
908 exc_info = sys.exc_info()
b1e614c6759f Improve error reporting.
Stefan Seefeld <stefan@seefeld.name>
parents: 4263
diff changeset
909 subject = "Error: %s" % exc_info[1]
4543
d16d9bf655d8 - fix handling of traceback mails to the roundup admin
Ralf Schlatterbeck <schlatterbeck@users.sourceforge.net>
parents: 4530
diff changeset
910 self.send_error_to_admin(subject, html, format_exc())
4880
ca692423e401 Different approach to fix XSS in issue2550817
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4851
diff changeset
911 self.write_html(self._(default_err_msg))
3548
61d48244e7a8 login may now be for a single session
Richard Jones <richard@users.sourceforge.net>
parents: 3494
diff changeset
912 else:
4264
b1e614c6759f Improve error reporting.
Stefan Seefeld <stefan@seefeld.name>
parents: 4263
diff changeset
913 self.write_html(html)
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
914
1372
3931614b1cce cleaning old unused sessions only once per hour, not on every cgi request
Andrey Lebedev <kedder@users.sourceforge.net>
parents: 1358
diff changeset
915 def clean_sessions(self):
3989
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
916 """Deprecated
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
917 XXX remove
1937
4c850112895b Some reformatting and fixing docstrings for emacs.
Johannes Gijsbers <jlgijsbers@users.sourceforge.net>
parents: 1936
diff changeset
918 """
3989
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
919 self.clean_up()
1372
3931614b1cce cleaning old unused sessions only once per hour, not on every cgi request
Andrey Lebedev <kedder@users.sourceforge.net>
parents: 1358
diff changeset
920
3989
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
921 def clean_up(self):
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
922 """Remove expired sessions and One Time Keys.
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
923
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
924 Do it only once an hour.
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
925 """
1372
3931614b1cce cleaning old unused sessions only once per hour, not on every cgi request
Andrey Lebedev <kedder@users.sourceforge.net>
parents: 1358
diff changeset
926 hour = 60*60
3931614b1cce cleaning old unused sessions only once per hour, not on every cgi request
Andrey Lebedev <kedder@users.sourceforge.net>
parents: 1358
diff changeset
927 now = time.time()
3989
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
928
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
929 # XXX: hack - use OTK table to store last_clean time information
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
930 # 'last_clean' string is used instead of otk key
5319
62de601bdf6f Fix commits although a Reject exception is raised
Ralf Schlatterbeck <rsc@runtux.com>
parents: 5248
diff changeset
931 otks = self.db.getOTKManager()
62de601bdf6f Fix commits although a Reject exception is raised
Ralf Schlatterbeck <rsc@runtux.com>
parents: 5248
diff changeset
932 last_clean = otks.get('last_clean', 'last_use', 0)
2046
f913b6beac35 document and make easier the actions-returning-content idiom
Richard Jones <richard@users.sourceforge.net>
parents: 2045
diff changeset
933 if now - last_clean < hour:
f913b6beac35 document and make easier the actions-returning-content idiom
Richard Jones <richard@users.sourceforge.net>
parents: 2045
diff changeset
934 return
f913b6beac35 document and make easier the actions-returning-content idiom
Richard Jones <richard@users.sourceforge.net>
parents: 2045
diff changeset
935
3989
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
936 self.session_api.clean_up()
5319
62de601bdf6f Fix commits although a Reject exception is raised
Ralf Schlatterbeck <rsc@runtux.com>
parents: 5248
diff changeset
937 otks.clean()
62de601bdf6f Fix commits although a Reject exception is raised
Ralf Schlatterbeck <rsc@runtux.com>
parents: 5248
diff changeset
938 otks.set('last_clean', last_use=now)
62de601bdf6f Fix commits although a Reject exception is raised
Ralf Schlatterbeck <rsc@runtux.com>
parents: 5248
diff changeset
939 otks.commit()
1372
3931614b1cce cleaning old unused sessions only once per hour, not on every cgi request
Andrey Lebedev <kedder@users.sourceforge.net>
parents: 1358
diff changeset
940
2279
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
941 def determine_charset(self):
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
942 """Look for client charset in the form parameters or browser cookie.
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
943
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
944 If no charset requested by client, use storage charset (utf-8).
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
945
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
946 If the charset is found, and differs from the storage charset,
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
947 recode all form fields of type 'text/plain'
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
948 """
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
949 # look for client charset
2946
661028d24cd2 support for multiple cookie headers in single http response;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2942
diff changeset
950 charset_parameter = 0
4799
b474adb17fda Fix case where querying form returns a TypeError
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4781
diff changeset
951 # Python 2.6 form may raise a TypeError if list in form is None
b474adb17fda Fix case where querying form returns a TypeError
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4781
diff changeset
952 charset = None
4800
3961b2b91568 2nd case where querying form returns a TypeError
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4799
diff changeset
953 try:
2279
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
954 charset = self.form['@charset'].value
2946
661028d24cd2 support for multiple cookie headers in single http response;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2942
diff changeset
955 if charset.lower() == "none":
661028d24cd2 support for multiple cookie headers in single http response;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2942
diff changeset
956 charset = ""
661028d24cd2 support for multiple cookie headers in single http response;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2942
diff changeset
957 charset_parameter = 1
4799
b474adb17fda Fix case where querying form returns a TypeError
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4781
diff changeset
958 except (KeyError, TypeError):
b474adb17fda Fix case where querying form returns a TypeError
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4781
diff changeset
959 pass
b474adb17fda Fix case where querying form returns a TypeError
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4781
diff changeset
960 if charset is None and 'roundup_charset' in self.cookie:
2279
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
961 charset = self.cookie['roundup_charset'].value
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
962 if charset:
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
963 # make sure the charset is recognized
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
964 try:
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
965 codecs.lookup(charset)
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
966 except LookupError:
4880
ca692423e401 Different approach to fix XSS in issue2550817
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4851
diff changeset
967 self.add_error_message(self._('Unrecognized charset: %r')
2279
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
968 % charset)
2946
661028d24cd2 support for multiple cookie headers in single http response;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2942
diff changeset
969 charset_parameter = 0
2279
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
970 else:
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
971 self.charset = charset.lower()
2946
661028d24cd2 support for multiple cookie headers in single http response;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2942
diff changeset
972 # If we've got a character set in request parameters,
661028d24cd2 support for multiple cookie headers in single http response;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2942
diff changeset
973 # set the browser cookie to keep the preference.
661028d24cd2 support for multiple cookie headers in single http response;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2942
diff changeset
974 # This is done after codecs.lookup to make sure
661028d24cd2 support for multiple cookie headers in single http response;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2942
diff changeset
975 # that we aren't keeping a wrong value.
661028d24cd2 support for multiple cookie headers in single http response;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2942
diff changeset
976 if charset_parameter:
661028d24cd2 support for multiple cookie headers in single http response;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2942
diff changeset
977 self.add_cookie('roundup_charset', charset)
2279
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
978
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
979 # if client charset is different from the storage charset,
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
980 # recode form fields
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
981 # XXX this requires FieldStorage from Python library.
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
982 # mod_python FieldStorage is not supported!
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
983 if self.charset != self.STORAGE_CHARSET:
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
984 decoder = codecs.getdecoder(self.charset)
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
985 encoder = codecs.getencoder(self.STORAGE_CHARSET)
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
986 re_charref = re.compile('&#([0-9]+|x[0-9a-f]+);', re.IGNORECASE)
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
987 def _decode_charref(matchobj):
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
988 num = matchobj.group(1)
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
989 if num[0].lower() == 'x':
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
990 uc = int(num[1:], 16)
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
991 else:
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
992 uc = int(num)
5417
c749d6795bc2 Python 3 preparation: unichr.
Joseph Myers <jsm@polyomino.org.uk>
parents: 5408
diff changeset
993 return uchr(uc)
2279
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
994
4362
74476eaac38a more modernisation
Richard Jones <richard@users.sourceforge.net>
parents: 4344
diff changeset
995 for field_name in self.form:
2279
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
996 field = self.form[field_name]
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
997 if (field.type == 'text/plain') and not field.filename:
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
998 try:
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
999 value = decoder(field.value)[0]
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
1000 except UnicodeError:
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
1001 continue
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
1002 value = re_charref.sub(_decode_charref, value)
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
1003 field.value = encoder(value)[0]
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
1004
3427
198fe87b0254 add language detection (patch [SF#1360321])
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3396
diff changeset
1005 def determine_language(self):
198fe87b0254 add language detection (patch [SF#1360321])
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3396
diff changeset
1006 """Determine the language"""
198fe87b0254 add language detection (patch [SF#1360321])
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3396
diff changeset
1007 # look for language parameter
198fe87b0254 add language detection (patch [SF#1360321])
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3396
diff changeset
1008 # then for language cookie
198fe87b0254 add language detection (patch [SF#1360321])
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3396
diff changeset
1009 # last for the Accept-Language header
4800
3961b2b91568 2nd case where querying form returns a TypeError
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4799
diff changeset
1010 # Python 2.6 form may raise a TypeError if list in form is None
3961b2b91568 2nd case where querying form returns a TypeError
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4799
diff changeset
1011 language = None
3961b2b91568 2nd case where querying form returns a TypeError
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4799
diff changeset
1012 try:
3427
198fe87b0254 add language detection (patch [SF#1360321])
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3396
diff changeset
1013 language = self.form["@language"].value
198fe87b0254 add language detection (patch [SF#1360321])
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3396
diff changeset
1014 if language.lower() == "none":
198fe87b0254 add language detection (patch [SF#1360321])
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3396
diff changeset
1015 language = ""
198fe87b0254 add language detection (patch [SF#1360321])
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3396
diff changeset
1016 self.add_cookie("roundup_language", language)
4800
3961b2b91568 2nd case where querying form returns a TypeError
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4799
diff changeset
1017 except (KeyError, TypeError):
3961b2b91568 2nd case where querying form returns a TypeError
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4799
diff changeset
1018 pass
3961b2b91568 2nd case where querying form returns a TypeError
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4799
diff changeset
1019 if language is None:
3961b2b91568 2nd case where querying form returns a TypeError
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4799
diff changeset
1020 if "roundup_language" in self.cookie:
3961b2b91568 2nd case where querying form returns a TypeError
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4799
diff changeset
1021 language = self.cookie["roundup_language"].value
3961b2b91568 2nd case where querying form returns a TypeError
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4799
diff changeset
1022 elif self.instance.config["WEB_USE_BROWSER_LANGUAGE"]:
3961b2b91568 2nd case where querying form returns a TypeError
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4799
diff changeset
1023 hal = self.env.get('HTTP_ACCEPT_LANGUAGE')
3961b2b91568 2nd case where querying form returns a TypeError
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4799
diff changeset
1024 language = accept_language.parse(hal)
3961b2b91568 2nd case where querying form returns a TypeError
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4799
diff changeset
1025 else:
3961b2b91568 2nd case where querying form returns a TypeError
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4799
diff changeset
1026 language = ""
3427
198fe87b0254 add language detection (patch [SF#1360321])
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3396
diff changeset
1027
6658
408fd477761f Add i18n object to roundupdb.Database
Ralf Schlatterbeck <rsc@runtux.com>
parents: 6656
diff changeset
1028 if not language :
408fd477761f Add i18n object to roundupdb.Database
Ralf Schlatterbeck <rsc@runtux.com>
parents: 6656
diff changeset
1029 # default to tracker language
408fd477761f Add i18n object to roundupdb.Database
Ralf Schlatterbeck <rsc@runtux.com>
parents: 6656
diff changeset
1030 language = self.instance.config["TRACKER_LANGUAGE"]
408fd477761f Add i18n object to roundupdb.Database
Ralf Schlatterbeck <rsc@runtux.com>
parents: 6656
diff changeset
1031
408fd477761f Add i18n object to roundupdb.Database
Ralf Schlatterbeck <rsc@runtux.com>
parents: 6656
diff changeset
1032 # this maybe is not correct, as get_translation could not
408fd477761f Add i18n object to roundupdb.Database
Ralf Schlatterbeck <rsc@runtux.com>
parents: 6656
diff changeset
1033 # find desired locale and switch back to "en" but we set
408fd477761f Add i18n object to roundupdb.Database
Ralf Schlatterbeck <rsc@runtux.com>
parents: 6656
diff changeset
1034 # self.language to the desired language !
3427
198fe87b0254 add language detection (patch [SF#1360321])
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3396
diff changeset
1035 self.language = language
6658
408fd477761f Add i18n object to roundupdb.Database
Ralf Schlatterbeck <rsc@runtux.com>
parents: 6656
diff changeset
1036
408fd477761f Add i18n object to roundupdb.Database
Ralf Schlatterbeck <rsc@runtux.com>
parents: 6656
diff changeset
1037 self.setTranslator(TranslationService.get_translation(
408fd477761f Add i18n object to roundupdb.Database
Ralf Schlatterbeck <rsc@runtux.com>
parents: 6656
diff changeset
1038 language,
408fd477761f Add i18n object to roundupdb.Database
Ralf Schlatterbeck <rsc@runtux.com>
parents: 6656
diff changeset
1039 tracker_home=self.instance.config["TRACKER_HOME"]))
3427
198fe87b0254 add language detection (patch [SF#1360321])
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3396
diff changeset
1040
5934
db9bd45d50ad Refactor jwt auth into authenticate_bearer_token() method on Client
John Rouillard <rouilj@ieee.org>
parents: 5924
diff changeset
1041 def authenticate_bearer_token(self, challenge):
db9bd45d50ad Refactor jwt auth into authenticate_bearer_token() method on Client
John Rouillard <rouilj@ieee.org>
parents: 5924
diff changeset
1042 ''' authenticate the bearer token. Refactored from determine_user()
db9bd45d50ad Refactor jwt auth into authenticate_bearer_token() method on Client
John Rouillard <rouilj@ieee.org>
parents: 5924
diff changeset
1043 to alow it to be overridden if needed.
db9bd45d50ad Refactor jwt auth into authenticate_bearer_token() method on Client
John Rouillard <rouilj@ieee.org>
parents: 5924
diff changeset
1044 '''
db9bd45d50ad Refactor jwt auth into authenticate_bearer_token() method on Client
John Rouillard <rouilj@ieee.org>
parents: 5924
diff changeset
1045 try: # will jwt import?
db9bd45d50ad Refactor jwt auth into authenticate_bearer_token() method on Client
John Rouillard <rouilj@ieee.org>
parents: 5924
diff changeset
1046 import jwt
db9bd45d50ad Refactor jwt auth into authenticate_bearer_token() method on Client
John Rouillard <rouilj@ieee.org>
parents: 5924
diff changeset
1047 except ImportError:
db9bd45d50ad Refactor jwt auth into authenticate_bearer_token() method on Client
John Rouillard <rouilj@ieee.org>
parents: 5924
diff changeset
1048 # no support for jwt, this is fine.
db9bd45d50ad Refactor jwt auth into authenticate_bearer_token() method on Client
John Rouillard <rouilj@ieee.org>
parents: 5924
diff changeset
1049 self.setHeader("WWW-Authenticate", "Basic")
db9bd45d50ad Refactor jwt auth into authenticate_bearer_token() method on Client
John Rouillard <rouilj@ieee.org>
parents: 5924
diff changeset
1050 raise LoginError('Support for jwt disabled.')
db9bd45d50ad Refactor jwt auth into authenticate_bearer_token() method on Client
John Rouillard <rouilj@ieee.org>
parents: 5924
diff changeset
1051
db9bd45d50ad Refactor jwt auth into authenticate_bearer_token() method on Client
John Rouillard <rouilj@ieee.org>
parents: 5924
diff changeset
1052 secret = self.db.config.WEB_JWT_SECRET
db9bd45d50ad Refactor jwt auth into authenticate_bearer_token() method on Client
John Rouillard <rouilj@ieee.org>
parents: 5924
diff changeset
1053 if len(secret) < 32:
db9bd45d50ad Refactor jwt auth into authenticate_bearer_token() method on Client
John Rouillard <rouilj@ieee.org>
parents: 5924
diff changeset
1054 # no support for jwt, this is fine.
db9bd45d50ad Refactor jwt auth into authenticate_bearer_token() method on Client
John Rouillard <rouilj@ieee.org>
parents: 5924
diff changeset
1055 self.setHeader("WWW-Authenticate", "Basic")
db9bd45d50ad Refactor jwt auth into authenticate_bearer_token() method on Client
John Rouillard <rouilj@ieee.org>
parents: 5924
diff changeset
1056 raise LoginError('Support for jwt disabled by admin.')
db9bd45d50ad Refactor jwt auth into authenticate_bearer_token() method on Client
John Rouillard <rouilj@ieee.org>
parents: 5924
diff changeset
1057
db9bd45d50ad Refactor jwt auth into authenticate_bearer_token() method on Client
John Rouillard <rouilj@ieee.org>
parents: 5924
diff changeset
1058 try: # handle jwt exceptions
db9bd45d50ad Refactor jwt auth into authenticate_bearer_token() method on Client
John Rouillard <rouilj@ieee.org>
parents: 5924
diff changeset
1059 token = jwt.decode(challenge, secret,
db9bd45d50ad Refactor jwt auth into authenticate_bearer_token() method on Client
John Rouillard <rouilj@ieee.org>
parents: 5924
diff changeset
1060 algorithms=['HS256'],
db9bd45d50ad Refactor jwt auth into authenticate_bearer_token() method on Client
John Rouillard <rouilj@ieee.org>
parents: 5924
diff changeset
1061 audience=self.db.config.TRACKER_WEB,
db9bd45d50ad Refactor jwt auth into authenticate_bearer_token() method on Client
John Rouillard <rouilj@ieee.org>
parents: 5924
diff changeset
1062 issuer=self.db.config.TRACKER_WEB)
db9bd45d50ad Refactor jwt auth into authenticate_bearer_token() method on Client
John Rouillard <rouilj@ieee.org>
parents: 5924
diff changeset
1063 except jwt.exceptions.InvalidTokenError as err:
db9bd45d50ad Refactor jwt auth into authenticate_bearer_token() method on Client
John Rouillard <rouilj@ieee.org>
parents: 5924
diff changeset
1064 self.setHeader("WWW-Authenticate", "Basic, Bearer")
db9bd45d50ad Refactor jwt auth into authenticate_bearer_token() method on Client
John Rouillard <rouilj@ieee.org>
parents: 5924
diff changeset
1065 self.make_user_anonymous()
db9bd45d50ad Refactor jwt auth into authenticate_bearer_token() method on Client
John Rouillard <rouilj@ieee.org>
parents: 5924
diff changeset
1066 raise LoginError(str(err))
db9bd45d50ad Refactor jwt auth into authenticate_bearer_token() method on Client
John Rouillard <rouilj@ieee.org>
parents: 5924
diff changeset
1067
db9bd45d50ad Refactor jwt auth into authenticate_bearer_token() method on Client
John Rouillard <rouilj@ieee.org>
parents: 5924
diff changeset
1068 return(token)
db9bd45d50ad Refactor jwt auth into authenticate_bearer_token() method on Client
John Rouillard <rouilj@ieee.org>
parents: 5924
diff changeset
1069
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1070 def determine_user(self):
3427
198fe87b0254 add language detection (patch [SF#1360321])
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3396
diff changeset
1071 """Determine who the user is"""
1724
bc4f0aec594e oops, we really do need a database
Richard Jones <richard@users.sourceforge.net>
parents: 1719
diff changeset
1072 self.opendb('admin')
bc4f0aec594e oops, we really do need a database
Richard Jones <richard@users.sourceforge.net>
parents: 1719
diff changeset
1073
5878
1b57d8f3eb97 Add rudimentery experiment JSON Web Token (jwt) support
John Rouillard <rouilj@ieee.org>
parents: 5847
diff changeset
1074 # if we get a jwt, it includes the roles to be used for this session
1b57d8f3eb97 Add rudimentery experiment JSON Web Token (jwt) support
John Rouillard <rouilj@ieee.org>
parents: 5847
diff changeset
1075 # so we define a new function to encpsulate and return the jwt roles
1b57d8f3eb97 Add rudimentery experiment JSON Web Token (jwt) support
John Rouillard <rouilj@ieee.org>
parents: 5847
diff changeset
1076 # and not take the roles from the database.
1b57d8f3eb97 Add rudimentery experiment JSON Web Token (jwt) support
John Rouillard <rouilj@ieee.org>
parents: 5847
diff changeset
1077 override_get_roles = None
1b57d8f3eb97 Add rudimentery experiment JSON Web Token (jwt) support
John Rouillard <rouilj@ieee.org>
parents: 5847
diff changeset
1078
3989
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
1079 # get session data from db
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
1080 # XXX: rename
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
1081 self.session_api = Session(self)
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
1082
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
1083 # take the opportunity to cleanup expired sessions and otks
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
1084 self.clean_up()
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1085
3453
8e3c0b88afad prefer http authorization over cookie sessions [SF#1396134]
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3427
diff changeset
1086 user = None
8e3c0b88afad prefer http authorization over cookie sessions [SF#1396134]
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3427
diff changeset
1087 # first up, try http authorization if enabled
6053
380dec305c28 Add config option 'http_auth_convert_realm_to_lowercase'
Ralf Schlatterbeck <rsc@runtux.com>
parents: 6014
diff changeset
1088 cfg = self.instance.config
6436
1f2f7c0b8968 issue2550837 - New option for web auth (also http header passing)
John Rouillard <rouilj@ieee.org>
parents: 6382
diff changeset
1089 remote_user_header = cfg.WEB_HTTP_AUTH_HEADER or 'REMOTE_USER'
6211
50960479f627 New config-option 'cookie_takes_precedence'
Ralf Schlatterbeck <rsc@runtux.com>
parents: 6147
diff changeset
1090 if cfg.WEB_COOKIE_TAKES_PRECEDENCE:
50960479f627 New config-option 'cookie_takes_precedence'
Ralf Schlatterbeck <rsc@runtux.com>
parents: 6147
diff changeset
1091 user = self.session_api.get('user')
50960479f627 New config-option 'cookie_takes_precedence'
Ralf Schlatterbeck <rsc@runtux.com>
parents: 6147
diff changeset
1092 if user:
50960479f627 New config-option 'cookie_takes_precedence'
Ralf Schlatterbeck <rsc@runtux.com>
parents: 6147
diff changeset
1093 # update session lifetime datestamp
50960479f627 New config-option 'cookie_takes_precedence'
Ralf Schlatterbeck <rsc@runtux.com>
parents: 6147
diff changeset
1094 self.session_api.update()
6436
1f2f7c0b8968 issue2550837 - New option for web auth (also http header passing)
John Rouillard <rouilj@ieee.org>
parents: 6382
diff changeset
1095 if remote_user_header in self.env:
1f2f7c0b8968 issue2550837 - New option for web auth (also http header passing)
John Rouillard <rouilj@ieee.org>
parents: 6382
diff changeset
1096 del self.env[remote_user_header]
6211
50960479f627 New config-option 'cookie_takes_precedence'
Ralf Schlatterbeck <rsc@runtux.com>
parents: 6147
diff changeset
1097 if not user and cfg.WEB_HTTP_AUTH:
6436
1f2f7c0b8968 issue2550837 - New option for web auth (also http header passing)
John Rouillard <rouilj@ieee.org>
parents: 6382
diff changeset
1098 if remote_user_header in self.env:
3453
8e3c0b88afad prefer http authorization over cookie sessions [SF#1396134]
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3427
diff changeset
1099 # we have external auth (e.g. by Apache)
6436
1f2f7c0b8968 issue2550837 - New option for web auth (also http header passing)
John Rouillard <rouilj@ieee.org>
parents: 6382
diff changeset
1100 user = self.env[remote_user_header]
6053
380dec305c28 Add config option 'http_auth_convert_realm_to_lowercase'
Ralf Schlatterbeck <rsc@runtux.com>
parents: 6014
diff changeset
1101 if cfg.WEB_HTTP_AUTH_CONVERT_REALM_TO_LOWERCASE and '@' in user:
380dec305c28 Add config option 'http_auth_convert_realm_to_lowercase'
Ralf Schlatterbeck <rsc@runtux.com>
parents: 6014
diff changeset
1102 u, d = user.split ('@', 1)
380dec305c28 Add config option 'http_auth_convert_realm_to_lowercase'
Ralf Schlatterbeck <rsc@runtux.com>
parents: 6014
diff changeset
1103 user = '@'.join ((u, d.lower()))
3356
2913b42c0810 enabled disabling of REMOTE_USER for when it's not a valid username
Richard Jones <richard@users.sourceforge.net>
parents: 3276
diff changeset
1104 elif self.env.get('HTTP_AUTHORIZATION', ''):
3453
8e3c0b88afad prefer http authorization over cookie sessions [SF#1396134]
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3427
diff changeset
1105 # try handling Basic Auth ourselves
3356
2913b42c0810 enabled disabling of REMOTE_USER for when it's not a valid username
Richard Jones <richard@users.sourceforge.net>
parents: 3276
diff changeset
1106 auth = self.env['HTTP_AUTHORIZATION']
5549
901d7ba146ad Avoid errors from invalid Authorization headers (issue2550992).
Joseph Myers <jsm@polyomino.org.uk>
parents: 5524
diff changeset
1107 try:
901d7ba146ad Avoid errors from invalid Authorization headers (issue2550992).
Joseph Myers <jsm@polyomino.org.uk>
parents: 5524
diff changeset
1108 scheme, challenge = auth.split(' ', 1)
901d7ba146ad Avoid errors from invalid Authorization headers (issue2550992).
Joseph Myers <jsm@polyomino.org.uk>
parents: 5524
diff changeset
1109 except ValueError:
901d7ba146ad Avoid errors from invalid Authorization headers (issue2550992).
Joseph Myers <jsm@polyomino.org.uk>
parents: 5524
diff changeset
1110 # Invalid header.
901d7ba146ad Avoid errors from invalid Authorization headers (issue2550992).
Joseph Myers <jsm@polyomino.org.uk>
parents: 5524
diff changeset
1111 scheme = ''
901d7ba146ad Avoid errors from invalid Authorization headers (issue2550992).
Joseph Myers <jsm@polyomino.org.uk>
parents: 5524
diff changeset
1112 challenge = ''
3356
2913b42c0810 enabled disabling of REMOTE_USER for when it's not a valid username
Richard Jones <richard@users.sourceforge.net>
parents: 3276
diff changeset
1113 if scheme.lower() == 'basic':
2913b42c0810 enabled disabling of REMOTE_USER for when it's not a valid username
Richard Jones <richard@users.sourceforge.net>
parents: 3276
diff changeset
1114 try:
5474
4c9192393cd9 encoding fixes
Christof Meerwald <cmeerw@cmeerw.org>
parents: 5456
diff changeset
1115 decoded = b2s(base64.b64decode(challenge))
3356
2913b42c0810 enabled disabling of REMOTE_USER for when it's not a valid username
Richard Jones <richard@users.sourceforge.net>
parents: 3276
diff changeset
1116 except TypeError:
2913b42c0810 enabled disabling of REMOTE_USER for when it's not a valid username
Richard Jones <richard@users.sourceforge.net>
parents: 3276
diff changeset
1117 # invalid challenge
5474
4c9192393cd9 encoding fixes
Christof Meerwald <cmeerw@cmeerw.org>
parents: 5456
diff changeset
1118 decoded = ''
5549
901d7ba146ad Avoid errors from invalid Authorization headers (issue2550992).
Joseph Myers <jsm@polyomino.org.uk>
parents: 5524
diff changeset
1119 try:
901d7ba146ad Avoid errors from invalid Authorization headers (issue2550992).
Joseph Myers <jsm@polyomino.org.uk>
parents: 5524
diff changeset
1120 username, password = decoded.split(':', 1)
901d7ba146ad Avoid errors from invalid Authorization headers (issue2550992).
Joseph Myers <jsm@polyomino.org.uk>
parents: 5524
diff changeset
1121 except ValueError:
901d7ba146ad Avoid errors from invalid Authorization headers (issue2550992).
Joseph Myers <jsm@polyomino.org.uk>
parents: 5524
diff changeset
1122 # Invalid challenge.
901d7ba146ad Avoid errors from invalid Authorization headers (issue2550992).
Joseph Myers <jsm@polyomino.org.uk>
parents: 5524
diff changeset
1123 username = ''
901d7ba146ad Avoid errors from invalid Authorization headers (issue2550992).
Joseph Myers <jsm@polyomino.org.uk>
parents: 5524
diff changeset
1124 password = ''
3356
2913b42c0810 enabled disabling of REMOTE_USER for when it's not a valid username
Richard Jones <richard@users.sourceforge.net>
parents: 3276
diff changeset
1125 try:
4669
d7ac6c7bc371 Fix basic authentication.
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4649
diff changeset
1126 # Current user may not be None, otherwise
d7ac6c7bc371 Fix basic authentication.
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4649
diff changeset
1127 # instatiation of the login action will fail.
d7ac6c7bc371 Fix basic authentication.
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4649
diff changeset
1128 # So we set the user to anonymous first.
d7ac6c7bc371 Fix basic authentication.
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4649
diff changeset
1129 self.make_user_anonymous()
3356
2913b42c0810 enabled disabling of REMOTE_USER for when it's not a valid username
Richard Jones <richard@users.sourceforge.net>
parents: 3276
diff changeset
1130 login = self.get_action_class('login')(self)
2913b42c0810 enabled disabling of REMOTE_USER for when it's not a valid username
Richard Jones <richard@users.sourceforge.net>
parents: 3276
diff changeset
1131 login.verifyLogin(username, password)
5248
198b6e810c67 Use Python-3-compatible 'as' syntax for except statements
Eric S. Raymond <esr@thyrsus.com>
parents: 5231
diff changeset
1132 except LoginError as err:
3356
2913b42c0810 enabled disabling of REMOTE_USER for when it's not a valid username
Richard Jones <richard@users.sourceforge.net>
parents: 3276
diff changeset
1133 self.make_user_anonymous()
4265
e24a6ca34448 Improve login failure response.
Stefan Seefeld <stefan@seefeld.name>
parents: 4264
diff changeset
1134 raise
3356
2913b42c0810 enabled disabling of REMOTE_USER for when it's not a valid username
Richard Jones <richard@users.sourceforge.net>
parents: 3276
diff changeset
1135 user = username
5201
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1136 # try to seed with something harder to guess than
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1137 # just the time. If random is SystemRandom,
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1138 # this is a no-op.
5488
52cb53eedf77 reworked random number use
Christof Meerwald <cmeerw@cmeerw.org>
parents: 5475
diff changeset
1139 random_.seed("%s%s"%(password,time.time()))
5878
1b57d8f3eb97 Add rudimentery experiment JSON Web Token (jwt) support
John Rouillard <rouilj@ieee.org>
parents: 5847
diff changeset
1140 elif scheme.lower() == 'bearer':
5934
db9bd45d50ad Refactor jwt auth into authenticate_bearer_token() method on Client
John Rouillard <rouilj@ieee.org>
parents: 5924
diff changeset
1141 token = self.authenticate_bearer_token(challenge)
db9bd45d50ad Refactor jwt auth into authenticate_bearer_token() method on Client
John Rouillard <rouilj@ieee.org>
parents: 5924
diff changeset
1142
db9bd45d50ad Refactor jwt auth into authenticate_bearer_token() method on Client
John Rouillard <rouilj@ieee.org>
parents: 5924
diff changeset
1143 from roundup.hyperdb import iter_roles
5878
1b57d8f3eb97 Add rudimentery experiment JSON Web Token (jwt) support
John Rouillard <rouilj@ieee.org>
parents: 5847
diff changeset
1144
5934
db9bd45d50ad Refactor jwt auth into authenticate_bearer_token() method on Client
John Rouillard <rouilj@ieee.org>
parents: 5924
diff changeset
1145 # if we got here token is valid, use the role
db9bd45d50ad Refactor jwt auth into authenticate_bearer_token() method on Client
John Rouillard <rouilj@ieee.org>
parents: 5924
diff changeset
1146 # and sub claims.
db9bd45d50ad Refactor jwt auth into authenticate_bearer_token() method on Client
John Rouillard <rouilj@ieee.org>
parents: 5924
diff changeset
1147 try:
db9bd45d50ad Refactor jwt auth into authenticate_bearer_token() method on Client
John Rouillard <rouilj@ieee.org>
parents: 5924
diff changeset
1148 # make sure to str(token['sub']) the subject. As decoded
db9bd45d50ad Refactor jwt auth into authenticate_bearer_token() method on Client
John Rouillard <rouilj@ieee.org>
parents: 5924
diff changeset
1149 # by json, it is unicode which thows an error when used
db9bd45d50ad Refactor jwt auth into authenticate_bearer_token() method on Client
John Rouillard <rouilj@ieee.org>
parents: 5924
diff changeset
1150 # with 'nodeid in db' down the call chain.
db9bd45d50ad Refactor jwt auth into authenticate_bearer_token() method on Client
John Rouillard <rouilj@ieee.org>
parents: 5924
diff changeset
1151 user = self.db.user.get(str(token['sub']), 'username')
db9bd45d50ad Refactor jwt auth into authenticate_bearer_token() method on Client
John Rouillard <rouilj@ieee.org>
parents: 5924
diff changeset
1152 except IndexError:
db9bd45d50ad Refactor jwt auth into authenticate_bearer_token() method on Client
John Rouillard <rouilj@ieee.org>
parents: 5924
diff changeset
1153 raise LoginError("Token subject is invalid.")
5878
1b57d8f3eb97 Add rudimentery experiment JSON Web Token (jwt) support
John Rouillard <rouilj@ieee.org>
parents: 5847
diff changeset
1154
5934
db9bd45d50ad Refactor jwt auth into authenticate_bearer_token() method on Client
John Rouillard <rouilj@ieee.org>
parents: 5924
diff changeset
1155 # validate roles
db9bd45d50ad Refactor jwt auth into authenticate_bearer_token() method on Client
John Rouillard <rouilj@ieee.org>
parents: 5924
diff changeset
1156 all_rolenames = [ role[0] for role in self.db.security.role.items() ]
db9bd45d50ad Refactor jwt auth into authenticate_bearer_token() method on Client
John Rouillard <rouilj@ieee.org>
parents: 5924
diff changeset
1157 for r in token['roles']:
db9bd45d50ad Refactor jwt auth into authenticate_bearer_token() method on Client
John Rouillard <rouilj@ieee.org>
parents: 5924
diff changeset
1158 if r.lower() not in all_rolenames:
db9bd45d50ad Refactor jwt auth into authenticate_bearer_token() method on Client
John Rouillard <rouilj@ieee.org>
parents: 5924
diff changeset
1159 raise LoginError("Token roles are invalid.")
5878
1b57d8f3eb97 Add rudimentery experiment JSON Web Token (jwt) support
John Rouillard <rouilj@ieee.org>
parents: 5847
diff changeset
1160
5934
db9bd45d50ad Refactor jwt auth into authenticate_bearer_token() method on Client
John Rouillard <rouilj@ieee.org>
parents: 5924
diff changeset
1161 # will be used later to override the get_roles method
db9bd45d50ad Refactor jwt auth into authenticate_bearer_token() method on Client
John Rouillard <rouilj@ieee.org>
parents: 5924
diff changeset
1162 override_get_roles = \
db9bd45d50ad Refactor jwt auth into authenticate_bearer_token() method on Client
John Rouillard <rouilj@ieee.org>
parents: 5924
diff changeset
1163 lambda self: iter_roles(','.join(token['roles']))
2928
81c99c857b57 applied patch [SF#1067690]
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2923
diff changeset
1164
3989
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
1165 # if user was not set by http authorization, try session lookup
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
1166 if not user:
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
1167 user = self.session_api.get('user')
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
1168 if user:
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
1169 # update session lifetime datestamp
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
1170 self.session_api.update()
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1171
3989
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
1172 # if no user name set by http authorization or session lookup
3453
8e3c0b88afad prefer http authorization over cookie sessions [SF#1396134]
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3427
diff changeset
1173 # the user is anonymous
8e3c0b88afad prefer http authorization over cookie sessions [SF#1396134]
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3427
diff changeset
1174 if not user:
8e3c0b88afad prefer http authorization over cookie sessions [SF#1396134]
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3427
diff changeset
1175 user = 'anonymous'
8e3c0b88afad prefer http authorization over cookie sessions [SF#1396134]
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3427
diff changeset
1176
8e3c0b88afad prefer http authorization over cookie sessions [SF#1396134]
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3427
diff changeset
1177 # sanity check on the user still being valid,
8e3c0b88afad prefer http authorization over cookie sessions [SF#1396134]
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3427
diff changeset
1178 # getting the userid at the same time
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1179 try:
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1180 self.userid = self.db.user.lookup(user)
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1181 except (KeyError, TypeError):
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1182 user = 'anonymous'
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1183
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1184 # make sure the anonymous user is valid if we're using it
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1185 if user == 'anonymous':
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1186 self.make_user_anonymous()
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1187 else:
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1188 self.user = user
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1189
1003
f89b8d32291b Hack hack hack...
Richard Jones <richard@users.sourceforge.net>
parents: 1002
diff changeset
1190 # reopen the database as the correct user
f89b8d32291b Hack hack hack...
Richard Jones <richard@users.sourceforge.net>
parents: 1002
diff changeset
1191 self.opendb(self.user)
5878
1b57d8f3eb97 Add rudimentery experiment JSON Web Token (jwt) support
John Rouillard <rouilj@ieee.org>
parents: 5847
diff changeset
1192 if override_get_roles:
1b57d8f3eb97 Add rudimentery experiment JSON Web Token (jwt) support
John Rouillard <rouilj@ieee.org>
parents: 5847
diff changeset
1193 # opendb destroys and re-opens the db if instance.optimize
1b57d8f3eb97 Add rudimentery experiment JSON Web Token (jwt) support
John Rouillard <rouilj@ieee.org>
parents: 5847
diff changeset
1194 # is not true. This deletes an override of get_roles. So
1b57d8f3eb97 Add rudimentery experiment JSON Web Token (jwt) support
John Rouillard <rouilj@ieee.org>
parents: 5847
diff changeset
1195 # assign get_roles override from the jwt if needed at this
1b57d8f3eb97 Add rudimentery experiment JSON Web Token (jwt) support
John Rouillard <rouilj@ieee.org>
parents: 5847
diff changeset
1196 # point.
1b57d8f3eb97 Add rudimentery experiment JSON Web Token (jwt) support
John Rouillard <rouilj@ieee.org>
parents: 5847
diff changeset
1197 self.db.user.get_roles = override_get_roles
1003
f89b8d32291b Hack hack hack...
Richard Jones <richard@users.sourceforge.net>
parents: 1002
diff changeset
1198
4327
095d92109cc7 allow Anonymous users to log in, and register
Richard Jones <richard@users.sourceforge.net>
parents: 4326
diff changeset
1199 def check_anonymous_access(self):
4326
d51a9c498dc4 Fix "Web Access" permission check to allow serving of static files to Anonymous again
Richard Jones <richard@users.sourceforge.net>
parents: 4291
diff changeset
1200 """Check that the Anonymous user is actually allowed to use the web
d51a9c498dc4 Fix "Web Access" permission check to allow serving of static files to Anonymous again
Richard Jones <richard@users.sourceforge.net>
parents: 4291
diff changeset
1201 interface and short-circuit all further processing if they're not.
d51a9c498dc4 Fix "Web Access" permission check to allow serving of static files to Anonymous again
Richard Jones <richard@users.sourceforge.net>
parents: 4291
diff changeset
1202 """
4327
095d92109cc7 allow Anonymous users to log in, and register
Richard Jones <richard@users.sourceforge.net>
parents: 4326
diff changeset
1203 # allow Anonymous to use the "login" and "register" actions (noting
095d92109cc7 allow Anonymous users to log in, and register
Richard Jones <richard@users.sourceforge.net>
parents: 4326
diff changeset
1204 # that "register" has its own "Register" permission check)
4367
fa5587802af9 Handle multiple @action values from broken trackers
Richard Jones <richard@users.sourceforge.net>
parents: 4362
diff changeset
1205
4802
e1ffab417c28 Yet another instance of a TypeError fixed
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4801
diff changeset
1206 action = ''
e1ffab417c28 Yet another instance of a TypeError fixed
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4801
diff changeset
1207 try:
e1ffab417c28 Yet another instance of a TypeError fixed
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4801
diff changeset
1208 if ':action' in self.form:
e1ffab417c28 Yet another instance of a TypeError fixed
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4801
diff changeset
1209 action = self.form[':action']
e1ffab417c28 Yet another instance of a TypeError fixed
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4801
diff changeset
1210 elif '@action' in self.form:
e1ffab417c28 Yet another instance of a TypeError fixed
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4801
diff changeset
1211 action = self.form['@action']
e1ffab417c28 Yet another instance of a TypeError fixed
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4801
diff changeset
1212 except TypeError:
e1ffab417c28 Yet another instance of a TypeError fixed
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4801
diff changeset
1213 pass
4367
fa5587802af9 Handle multiple @action values from broken trackers
Richard Jones <richard@users.sourceforge.net>
parents: 4362
diff changeset
1214 if isinstance(action, list):
fa5587802af9 Handle multiple @action values from broken trackers
Richard Jones <richard@users.sourceforge.net>
parents: 4362
diff changeset
1215 raise SeriousError('broken form: multiple @action values submitted')
4384
b0d812e10549 fix actions check for < Python2.6
Richard Jones <richard@users.sourceforge.net>
parents: 4380
diff changeset
1216 elif action != '':
4367
fa5587802af9 Handle multiple @action values from broken trackers
Richard Jones <richard@users.sourceforge.net>
parents: 4362
diff changeset
1217 action = action.value.lower()
4327
095d92109cc7 allow Anonymous users to log in, and register
Richard Jones <richard@users.sourceforge.net>
parents: 4326
diff changeset
1218 if action in ('login', 'register'):
095d92109cc7 allow Anonymous users to log in, and register
Richard Jones <richard@users.sourceforge.net>
parents: 4326
diff changeset
1219 return
095d92109cc7 allow Anonymous users to log in, and register
Richard Jones <richard@users.sourceforge.net>
parents: 4326
diff changeset
1220
4329
58b7ba47af87 fixes to make registration work again
Richard Jones <richard@users.sourceforge.net>
parents: 4327
diff changeset
1221 # allow Anonymous to view the "user" "register" template if they're
58b7ba47af87 fixes to make registration work again
Richard Jones <richard@users.sourceforge.net>
parents: 4327
diff changeset
1222 # allowed to register
58b7ba47af87 fixes to make registration work again
Richard Jones <richard@users.sourceforge.net>
parents: 4327
diff changeset
1223 if (self.db.security.hasPermission('Register', self.userid, 'user')
58b7ba47af87 fixes to make registration work again
Richard Jones <richard@users.sourceforge.net>
parents: 4327
diff changeset
1224 and self.classname == 'user' and self.template == 'register'):
58b7ba47af87 fixes to make registration work again
Richard Jones <richard@users.sourceforge.net>
parents: 4327
diff changeset
1225 return
58b7ba47af87 fixes to make registration work again
Richard Jones <richard@users.sourceforge.net>
parents: 4327
diff changeset
1226
4327
095d92109cc7 allow Anonymous users to log in, and register
Richard Jones <richard@users.sourceforge.net>
parents: 4326
diff changeset
1227 # otherwise for everything else
4326
d51a9c498dc4 Fix "Web Access" permission check to allow serving of static files to Anonymous again
Richard Jones <richard@users.sourceforge.net>
parents: 4291
diff changeset
1228 if self.user == 'anonymous':
d51a9c498dc4 Fix "Web Access" permission check to allow serving of static files to Anonymous again
Richard Jones <richard@users.sourceforge.net>
parents: 4291
diff changeset
1229 if not self.db.security.hasPermission('Web Access', self.userid):
4362
74476eaac38a more modernisation
Richard Jones <richard@users.sourceforge.net>
parents: 4344
diff changeset
1230 raise Unauthorised(self._("Anonymous users are not "
74476eaac38a more modernisation
Richard Jones <richard@users.sourceforge.net>
parents: 4344
diff changeset
1231 "allowed to use the web interface"))
4326
d51a9c498dc4 Fix "Web Access" permission check to allow serving of static files to Anonymous again
Richard Jones <richard@users.sourceforge.net>
parents: 4291
diff changeset
1232
6681
ab2ed11c021e issue2551205: Add support for specifying valid origins for api: xmlrpc/rest
John Rouillard <rouilj@ieee.org>
parents: 6658
diff changeset
1233 def is_origin_header_ok(self, api=False):
ab2ed11c021e issue2551205: Add support for specifying valid origins for api: xmlrpc/rest
John Rouillard <rouilj@ieee.org>
parents: 6658
diff changeset
1234 origin = self.env['HTTP_ORIGIN']
ab2ed11c021e issue2551205: Add support for specifying valid origins for api: xmlrpc/rest
John Rouillard <rouilj@ieee.org>
parents: 6658
diff changeset
1235 # note base https://host/... ends host with with a /,
ab2ed11c021e issue2551205: Add support for specifying valid origins for api: xmlrpc/rest
John Rouillard <rouilj@ieee.org>
parents: 6658
diff changeset
1236 # so add it to origin.
ab2ed11c021e issue2551205: Add support for specifying valid origins for api: xmlrpc/rest
John Rouillard <rouilj@ieee.org>
parents: 6658
diff changeset
1237 foundat = self.base.find(origin +'/')
ab2ed11c021e issue2551205: Add support for specifying valid origins for api: xmlrpc/rest
John Rouillard <rouilj@ieee.org>
parents: 6658
diff changeset
1238 if foundat == 0:
ab2ed11c021e issue2551205: Add support for specifying valid origins for api: xmlrpc/rest
John Rouillard <rouilj@ieee.org>
parents: 6658
diff changeset
1239 return True
5201
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1240
6681
ab2ed11c021e issue2551205: Add support for specifying valid origins for api: xmlrpc/rest
John Rouillard <rouilj@ieee.org>
parents: 6658
diff changeset
1241 if not api:
ab2ed11c021e issue2551205: Add support for specifying valid origins for api: xmlrpc/rest
John Rouillard <rouilj@ieee.org>
parents: 6658
diff changeset
1242 return False
ab2ed11c021e issue2551205: Add support for specifying valid origins for api: xmlrpc/rest
John Rouillard <rouilj@ieee.org>
parents: 6658
diff changeset
1243
ab2ed11c021e issue2551205: Add support for specifying valid origins for api: xmlrpc/rest
John Rouillard <rouilj@ieee.org>
parents: 6658
diff changeset
1244 allowed_origins = self.db.config['WEB_ALLOWED_API_ORIGINS']
ab2ed11c021e issue2551205: Add support for specifying valid origins for api: xmlrpc/rest
John Rouillard <rouilj@ieee.org>
parents: 6658
diff changeset
1245 # find a match for other possible origins
ab2ed11c021e issue2551205: Add support for specifying valid origins for api: xmlrpc/rest
John Rouillard <rouilj@ieee.org>
parents: 6658
diff changeset
1246 # Original spec says origin is case sensitive match.
ab2ed11c021e issue2551205: Add support for specifying valid origins for api: xmlrpc/rest
John Rouillard <rouilj@ieee.org>
parents: 6658
diff changeset
1247 # Living spec doesn't address Origin value's case or
ab2ed11c021e issue2551205: Add support for specifying valid origins for api: xmlrpc/rest
John Rouillard <rouilj@ieee.org>
parents: 6658
diff changeset
1248 # how to compare it. So implement case sensitive....
6693
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
1249 if allowed_origins:
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
1250 if allowed_origins[0] == '*' or origin in allowed_origins:
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
1251 return True
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
1252
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
1253 return False
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
1254
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
1255 def is_referer_header_ok(self, api=False):
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
1256 referer = self.env['HTTP_REFERER']
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
1257 # parse referer and create an origin
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
1258 referer_comp = urllib_.urlparse(referer)
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
1259
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
1260 # self.base always has trailing /, so add trailing / to referer_origin
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
1261 referer_origin = "%s://%s/"%(referer_comp[0], referer_comp[1])
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
1262 foundat = self.base.find(referer_origin)
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
1263 if foundat == 0:
6681
ab2ed11c021e issue2551205: Add support for specifying valid origins for api: xmlrpc/rest
John Rouillard <rouilj@ieee.org>
parents: 6658
diff changeset
1264 return True
ab2ed11c021e issue2551205: Add support for specifying valid origins for api: xmlrpc/rest
John Rouillard <rouilj@ieee.org>
parents: 6658
diff changeset
1265
6693
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
1266 if not api:
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
1267 return False
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
1268
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
1269 allowed_origins = self.db.config['WEB_ALLOWED_API_ORIGINS']
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
1270 if allowed_origins[0] == '*':
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
1271 return True
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
1272
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
1273 # For referer, loop over allowed_api_origins and
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
1274 # see if any of them are a prefix to referer, case sensitive.
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
1275 # Append / to each origin so that:
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
1276 # an allowed_origin of https://my.host does not match
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
1277 # a referer of https://my.host.com/my/path
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
1278 for allowed_origin in allowed_origins:
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
1279 foundat = referer_origin.find(allowed_origin + '/')
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
1280 if foundat == 0:
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
1281 return True
6681
ab2ed11c021e issue2551205: Add support for specifying valid origins for api: xmlrpc/rest
John Rouillard <rouilj@ieee.org>
parents: 6658
diff changeset
1282 return False
ab2ed11c021e issue2551205: Add support for specifying valid origins for api: xmlrpc/rest
John Rouillard <rouilj@ieee.org>
parents: 6658
diff changeset
1283
ab2ed11c021e issue2551205: Add support for specifying valid origins for api: xmlrpc/rest
John Rouillard <rouilj@ieee.org>
parents: 6658
diff changeset
1284 def handle_csrf(self, api=False):
5201
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1285 '''Handle csrf token lookup and validate current user and session
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1286
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1287 This implements (or tries to implement) the
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1288 Session-Dependent Nonce from
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1289 https://seclab.stanford.edu/websec/csrf/csrf.pdf.
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1290
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1291 Changing this to an HMAC(sessionid,secret) will
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1292 remove the need for saving a fair amount of
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1293 state on the server (one nonce per form per
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1294 page). If you have multiple forms/page this can
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1295 lead to abandoned csrf tokens that have to time
5946
1b50c2c5619a Fix crash bug where looking for @csrf in a form failed.
John Rouillard <rouilj@ieee.org>
parents: 5934
diff changeset
1296 out and get cleaned up. But you lose per form
5201
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1297 tokens which may be an advantage. Also the HMAC
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1298 is constant for the session, so provides more
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1299 occasions for it to be exposed.
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1300
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1301 This only runs on post (or put and delete for
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1302 future use). Nobody should be changing data
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1303 with a get.
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1304
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1305 A session token lifetime is settable in
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1306 config.ini. A future enhancement to the
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1307 creation routines should allow for the requester
5946
1b50c2c5619a Fix crash bug where looking for @csrf in a form failed.
John Rouillard <rouilj@ieee.org>
parents: 5934
diff changeset
1308 of the token to set the lifetime.
5201
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1309
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1310 The unique session key and user id is stored
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1311 with the token. The token is valid if the stored
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1312 values match the current client's userid and
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1313 session.
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1314
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1315 If a user logs out, the csrf keys are
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1316 invalidated since no other connection should
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1317 have the same session id.
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1318
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1319 At least to start I am reporting anti-csrf to
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1320 the user. If it's an attacker who can see the
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1321 site, they can see the @csrf fields and can
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1322 probably figure out that he needs to supply
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1323 valid headers. Or they can just read this code
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1324 8-). So hiding it doesn't seem to help but it
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1325 does arguably show the enforcement settings, but
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1326 given the newness of this code notifying the
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1327 user and having them notify the admins for
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1328 debugging seems to be an advantage.
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1329
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1330 '''
5210
7da56980754d Remove csrf keys used with get
John Rouillard <rouilj@ieee.org>
parents: 5202
diff changeset
1331 # Create the otks handle here as we need it almost immediately.
7da56980754d Remove csrf keys used with get
John Rouillard <rouilj@ieee.org>
parents: 5202
diff changeset
1332 # If this is perf issue, set to None here and check below
7da56980754d Remove csrf keys used with get
John Rouillard <rouilj@ieee.org>
parents: 5202
diff changeset
1333 # once all header checks have passed if it needs to be opened.
7da56980754d Remove csrf keys used with get
John Rouillard <rouilj@ieee.org>
parents: 5202
diff changeset
1334 otks=self.db.getOTKManager()
7da56980754d Remove csrf keys used with get
John Rouillard <rouilj@ieee.org>
parents: 5202
diff changeset
1335
5201
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1336 # Assume: never allow changes via GET
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1337 if self.env['REQUEST_METHOD'] not in ['POST', 'PUT', 'DELETE']:
5946
1b50c2c5619a Fix crash bug where looking for @csrf in a form failed.
John Rouillard <rouilj@ieee.org>
parents: 5934
diff changeset
1338 if (self.form.list is not None) and ("@csrf" in self.form):
5210
7da56980754d Remove csrf keys used with get
John Rouillard <rouilj@ieee.org>
parents: 5202
diff changeset
1339 # We have a nonce being used with a method it should
7da56980754d Remove csrf keys used with get
John Rouillard <rouilj@ieee.org>
parents: 5202
diff changeset
1340 # not be. If the nonce exists, report to admin so they
7da56980754d Remove csrf keys used with get
John Rouillard <rouilj@ieee.org>
parents: 5202
diff changeset
1341 # can fix the nonce leakage and destroy it. (nonces
7da56980754d Remove csrf keys used with get
John Rouillard <rouilj@ieee.org>
parents: 5202
diff changeset
1342 # used in a get are more exposed than those used in a
7da56980754d Remove csrf keys used with get
John Rouillard <rouilj@ieee.org>
parents: 5202
diff changeset
1343 # post.) Note, I don't attempt to validate here since
5220
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1344 # existence here is the sign of a failure. If nonce
5210
7da56980754d Remove csrf keys used with get
John Rouillard <rouilj@ieee.org>
parents: 5202
diff changeset
1345 # exists try to report the referer header to try to
7da56980754d Remove csrf keys used with get
John Rouillard <rouilj@ieee.org>
parents: 5202
diff changeset
1346 # find where this comes from so it can be fixed. If
7da56980754d Remove csrf keys used with get
John Rouillard <rouilj@ieee.org>
parents: 5202
diff changeset
1347 # nonce doesn't exist just ignore it. Maybe we should
7da56980754d Remove csrf keys used with get
John Rouillard <rouilj@ieee.org>
parents: 5202
diff changeset
1348 # report, but somebody could spam us with a ton of
7da56980754d Remove csrf keys used with get
John Rouillard <rouilj@ieee.org>
parents: 5202
diff changeset
1349 # invalid keys and fill up the logs.
7da56980754d Remove csrf keys used with get
John Rouillard <rouilj@ieee.org>
parents: 5202
diff changeset
1350 if 'HTTP_REFERER' in self.env:
7da56980754d Remove csrf keys used with get
John Rouillard <rouilj@ieee.org>
parents: 5202
diff changeset
1351 referer = self.env['HTTP_REFERER']
7da56980754d Remove csrf keys used with get
John Rouillard <rouilj@ieee.org>
parents: 5202
diff changeset
1352 else:
7da56980754d Remove csrf keys used with get
John Rouillard <rouilj@ieee.org>
parents: 5202
diff changeset
1353 referer = self._("Referer header not available.")
7da56980754d Remove csrf keys used with get
John Rouillard <rouilj@ieee.org>
parents: 5202
diff changeset
1354 key=self.form['@csrf'].value
7da56980754d Remove csrf keys used with get
John Rouillard <rouilj@ieee.org>
parents: 5202
diff changeset
1355 if otks.exists(key):
7da56980754d Remove csrf keys used with get
John Rouillard <rouilj@ieee.org>
parents: 5202
diff changeset
1356 logger.error(
7da56980754d Remove csrf keys used with get
John Rouillard <rouilj@ieee.org>
parents: 5202
diff changeset
1357 self._("csrf key used with wrong method from: %s"),
7da56980754d Remove csrf keys used with get
John Rouillard <rouilj@ieee.org>
parents: 5202
diff changeset
1358 referer)
7da56980754d Remove csrf keys used with get
John Rouillard <rouilj@ieee.org>
parents: 5202
diff changeset
1359 otks.destroy(key)
5319
62de601bdf6f Fix commits although a Reject exception is raised
Ralf Schlatterbeck <rsc@runtux.com>
parents: 5248
diff changeset
1360 otks.commit()
5220
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1361 # do return here. Keys have been obsoleted.
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1362 # we didn't do a expire cycle of session keys,
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1363 # but that's ok.
5201
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1364 return True
5210
7da56980754d Remove csrf keys used with get
John Rouillard <rouilj@ieee.org>
parents: 5202
diff changeset
1365
5201
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1366 config=self.instance.config
5220
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1367 current_user=self.db.getuid()
5201
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1368
5220
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1369 # List HTTP headers we check. Note that the xmlrpc header is
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1370 # missing. Its enforcement is different (yes/required are the
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1371 # same for example) so we don't include here.
5201
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1372 header_names = [
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1373 "ORIGIN",
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1374 "REFERER",
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1375 "X-FORWARDED-HOST",
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1376 "HOST"
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1377 ]
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1378
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1379 header_pass = 0 # count of passing header checks
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1380
5220
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1381 # If required headers are missing, raise an error
5201
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1382 for header in header_names:
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1383 if (config["WEB_CSRF_ENFORCE_HEADER_%s"%header] == 'required'
5624
b3618882f906 issue2551023: Fix CSRF headers for use with wsgi and cgi. The
John Rouillard <rouilj@ieee.org>
parents: 5615
diff changeset
1384 and "HTTP_%s" % header.replace('-', '_') not in self.env):
5220
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1385 logger.error(self._("csrf header %s required but missing for user%s."), header, current_user)
5378
35ea9b1efc14 Python 3 preparation: "raise" syntax.
Joseph Myers <jsm@polyomino.org.uk>
parents: 5356
diff changeset
1386 raise Unauthorised(self._("Missing header: %s")%header)
5201
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1387
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1388 # self.base always matches: ^https?://hostname
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1389 enforce=config['WEB_CSRF_ENFORCE_HEADER_REFERER']
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1390 if 'HTTP_REFERER' in self.env and enforce != "no":
6693
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
1391 if not self.is_referer_header_ok(api=api):
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
1392 referer = self.env['HTTP_REFERER']
5201
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1393 if enforce in ('required', 'yes'):
5220
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1394 logger.error(self._("csrf Referer header check failed for user%s. Value=%s"), current_user, referer)
6693
9a1f5e496e6c issue2551203 - Add support for CORS preflight request
John Rouillard <rouilj@ieee.org>
parents: 6681
diff changeset
1395 raise Unauthorised(self._("Invalid Referer: %s")%(referer))
5201
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1396 elif enforce == 'logfailure':
5220
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1397 logger.warning(self._("csrf Referer header check failed for user%s. Value=%s"), current_user, referer)
5201
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1398 else:
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1399 header_pass += 1
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1400
5220
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1401 # if you change these make sure to consider what
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1402 # happens if header variable exists but is empty.
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1403 # self.base.find("") returns 0 for example not -1
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1404 enforce=config['WEB_CSRF_ENFORCE_HEADER_ORIGIN']
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1405 if 'HTTP_ORIGIN' in self.env and enforce != "no":
6681
ab2ed11c021e issue2551205: Add support for specifying valid origins for api: xmlrpc/rest
John Rouillard <rouilj@ieee.org>
parents: 6658
diff changeset
1406 if not self.is_origin_header_ok(api=api):
ab2ed11c021e issue2551205: Add support for specifying valid origins for api: xmlrpc/rest
John Rouillard <rouilj@ieee.org>
parents: 6658
diff changeset
1407 origin = self.env['HTTP_ORIGIN']
5201
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1408 if enforce in ('required', 'yes'):
5220
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1409 logger.error(self._("csrf Origin header check failed for user%s. Value=%s"), current_user, origin)
5378
35ea9b1efc14 Python 3 preparation: "raise" syntax.
Joseph Myers <jsm@polyomino.org.uk>
parents: 5356
diff changeset
1410 raise Unauthorised(self._("Invalid Origin %s"%origin))
5201
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1411 elif enforce == 'logfailure':
5220
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1412 logger.warning(self._("csrf Origin header check failed for user%s. Value=%s"), current_user, origin)
5201
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1413 else:
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1414 header_pass += 1
5220
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1415
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1416 enforce=config['WEB_CSRF_ENFORCE_HEADER_X-FORWARDED-HOST']
5624
b3618882f906 issue2551023: Fix CSRF headers for use with wsgi and cgi. The
John Rouillard <rouilj@ieee.org>
parents: 5615
diff changeset
1417 if 'HTTP_X_FORWARDED_HOST' in self.env:
5220
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1418 if enforce != "no":
5624
b3618882f906 issue2551023: Fix CSRF headers for use with wsgi and cgi. The
John Rouillard <rouilj@ieee.org>
parents: 5615
diff changeset
1419 host = self.env['HTTP_X_FORWARDED_HOST']
5220
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1420 foundat = self.base.find('://' + host + '/')
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1421 # 4 means self.base has http:/ prefix, 5 means https:/ prefix
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1422 if foundat not in [4, 5]:
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1423 if enforce in ('required', 'yes'):
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1424 logger.error(self._("csrf X-FORWARDED-HOST header check failed for user%s. Value=%s"), current_user, host)
5378
35ea9b1efc14 Python 3 preparation: "raise" syntax.
Joseph Myers <jsm@polyomino.org.uk>
parents: 5356
diff changeset
1425 raise Unauthorised(self._("Invalid X-FORWARDED-HOST %s")%host)
5220
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1426 elif enforce == 'logfailure':
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1427 logger.warning(self._("csrf X-FORWARDED-HOST header check failed for user%s. Value=%s"), current_user, host)
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1428 else:
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1429 header_pass += 1
5201
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1430 else:
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1431 # https://seclab.stanford.edu/websec/csrf/csrf.pdf
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1432 # recommends checking HTTP HOST header as well.
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1433 # If there is an X-FORWARDED-HOST header, check
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1434 # that only. The proxy setting X-F-H has probably set
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1435 # the host header to a local hostname that is
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1436 # internal name of system not name supplied by user.
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1437 enforce=config['WEB_CSRF_ENFORCE_HEADER_HOST']
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1438 if 'HTTP_HOST' in self.env and enforce != "no":
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1439 host = self.env['HTTP_HOST']
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1440 foundat = self.base.find('://' + host + '/')
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1441 # 4 means http:// prefix, 5 means https:// prefix
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1442 if foundat not in [4, 5]:
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1443 if enforce in ('required', 'yes'):
5220
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1444 logger.error(self._("csrf HOST header check failed for user%s. Value=%s"), current_user, host)
5378
35ea9b1efc14 Python 3 preparation: "raise" syntax.
Joseph Myers <jsm@polyomino.org.uk>
parents: 5356
diff changeset
1445 raise Unauthorised(self._("Invalid HOST %s")%host)
5201
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1446 elif enforce == 'logfailure':
5220
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1447 logger.warning(self._("csrf HOST header check failed for user%s. Value=%s"), current_user, host)
5201
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1448 else:
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1449 header_pass += 1
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1450
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1451 enforce=config['WEB_CSRF_HEADER_MIN_COUNT']
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1452 if header_pass < enforce:
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1453 logger.error(self._("Csrf: unable to verify sufficient headers"))
5378
35ea9b1efc14 Python 3 preparation: "raise" syntax.
Joseph Myers <jsm@polyomino.org.uk>
parents: 5356
diff changeset
1454 raise UsageError(self._("Unable to verify sufficient headers"))
5201
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1455
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1456 enforce=config['WEB_CSRF_ENFORCE_HEADER_X-REQUESTED-WITH']
6681
ab2ed11c021e issue2551205: Add support for specifying valid origins for api: xmlrpc/rest
John Rouillard <rouilj@ieee.org>
parents: 6658
diff changeset
1457 if api:
5218
44f7e6b958fe Added tests for csrf with xmlrpc.
John Rouillard <rouilj@ieee.org>
parents: 5212
diff changeset
1458 if enforce in ['required', 'yes']:
44f7e6b958fe Added tests for csrf with xmlrpc.
John Rouillard <rouilj@ieee.org>
parents: 5212
diff changeset
1459 # if we get here we have usually passed at least one
44f7e6b958fe Added tests for csrf with xmlrpc.
John Rouillard <rouilj@ieee.org>
parents: 5212
diff changeset
1460 # header check. We check for presence of this custom
6681
ab2ed11c021e issue2551205: Add support for specifying valid origins for api: xmlrpc/rest
John Rouillard <rouilj@ieee.org>
parents: 6658
diff changeset
1461 # header for xmlrpc/rest calls only.
5218
44f7e6b958fe Added tests for csrf with xmlrpc.
John Rouillard <rouilj@ieee.org>
parents: 5212
diff changeset
1462 # E.G. X-Requested-With: XMLHttpRequest
6681
ab2ed11c021e issue2551205: Add support for specifying valid origins for api: xmlrpc/rest
John Rouillard <rouilj@ieee.org>
parents: 6658
diff changeset
1463 # Note we do not use CSRF nonces for xmlrpc/rest requests.
5218
44f7e6b958fe Added tests for csrf with xmlrpc.
John Rouillard <rouilj@ieee.org>
parents: 5212
diff changeset
1464 #
44f7e6b958fe Added tests for csrf with xmlrpc.
John Rouillard <rouilj@ieee.org>
parents: 5212
diff changeset
1465 # see: https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet#Protecting_REST_Services:_Use_of_Custom_Request_Headers
5624
b3618882f906 issue2551023: Fix CSRF headers for use with wsgi and cgi. The
John Rouillard <rouilj@ieee.org>
parents: 5615
diff changeset
1466 if 'HTTP_X_REQUESTED_WITH' not in self.env:
5220
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1467 logger.error(self._("csrf X-REQUESTED-WITH xmlrpc required header check failed for user%s."), current_user)
5378
35ea9b1efc14 Python 3 preparation: "raise" syntax.
Joseph Myers <jsm@polyomino.org.uk>
parents: 5356
diff changeset
1468 raise UsageError(self._("Required Header Missing"))
5201
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1469
5211
f4b6a2a3e605 Fix expiration dates and expire csrf tokens properly
John Rouillard <rouilj@ieee.org>
parents: 5210
diff changeset
1470 # Expire old csrf tokens now so we don't use them. These will
f4b6a2a3e605 Fix expiration dates and expire csrf tokens properly
John Rouillard <rouilj@ieee.org>
parents: 5210
diff changeset
1471 # be committed after the otks.destroy below. Note that the
f4b6a2a3e605 Fix expiration dates and expire csrf tokens properly
John Rouillard <rouilj@ieee.org>
parents: 5210
diff changeset
1472 # self.clean_up run as part of determine_user() will run only
f4b6a2a3e605 Fix expiration dates and expire csrf tokens properly
John Rouillard <rouilj@ieee.org>
parents: 5210
diff changeset
1473 # once an hour. If we have short lived (e.g. 5 minute) keys
f4b6a2a3e605 Fix expiration dates and expire csrf tokens properly
John Rouillard <rouilj@ieee.org>
parents: 5210
diff changeset
1474 # they will live too long if we depend on clean_up. So we do
f4b6a2a3e605 Fix expiration dates and expire csrf tokens properly
John Rouillard <rouilj@ieee.org>
parents: 5210
diff changeset
1475 # our own.
f4b6a2a3e605 Fix expiration dates and expire csrf tokens properly
John Rouillard <rouilj@ieee.org>
parents: 5210
diff changeset
1476 otks.clean()
f4b6a2a3e605 Fix expiration dates and expire csrf tokens properly
John Rouillard <rouilj@ieee.org>
parents: 5210
diff changeset
1477
6681
ab2ed11c021e issue2551205: Add support for specifying valid origins for api: xmlrpc/rest
John Rouillard <rouilj@ieee.org>
parents: 6658
diff changeset
1478 if api:
5220
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1479 # Save removal of expired keys from database.
5319
62de601bdf6f Fix commits although a Reject exception is raised
Ralf Schlatterbeck <rsc@runtux.com>
parents: 5248
diff changeset
1480 otks.commit()
5220
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1481 # Return from here since we have done housekeeping
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1482 # and don't use csrf tokens for xmlrpc.
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1483 return True
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1484
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1485 # process @csrf tokens past this point.
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1486 key=None
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1487 nonce_user = None
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1488 nonce_session = None
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1489
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1490 if '@csrf' in self.form:
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1491 key=self.form['@csrf'].value
5210
7da56980754d Remove csrf keys used with get
John Rouillard <rouilj@ieee.org>
parents: 5202
diff changeset
1492
5220
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1493 nonce_user = otks.get(key, 'uid', default=None)
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1494 nonce_session = otks.get(key, 'sid', default=None)
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1495 # The key has been used or compromised.
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1496 # Delete it to prevent replay.
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1497 otks.destroy(key)
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1498
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1499 # commit the deletion/expiration of all keys
5319
62de601bdf6f Fix commits although a Reject exception is raised
Ralf Schlatterbeck <rsc@runtux.com>
parents: 5248
diff changeset
1500 otks.commit()
5201
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1501
5220
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1502 enforce=config['WEB_CSRF_ENFORCE_TOKEN']
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1503 if key is None: # we do not have an @csrf token
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1504 if enforce == 'required':
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1505 logger.error(self._("Required csrf field missing for user%s"), current_user)
5847
26cd8e8bbed3 Change microcopy for missing csrf to follow mismatched csrf. Fix tests.
John Rouillard <rouilj@ieee.org>
parents: 5846
diff changeset
1506 raise UsageError(self._("We can't validate your session (csrf failure). Re-enter any unsaved data and try again."))
5220
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1507 elif enforce == 'logfailure':
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1508 # FIXME include url
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1509 logger.warning(self._("csrf field not supplied by user%s"), current_user)
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1510 else:
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1511 # enforce is either yes or no. Both permit change if token is
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1512 # missing
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1513 return True
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1514
5211
f4b6a2a3e605 Fix expiration dates and expire csrf tokens properly
John Rouillard <rouilj@ieee.org>
parents: 5210
diff changeset
1515 current_session = self.session_api._sid
f4b6a2a3e605 Fix expiration dates and expire csrf tokens properly
John Rouillard <rouilj@ieee.org>
parents: 5210
diff changeset
1516
5201
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1517 '''
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1518 # I think now that LogoutAction redirects to
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1519 # self.base ([tracker] web parameter in config.ini),
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1520 # this code is not needed. However I am keeping it
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1521 # around in case it has to come back to life.
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1522 # Delete if this is still around in 3/2018.
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1523 # rouilj 3/2017.
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1524 #
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1525 # Note using this code may cause a CSRF Login vulnerability.
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1526 # Handle the case where user logs out and tries to
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1527 # log in again in same window.
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1528 # The csrf token for the login button is associated
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1529 # with the prior login, so it will not validate.
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1530 #
5220
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1531 # To bypass error, Verify that nonce_user != user and that
5201
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1532 # user is '2' (anonymous) and there is no current
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1533 # session key. Validate that the csrf exists
5220
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1534 # in the db and nonce_user and nonce_session are not None.
5201
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1535 # Also validate that the action is Login.
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1536 # Lastly requre at least one csrf header check to pass.
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1537 # If all of those work process the login.
5220
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1538 if current_user != nonce_user and \
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1539 current_user == '2' and \
5201
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1540 current_session is None and \
5220
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1541 nonce_user is not None and \
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1542 nonce_session is not None and \
5201
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1543 "@action" in self.form and \
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1544 self.form["@action"].value == "Login":
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1545 if header_pass > 0:
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1546 otks.destroy(key)
5319
62de601bdf6f Fix commits although a Reject exception is raised
Ralf Schlatterbeck <rsc@runtux.com>
parents: 5248
diff changeset
1547 otks.commit()
5201
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1548 return True
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1549 else:
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1550 self.add_error_message("Reload window before logging in.")
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1551 '''
5210
7da56980754d Remove csrf keys used with get
John Rouillard <rouilj@ieee.org>
parents: 5202
diff changeset
1552 # validate against user and session
5220
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1553 if current_user != nonce_user:
5201
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1554 if enforce in ('required', "yes"):
5220
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1555 logger.error(
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1556 self._("Csrf mismatch user: current user %s != stored user %s, current session, stored session: %s,%s for key %s."),
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1557 current_user, nonce_user, current_session, nonce_session, key)
5846
fd015c4c6c23 Fix microcopy for CSRF validation failure. Remove display of bad
John Rouillard <rouilj@ieee.org>
parents: 5837
diff changeset
1558 raise UsageError(self._("We can't validate your session (csrf failure). Re-enter any unsaved data and try again."))
5201
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1559 elif enforce == 'logfailure':
5220
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1560 logger.warning(
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1561 self._("logged only: Csrf mismatch user: current user %s != stored user %s, current session, stored session: %s,%s for key %s."),
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1562 current_user, nonce_user, current_session, nonce_session, key)
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1563 if current_session != nonce_session:
5201
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1564 if enforce in ('required', "yes"):
5220
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1565 logger.error(
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1566 self._("Csrf mismatch user: current session %s != stored session %s, current user/stored user is: %s for key %s."),
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1567 current_session, nonce_session, current_user, key)
5846
fd015c4c6c23 Fix microcopy for CSRF validation failure. Remove display of bad
John Rouillard <rouilj@ieee.org>
parents: 5837
diff changeset
1568 raise UsageError(self._("We can't validate your session (csrf failure). Re-enter any unsaved data and try again."))
5201
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1569 elif enforce == 'logfailure':
5220
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1570 logger.warning(
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1571 self._("logged only: Csrf mismatch user: current session %s != stored session %s, current user/stored user is: %s for key %s."),
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1572 current_session, nonce_session, current_user, key)
14d8f61e6ef2 Reimplemented anti-csrf measures by raising exceptions rather than
John Rouillard <rouilj@ieee.org>
parents: 5218
diff changeset
1573 # we are done and the change can occur.
5201
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1574 return True
a9ace22e0a2f issue 2550690 - Adding anti-csrf measures to roundup following
John Rouillard <rouilj@ieee.org>
parents: 5188
diff changeset
1575
2940
00f609d53a8c tweaks to last patch
Richard Jones <richard@users.sourceforge.net>
parents: 2938
diff changeset
1576 def opendb(self, username):
3427
198fe87b0254 add language detection (patch [SF#1360321])
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3396
diff changeset
1577 """Open the database and set the current user.
2940
00f609d53a8c tweaks to last patch
Richard Jones <richard@users.sourceforge.net>
parents: 2938
diff changeset
1578
00f609d53a8c tweaks to last patch
Richard Jones <richard@users.sourceforge.net>
parents: 2938
diff changeset
1579 Opens a database once. On subsequent calls only the user is set on
00f609d53a8c tweaks to last patch
Richard Jones <richard@users.sourceforge.net>
parents: 2938
diff changeset
1580 the database object the instance.optimize is set. If we are in
00f609d53a8c tweaks to last patch
Richard Jones <richard@users.sourceforge.net>
parents: 2938
diff changeset
1581 "Development Mode" (cf. roundup_server) then the database is always
00f609d53a8c tweaks to last patch
Richard Jones <richard@users.sourceforge.net>
parents: 2938
diff changeset
1582 re-opened.
3427
198fe87b0254 add language detection (patch [SF#1360321])
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3396
diff changeset
1583 """
2940
00f609d53a8c tweaks to last patch
Richard Jones <richard@users.sourceforge.net>
parents: 2938
diff changeset
1584 # don't do anything if the db is open and the user has not changed
00f609d53a8c tweaks to last patch
Richard Jones <richard@users.sourceforge.net>
parents: 2938
diff changeset
1585 if hasattr(self, 'db') and self.db.isCurrentUser(username):
00f609d53a8c tweaks to last patch
Richard Jones <richard@users.sourceforge.net>
parents: 2938
diff changeset
1586 return
00f609d53a8c tweaks to last patch
Richard Jones <richard@users.sourceforge.net>
parents: 2938
diff changeset
1587
00f609d53a8c tweaks to last patch
Richard Jones <richard@users.sourceforge.net>
parents: 2938
diff changeset
1588 # open the database or only set the user
00f609d53a8c tweaks to last patch
Richard Jones <richard@users.sourceforge.net>
parents: 2938
diff changeset
1589 if not hasattr(self, 'db'):
00f609d53a8c tweaks to last patch
Richard Jones <richard@users.sourceforge.net>
parents: 2938
diff changeset
1590 self.db = self.instance.open(username)
4781
6e9b9743de89 Implementation for:
John Rouillard <rouilj@ieee.org>
parents: 4740
diff changeset
1591 self.db.tx_Source = "web"
2940
00f609d53a8c tweaks to last patch
Richard Jones <richard@users.sourceforge.net>
parents: 2938
diff changeset
1592 else:
00f609d53a8c tweaks to last patch
Richard Jones <richard@users.sourceforge.net>
parents: 2938
diff changeset
1593 if self.instance.optimize:
00f609d53a8c tweaks to last patch
Richard Jones <richard@users.sourceforge.net>
parents: 2938
diff changeset
1594 self.db.setCurrentUser(username)
4781
6e9b9743de89 Implementation for:
John Rouillard <rouilj@ieee.org>
parents: 4740
diff changeset
1595 self.db.tx_Source = "web"
2940
00f609d53a8c tweaks to last patch
Richard Jones <richard@users.sourceforge.net>
parents: 2938
diff changeset
1596 else:
00f609d53a8c tweaks to last patch
Richard Jones <richard@users.sourceforge.net>
parents: 2938
diff changeset
1597 self.db.close()
00f609d53a8c tweaks to last patch
Richard Jones <richard@users.sourceforge.net>
parents: 2938
diff changeset
1598 self.db = self.instance.open(username)
4781
6e9b9743de89 Implementation for:
John Rouillard <rouilj@ieee.org>
parents: 4740
diff changeset
1599 self.db.tx_Source = "web"
4212
51a098592b78 Reopen session with database.
Stefan Seefeld <stefan@seefeld.name>
parents: 4145
diff changeset
1600 # The old session API refers to the closed database;
51a098592b78 Reopen session with database.
Stefan Seefeld <stefan@seefeld.name>
parents: 4145
diff changeset
1601 # we can no longer use it.
51a098592b78 Reopen session with database.
Stefan Seefeld <stefan@seefeld.name>
parents: 4145
diff changeset
1602 self.session_api = Session(self)
4648
e645820e8556 Clean up whitespace in client.py
Ezio Melotti <ezio.melotti@gmail.com>
parents: 4640
diff changeset
1603
2940
00f609d53a8c tweaks to last patch
Richard Jones <richard@users.sourceforge.net>
parents: 2938
diff changeset
1604
2829
aa1cb9df09c3 ignore leading zeroes in the ID part of a node designator
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2808
diff changeset
1605 def determine_context(self, dre=re.compile(r'([^\d]+)0*(\d+)')):
2005
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
1606 """Determine the context of this page from the URL:
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1607
2005
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
1608 The URL path after the instance identifier is examined. The path
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
1609 is generally only one entry long.
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1610
2005
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
1611 - if there is no path, then we are in the "home" context.
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
1612 - if the path is "_file", then the additional path entry
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
1613 specifies the filename of a static file we're to serve up
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
1614 from the instance "html" directory. Raises a SendStaticFile
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
1615 exception.(*)
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
1616 - if there is something in the path (eg "issue"), it identifies
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
1617 the tracker class we're to display.
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
1618 - if the path is an item designator (eg "issue123"), then we're
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
1619 to display a specific item.
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
1620 - if the path starts with an item designator and is longer than
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
1621 one entry, then we're assumed to be handling an item of a
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
1622 FileClass, and the extra path information gives the filename
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
1623 that the client is going to label the download with (ie
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
1624 "file123/image.png" is nicer to download than "file123"). This
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
1625 raises a SendFile exception.(*)
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1626
2005
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
1627 Both of the "*" types of contexts stop before we bother to
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
1628 determine the template we're going to use. That's because they
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
1629 don't actually use templates.
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1630
2005
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
1631 The template used is specified by the :template CGI variable,
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
1632 which defaults to:
1053
b28393def972 more explanatory docsting
Richard Jones <richard@users.sourceforge.net>
parents: 1051
diff changeset
1633
2005
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
1634 - only classname suplied: "index"
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
1635 - full item designator supplied: "item"
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
1636
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
1637 We set:
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1638
1041
c28603c9f831 Class help and generic class editing done.
Richard Jones <richard@users.sourceforge.net>
parents: 1029
diff changeset
1639 self.classname - the class to display, can be None
2005
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
1640
1041
c28603c9f831 Class help and generic class editing done.
Richard Jones <richard@users.sourceforge.net>
parents: 1029
diff changeset
1641 self.template - the template to render the current context with
2005
fc52d57c6c3e documentation cleanup
Richard Jones <richard@users.sourceforge.net>
parents: 2004
diff changeset
1642
1041
c28603c9f831 Class help and generic class editing done.
Richard Jones <richard@users.sourceforge.net>
parents: 1029
diff changeset
1643 self.nodeid - the nodeid of the class we're displaying
1937
4c850112895b Some reformatting and fixing docstrings for emacs.
Johannes Gijsbers <jlgijsbers@users.sourceforge.net>
parents: 1936
diff changeset
1644 """
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1645 # default the optional variables
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1646 self.classname = None
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1647 self.nodeid = None
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1648
1420
3ac43c62a250 implemented extension to form parsing...
Richard Jones <richard@users.sourceforge.net>
parents: 1417
diff changeset
1649 # see if a template or messages are specified
3ac43c62a250 implemented extension to form parsing...
Richard Jones <richard@users.sourceforge.net>
parents: 1417
diff changeset
1650 template_override = ok_message = error_message = None
4801
bff9e4145f70 Fix another instance of a TypeError
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4800
diff changeset
1651 try:
bff9e4145f70 Fix another instance of a TypeError
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4800
diff changeset
1652 keys = self.form.keys()
bff9e4145f70 Fix another instance of a TypeError
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4800
diff changeset
1653 except TypeError:
bff9e4145f70 Fix another instance of a TypeError
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4800
diff changeset
1654 keys = ()
bff9e4145f70 Fix another instance of a TypeError
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4800
diff changeset
1655 for key in keys:
1420
3ac43c62a250 implemented extension to form parsing...
Richard Jones <richard@users.sourceforge.net>
parents: 1417
diff changeset
1656 if self.FV_TEMPLATE.match(key):
3ac43c62a250 implemented extension to form parsing...
Richard Jones <richard@users.sourceforge.net>
parents: 1417
diff changeset
1657 template_override = self.form[key].value
3ac43c62a250 implemented extension to form parsing...
Richard Jones <richard@users.sourceforge.net>
parents: 1417
diff changeset
1658 elif self.FV_OK_MESSAGE.match(key):
3ac43c62a250 implemented extension to form parsing...
Richard Jones <richard@users.sourceforge.net>
parents: 1417
diff changeset
1659 ok_message = self.form[key].value
3ac43c62a250 implemented extension to form parsing...
Richard Jones <richard@users.sourceforge.net>
parents: 1417
diff changeset
1660 elif self.FV_ERROR_MESSAGE.match(key):
3ac43c62a250 implemented extension to form parsing...
Richard Jones <richard@users.sourceforge.net>
parents: 1417
diff changeset
1661 error_message = self.form[key].value
3ac43c62a250 implemented extension to form parsing...
Richard Jones <richard@users.sourceforge.net>
parents: 1417
diff changeset
1662
1977
f96592a7c357 changes to support the new templating Unauthorised exception.
Richard Jones <richard@users.sourceforge.net>
parents: 1973
diff changeset
1663 # see if we were passed in a message
f96592a7c357 changes to support the new templating Unauthorised exception.
Richard Jones <richard@users.sourceforge.net>
parents: 1973
diff changeset
1664 if ok_message:
4880
ca692423e401 Different approach to fix XSS in issue2550817
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4851
diff changeset
1665 self.add_ok_message(ok_message)
1977
f96592a7c357 changes to support the new templating Unauthorised exception.
Richard Jones <richard@users.sourceforge.net>
parents: 1973
diff changeset
1666 if error_message:
4880
ca692423e401 Different approach to fix XSS in issue2550817
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4851
diff changeset
1667 self.add_error_message(error_message)
1977
f96592a7c357 changes to support the new templating Unauthorised exception.
Richard Jones <richard@users.sourceforge.net>
parents: 1973
diff changeset
1668
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1669 # determine the classname and possibly nodeid
1157
26c8cb2162d7 fixed various URL / base URL issues
Richard Jones <richard@users.sourceforge.net>
parents: 1153
diff changeset
1670 path = self.path.split('/')
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1671 if not path or path[0] in ('', 'home', 'index'):
1420
3ac43c62a250 implemented extension to form parsing...
Richard Jones <richard@users.sourceforge.net>
parents: 1417
diff changeset
1672 if template_override is not None:
3ac43c62a250 implemented extension to form parsing...
Richard Jones <richard@users.sourceforge.net>
parents: 1417
diff changeset
1673 self.template = template_override
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1674 else:
1041
c28603c9f831 Class help and generic class editing done.
Richard Jones <richard@users.sourceforge.net>
parents: 1029
diff changeset
1675 self.template = ''
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1676 return
1911
f5c804379c85 fixed ZRoundup - mostly changes to classic template
Richard Jones <richard@users.sourceforge.net>
parents: 1905
diff changeset
1677 elif path[0] in ('_file', '@@file'):
4362
74476eaac38a more modernisation
Richard Jones <richard@users.sourceforge.net>
parents: 4344
diff changeset
1678 raise SendStaticFile(os.path.join(*path[1:]))
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1679 else:
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1680 self.classname = path[0]
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1681 if len(path) > 1:
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1682 # send the file identified by the designator in path[0]
4362
74476eaac38a more modernisation
Richard Jones <richard@users.sourceforge.net>
parents: 4344
diff changeset
1683 raise SendFile(path[0])
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1684
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1685 # see if we got a designator
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1686 m = dre.match(self.classname)
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1687 if m:
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1688 self.classname = m.group(1)
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1689 self.nodeid = m.group(2)
3494
5a56abcf1b22 catch bad classname in URL (related to [SF#1240541])
Richard Jones <richard@users.sourceforge.net>
parents: 3453
diff changeset
1690 try:
5a56abcf1b22 catch bad classname in URL (related to [SF#1240541])
Richard Jones <richard@users.sourceforge.net>
parents: 3453
diff changeset
1691 klass = self.db.getclass(self.classname)
5a56abcf1b22 catch bad classname in URL (related to [SF#1240541])
Richard Jones <richard@users.sourceforge.net>
parents: 3453
diff changeset
1692 except KeyError:
4362
74476eaac38a more modernisation
Richard Jones <richard@users.sourceforge.net>
parents: 4344
diff changeset
1693 raise NotFound('%s/%s'%(self.classname, self.nodeid))
5555
7b663b588292 Don't pass huge itemids into the backend.
martin.v.loewis <martin.v.loewis>
parents: 5554
diff changeset
1694 if int(self.nodeid) > 2**31:
7b663b588292 Don't pass huge itemids into the backend.
martin.v.loewis <martin.v.loewis>
parents: 5554
diff changeset
1695 # Postgres will complain with a ProgrammingError
7b663b588292 Don't pass huge itemids into the backend.
martin.v.loewis <martin.v.loewis>
parents: 5554
diff changeset
1696 # if we try to pass in numbers that are too large
5556
d75aa88c2a99 Added RestInstance and calling rest from client.py
Chau Nguyen <dangchau1991@yahoo.com>
parents: 5555
diff changeset
1697 raise NotFound('%s/%s'%(self.classname, self.nodeid))
3494
5a56abcf1b22 catch bad classname in URL (related to [SF#1240541])
Richard Jones <richard@users.sourceforge.net>
parents: 3453
diff changeset
1698 if not klass.hasnode(self.nodeid):
4362
74476eaac38a more modernisation
Richard Jones <richard@users.sourceforge.net>
parents: 4344
diff changeset
1699 raise NotFound('%s/%s'%(self.classname, self.nodeid))
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1700 # with a designator, we default to item view
1041
c28603c9f831 Class help and generic class editing done.
Richard Jones <richard@users.sourceforge.net>
parents: 1029
diff changeset
1701 self.template = 'item'
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1702 else:
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1703 # with only a class, we default to index view
1041
c28603c9f831 Class help and generic class editing done.
Richard Jones <richard@users.sourceforge.net>
parents: 1029
diff changeset
1704 self.template = 'index'
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1705
1288
ad8de51d7cd5 handle "classname" URL path errors cleaner (generate a 404)
Richard Jones <richard@users.sourceforge.net>
parents: 1277
diff changeset
1706 # make sure the classname is valid
ad8de51d7cd5 handle "classname" URL path errors cleaner (generate a 404)
Richard Jones <richard@users.sourceforge.net>
parents: 1277
diff changeset
1707 try:
ad8de51d7cd5 handle "classname" URL path errors cleaner (generate a 404)
Richard Jones <richard@users.sourceforge.net>
parents: 1277
diff changeset
1708 self.db.getclass(self.classname)
ad8de51d7cd5 handle "classname" URL path errors cleaner (generate a 404)
Richard Jones <richard@users.sourceforge.net>
parents: 1277
diff changeset
1709 except KeyError:
4362
74476eaac38a more modernisation
Richard Jones <richard@users.sourceforge.net>
parents: 4344
diff changeset
1710 raise NotFound(self.classname)
1288
ad8de51d7cd5 handle "classname" URL path errors cleaner (generate a 404)
Richard Jones <richard@users.sourceforge.net>
parents: 1277
diff changeset
1711
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1712 # see if we have a template override
1420
3ac43c62a250 implemented extension to form parsing...
Richard Jones <richard@users.sourceforge.net>
parents: 1417
diff changeset
1713 if template_override is not None:
3ac43c62a250 implemented extension to form parsing...
Richard Jones <richard@users.sourceforge.net>
parents: 1417
diff changeset
1714 self.template = template_override
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1715
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1716 def serve_file(self, designator, dre=re.compile(r'([^\d]+)(\d+)')):
4065
1e28d58c6d1c Uniformly use """...""" instead of '''...''' for comments.
Stefan Seefeld <stefan@seefeld.name>
parents: 4064
diff changeset
1717 """ Serve the file from the content property of the designated item.
1e28d58c6d1c Uniformly use """...""" instead of '''...''' for comments.
Stefan Seefeld <stefan@seefeld.name>
parents: 4064
diff changeset
1718 """
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1719 m = dre.match(str(designator))
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1720 if not m:
4362
74476eaac38a more modernisation
Richard Jones <richard@users.sourceforge.net>
parents: 4344
diff changeset
1721 raise NotFound(str(designator))
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1722 classname, nodeid = m.group(1), m.group(2)
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1723
4263
bd000a1e9a57 Robustify web interface.
Stefan Seefeld <stefan@seefeld.name>
parents: 4224
diff changeset
1724 try:
bd000a1e9a57 Robustify web interface.
Stefan Seefeld <stefan@seefeld.name>
parents: 4224
diff changeset
1725 klass = self.db.getclass(classname)
bd000a1e9a57 Robustify web interface.
Stefan Seefeld <stefan@seefeld.name>
parents: 4224
diff changeset
1726 except KeyError:
bd000a1e9a57 Robustify web interface.
Stefan Seefeld <stefan@seefeld.name>
parents: 4224
diff changeset
1727 # The classname was not valid.
4362
74476eaac38a more modernisation
Richard Jones <richard@users.sourceforge.net>
parents: 4344
diff changeset
1728 raise NotFound(str(designator))
4648
e645820e8556 Clean up whitespace in client.py
Ezio Melotti <ezio.melotti@gmail.com>
parents: 4640
diff changeset
1729
4326
d51a9c498dc4 Fix "Web Access" permission check to allow serving of static files to Anonymous again
Richard Jones <richard@users.sourceforge.net>
parents: 4291
diff changeset
1730 # perform the Anonymous user access check
4327
095d92109cc7 allow Anonymous users to log in, and register
Richard Jones <richard@users.sourceforge.net>
parents: 4326
diff changeset
1731 self.check_anonymous_access()
1946
c538a64b94a7 Refactored CGI file serving so that FileClass contents are...
Richard Jones <richard@users.sourceforge.net>
parents: 1937
diff changeset
1732
1967
d30cd44321f2 commit old file-serving bugfix, and new pt content-type fix
Richard Jones <richard@users.sourceforge.net>
parents: 1946
diff changeset
1733 # make sure we have the appropriate properties
d30cd44321f2 commit old file-serving bugfix, and new pt content-type fix
Richard Jones <richard@users.sourceforge.net>
parents: 1946
diff changeset
1734 props = klass.getprops()
4362
74476eaac38a more modernisation
Richard Jones <richard@users.sourceforge.net>
parents: 4344
diff changeset
1735 if 'type' not in props:
74476eaac38a more modernisation
Richard Jones <richard@users.sourceforge.net>
parents: 4344
diff changeset
1736 raise NotFound(designator)
74476eaac38a more modernisation
Richard Jones <richard@users.sourceforge.net>
parents: 4344
diff changeset
1737 if 'content' not in props:
74476eaac38a more modernisation
Richard Jones <richard@users.sourceforge.net>
parents: 4344
diff changeset
1738 raise NotFound(designator)
1967
d30cd44321f2 commit old file-serving bugfix, and new pt content-type fix
Richard Jones <richard@users.sourceforge.net>
parents: 1946
diff changeset
1739
2870
795cdba40c05 enforce View Permission when serving file content [SF#1050470]
Richard Jones <richard@users.sourceforge.net>
parents: 2864
diff changeset
1740 # make sure we have permission
795cdba40c05 enforce View Permission when serving file content [SF#1050470]
Richard Jones <richard@users.sourceforge.net>
parents: 2864
diff changeset
1741 if not self.db.security.hasPermission('View', self.userid,
795cdba40c05 enforce View Permission when serving file content [SF#1050470]
Richard Jones <richard@users.sourceforge.net>
parents: 2864
diff changeset
1742 classname, 'content', nodeid):
4362
74476eaac38a more modernisation
Richard Jones <richard@users.sourceforge.net>
parents: 4344
diff changeset
1743 raise Unauthorised(self._("You are not allowed to view "
74476eaac38a more modernisation
Richard Jones <richard@users.sourceforge.net>
parents: 4344
diff changeset
1744 "this file."))
2870
795cdba40c05 enforce View Permission when serving file content [SF#1050470]
Richard Jones <richard@users.sourceforge.net>
parents: 2864
diff changeset
1745
4962
63c31b18b955 Fix issue 2550848: HTML attachments should not be served as text/html
anatoly techtonik <techtonik@gmail.com>
parents: 4919
diff changeset
1746
63c31b18b955 Fix issue 2550848: HTML attachments should not be served as text/html
anatoly techtonik <techtonik@gmail.com>
parents: 4919
diff changeset
1747 # --- mime-type security
63c31b18b955 Fix issue 2550848: HTML attachments should not be served as text/html
anatoly techtonik <techtonik@gmail.com>
parents: 4919
diff changeset
1748 # mime type detection is performed in cgi.form_parser
63c31b18b955 Fix issue 2550848: HTML attachments should not be served as text/html
anatoly techtonik <techtonik@gmail.com>
parents: 4919
diff changeset
1749
63c31b18b955 Fix issue 2550848: HTML attachments should not be served as text/html
anatoly techtonik <techtonik@gmail.com>
parents: 4919
diff changeset
1750 # everything not here is served as 'application/octet-stream'
63c31b18b955 Fix issue 2550848: HTML attachments should not be served as text/html
anatoly techtonik <techtonik@gmail.com>
parents: 4919
diff changeset
1751 whitelist = [
63c31b18b955 Fix issue 2550848: HTML attachments should not be served as text/html
anatoly techtonik <techtonik@gmail.com>
parents: 4919
diff changeset
1752 'text/plain',
63c31b18b955 Fix issue 2550848: HTML attachments should not be served as text/html
anatoly techtonik <techtonik@gmail.com>
parents: 4919
diff changeset
1753 'text/x-csrc', # .c
63c31b18b955 Fix issue 2550848: HTML attachments should not be served as text/html
anatoly techtonik <techtonik@gmail.com>
parents: 4919
diff changeset
1754 'text/x-chdr', # .h
63c31b18b955 Fix issue 2550848: HTML attachments should not be served as text/html
anatoly techtonik <techtonik@gmail.com>
parents: 4919
diff changeset
1755 'text/x-patch', # .patch and .diff
63c31b18b955 Fix issue 2550848: HTML attachments should not be served as text/html
anatoly techtonik <techtonik@gmail.com>
parents: 4919
diff changeset
1756 'text/x-python', # .py
63c31b18b955 Fix issue 2550848: HTML attachments should not be served as text/html
anatoly techtonik <techtonik@gmail.com>
parents: 4919
diff changeset
1757 'text/xml',
63c31b18b955 Fix issue 2550848: HTML attachments should not be served as text/html
anatoly techtonik <techtonik@gmail.com>
parents: 4919
diff changeset
1758 'text/csv',
63c31b18b955 Fix issue 2550848: HTML attachments should not be served as text/html
anatoly techtonik <techtonik@gmail.com>
parents: 4919
diff changeset
1759 'text/css',
63c31b18b955 Fix issue 2550848: HTML attachments should not be served as text/html
anatoly techtonik <techtonik@gmail.com>
parents: 4919
diff changeset
1760 'application/pdf',
63c31b18b955 Fix issue 2550848: HTML attachments should not be served as text/html
anatoly techtonik <techtonik@gmail.com>
parents: 4919
diff changeset
1761 'image/gif',
63c31b18b955 Fix issue 2550848: HTML attachments should not be served as text/html
anatoly techtonik <techtonik@gmail.com>
parents: 4919
diff changeset
1762 'image/jpeg',
63c31b18b955 Fix issue 2550848: HTML attachments should not be served as text/html
anatoly techtonik <techtonik@gmail.com>
parents: 4919
diff changeset
1763 'image/png',
6447
8f8f4988b856 Add image/svg-xml as valid type to serve.
John Rouillard <rouilj@ieee.org>
parents: 6436
diff changeset
1764 'image/svg+xml',
4962
63c31b18b955 Fix issue 2550848: HTML attachments should not be served as text/html
anatoly techtonik <techtonik@gmail.com>
parents: 4919
diff changeset
1765 'image/webp',
63c31b18b955 Fix issue 2550848: HTML attachments should not be served as text/html
anatoly techtonik <techtonik@gmail.com>
parents: 4919
diff changeset
1766 'audio/ogg',
63c31b18b955 Fix issue 2550848: HTML attachments should not be served as text/html
anatoly techtonik <techtonik@gmail.com>
parents: 4919
diff changeset
1767 'video/webm',
63c31b18b955 Fix issue 2550848: HTML attachments should not be served as text/html
anatoly techtonik <techtonik@gmail.com>
parents: 4919
diff changeset
1768 ]
63c31b18b955 Fix issue 2550848: HTML attachments should not be served as text/html
anatoly techtonik <techtonik@gmail.com>
parents: 4919
diff changeset
1769
63c31b18b955 Fix issue 2550848: HTML attachments should not be served as text/html
anatoly techtonik <techtonik@gmail.com>
parents: 4919
diff changeset
1770 if self.instance.config['WEB_ALLOW_HTML_FILE']:
63c31b18b955 Fix issue 2550848: HTML attachments should not be served as text/html
anatoly techtonik <techtonik@gmail.com>
parents: 4919
diff changeset
1771 whitelist.append('text/html')
63c31b18b955 Fix issue 2550848: HTML attachments should not be served as text/html
anatoly techtonik <techtonik@gmail.com>
parents: 4919
diff changeset
1772
4530
c1c395058dee issue2550715: IndexError when requesting non-existing file via http.
Bernhard Reiter <Bernhard.Reiter@intevation.de>
parents: 4523
diff changeset
1773 try:
c1c395058dee issue2550715: IndexError when requesting non-existing file via http.
Bernhard Reiter <Bernhard.Reiter@intevation.de>
parents: 4523
diff changeset
1774 mime_type = klass.get(nodeid, 'type')
5248
198b6e810c67 Use Python-3-compatible 'as' syntax for except statements
Eric S. Raymond <esr@thyrsus.com>
parents: 5231
diff changeset
1775 except IndexError as e:
4530
c1c395058dee issue2550715: IndexError when requesting non-existing file via http.
Bernhard Reiter <Bernhard.Reiter@intevation.de>
parents: 4523
diff changeset
1776 raise NotFound(e)
4291
b1772fdb09d0 Fix traceback on .../msgN/ url...
Ralf Schlatterbeck <schlatterbeck@users.sourceforge.net>
parents: 4265
diff changeset
1777 # Can happen for msg class:
b1772fdb09d0 Fix traceback on .../msgN/ url...
Ralf Schlatterbeck <schlatterbeck@users.sourceforge.net>
parents: 4265
diff changeset
1778 if not mime_type:
b1772fdb09d0 Fix traceback on .../msgN/ url...
Ralf Schlatterbeck <schlatterbeck@users.sourceforge.net>
parents: 4265
diff changeset
1779 mime_type = 'text/plain'
4047
e70643990e9c Support the use of sendfile() for file transfer, if available.
Stefan Seefeld <stefan@seefeld.name>
parents: 4046
diff changeset
1780
4962
63c31b18b955 Fix issue 2550848: HTML attachments should not be served as text/html
anatoly techtonik <techtonik@gmail.com>
parents: 4919
diff changeset
1781 if mime_type not in whitelist:
63c31b18b955 Fix issue 2550848: HTML attachments should not be served as text/html
anatoly techtonik <techtonik@gmail.com>
parents: 4919
diff changeset
1782 mime_type = 'application/octet-stream'
63c31b18b955 Fix issue 2550848: HTML attachments should not be served as text/html
anatoly techtonik <techtonik@gmail.com>
parents: 4919
diff changeset
1783
63c31b18b955 Fix issue 2550848: HTML attachments should not be served as text/html
anatoly techtonik <techtonik@gmail.com>
parents: 4919
diff changeset
1784 # --/ mime-type security
63c31b18b955 Fix issue 2550848: HTML attachments should not be served as text/html
anatoly techtonik <techtonik@gmail.com>
parents: 4919
diff changeset
1785
4088
34434785f308 Plug a number of security holes:
Richard Jones <richard@users.sourceforge.net>
parents: 4083
diff changeset
1786
4047
e70643990e9c Support the use of sendfile() for file transfer, if available.
Stefan Seefeld <stefan@seefeld.name>
parents: 4046
diff changeset
1787 # If this object is a file (i.e., an instance of FileClass),
e70643990e9c Support the use of sendfile() for file transfer, if available.
Stefan Seefeld <stefan@seefeld.name>
parents: 4046
diff changeset
1788 # see if we can find it in the filesystem. If so, we may be
e70643990e9c Support the use of sendfile() for file transfer, if available.
Stefan Seefeld <stefan@seefeld.name>
parents: 4046
diff changeset
1789 # able to use the more-efficient request.sendfile method of
e70643990e9c Support the use of sendfile() for file transfer, if available.
Stefan Seefeld <stefan@seefeld.name>
parents: 4046
diff changeset
1790 # sending the file. If not, just get the "content" property
e70643990e9c Support the use of sendfile() for file transfer, if available.
Stefan Seefeld <stefan@seefeld.name>
parents: 4046
diff changeset
1791 # in the usual way, and use that.
e70643990e9c Support the use of sendfile() for file transfer, if available.
Stefan Seefeld <stefan@seefeld.name>
parents: 4046
diff changeset
1792 content = None
e70643990e9c Support the use of sendfile() for file transfer, if available.
Stefan Seefeld <stefan@seefeld.name>
parents: 4046
diff changeset
1793 filename = None
e70643990e9c Support the use of sendfile() for file transfer, if available.
Stefan Seefeld <stefan@seefeld.name>
parents: 4046
diff changeset
1794 if isinstance(klass, hyperdb.FileClass):
e70643990e9c Support the use of sendfile() for file transfer, if available.
Stefan Seefeld <stefan@seefeld.name>
parents: 4046
diff changeset
1795 try:
e70643990e9c Support the use of sendfile() for file transfer, if available.
Stefan Seefeld <stefan@seefeld.name>
parents: 4046
diff changeset
1796 filename = self.db.filename(classname, nodeid)
e70643990e9c Support the use of sendfile() for file transfer, if available.
Stefan Seefeld <stefan@seefeld.name>
parents: 4046
diff changeset
1797 except AttributeError:
e70643990e9c Support the use of sendfile() for file transfer, if available.
Stefan Seefeld <stefan@seefeld.name>
parents: 4046
diff changeset
1798 # The database doesn't store files in the filesystem
e70643990e9c Support the use of sendfile() for file transfer, if available.
Stefan Seefeld <stefan@seefeld.name>
parents: 4046
diff changeset
1799 # and therefore doesn't provide the "filename" method.
e70643990e9c Support the use of sendfile() for file transfer, if available.
Stefan Seefeld <stefan@seefeld.name>
parents: 4046
diff changeset
1800 pass
e70643990e9c Support the use of sendfile() for file transfer, if available.
Stefan Seefeld <stefan@seefeld.name>
parents: 4046
diff changeset
1801 except IOError:
e70643990e9c Support the use of sendfile() for file transfer, if available.
Stefan Seefeld <stefan@seefeld.name>
parents: 4046
diff changeset
1802 # The file does not exist.
e70643990e9c Support the use of sendfile() for file transfer, if available.
Stefan Seefeld <stefan@seefeld.name>
parents: 4046
diff changeset
1803 pass
e70643990e9c Support the use of sendfile() for file transfer, if available.
Stefan Seefeld <stefan@seefeld.name>
parents: 4046
diff changeset
1804 if not filename:
e70643990e9c Support the use of sendfile() for file transfer, if available.
Stefan Seefeld <stefan@seefeld.name>
parents: 4046
diff changeset
1805 content = klass.get(nodeid, 'content')
4648
e645820e8556 Clean up whitespace in client.py
Ezio Melotti <ezio.melotti@gmail.com>
parents: 4640
diff changeset
1806
1967
d30cd44321f2 commit old file-serving bugfix, and new pt content-type fix
Richard Jones <richard@users.sourceforge.net>
parents: 1946
diff changeset
1807 lmt = klass.get(nodeid, 'activity').timestamp()
1946
c538a64b94a7 Refactored CGI file serving so that FileClass contents are...
Richard Jones <richard@users.sourceforge.net>
parents: 1937
diff changeset
1808
4047
e70643990e9c Support the use of sendfile() for file transfer, if available.
Stefan Seefeld <stefan@seefeld.name>
parents: 4046
diff changeset
1809 self._serve_file(lmt, mime_type, content, filename)
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1810
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1811 def serve_static_file(self, file):
4065
1e28d58c6d1c Uniformly use """...""" instead of '''...''' for comments.
Stefan Seefeld <stefan@seefeld.name>
parents: 4064
diff changeset
1812 """ Serve up the file named from the templates dir
1e28d58c6d1c Uniformly use """...""" instead of '''...''' for comments.
Stefan Seefeld <stefan@seefeld.name>
parents: 4064
diff changeset
1813 """
2864
930e780c751f support STATIC_FILES directory in addition to TEMPLATES
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2853
diff changeset
1814 # figure the filename - try STATIC_FILES, then TEMPLATES dir
930e780c751f support STATIC_FILES directory in addition to TEMPLATES
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2853
diff changeset
1815 for dir_option in ('STATIC_FILES', 'TEMPLATES'):
930e780c751f support STATIC_FILES directory in addition to TEMPLATES
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2853
diff changeset
1816 prefix = self.instance.config[dir_option]
930e780c751f support STATIC_FILES directory in addition to TEMPLATES
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2853
diff changeset
1817 if not prefix:
930e780c751f support STATIC_FILES directory in addition to TEMPLATES
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2853
diff changeset
1818 continue
5613
0a8f0fddc2ae Support non-ASCII prefixes in instance config for finding static files (issue2551022).
Cédric Krier <cedric.krier@b2ck.com>
parents: 5608
diff changeset
1819 if is_us(prefix):
5231
8743b7226dc7 Fix issue with retreiving raw template files using the @@file mechanism.
John Rouillard <rouilj@ieee.org>
parents: 5220
diff changeset
1820 # prefix can be a string or list depending on
8743b7226dc7 Fix issue with retreiving raw template files using the @@file mechanism.
John Rouillard <rouilj@ieee.org>
parents: 5220
diff changeset
1821 # option. Make it a list to iterate over.
8743b7226dc7 Fix issue with retreiving raw template files using the @@file mechanism.
John Rouillard <rouilj@ieee.org>
parents: 5220
diff changeset
1822 prefix = [ prefix ]
8743b7226dc7 Fix issue with retreiving raw template files using the @@file mechanism.
John Rouillard <rouilj@ieee.org>
parents: 5220
diff changeset
1823
8743b7226dc7 Fix issue with retreiving raw template files using the @@file mechanism.
John Rouillard <rouilj@ieee.org>
parents: 5220
diff changeset
1824 for p in prefix:
8743b7226dc7 Fix issue with retreiving raw template files using the @@file mechanism.
John Rouillard <rouilj@ieee.org>
parents: 5220
diff changeset
1825 # if last element of STATIC_FILES ends with '/-',
8743b7226dc7 Fix issue with retreiving raw template files using the @@file mechanism.
John Rouillard <rouilj@ieee.org>
parents: 5220
diff changeset
1826 # we failed to find the file and we should
8743b7226dc7 Fix issue with retreiving raw template files using the @@file mechanism.
John Rouillard <rouilj@ieee.org>
parents: 5220
diff changeset
1827 # not look in TEMPLATES. So raise exception.
8743b7226dc7 Fix issue with retreiving raw template files using the @@file mechanism.
John Rouillard <rouilj@ieee.org>
parents: 5220
diff changeset
1828 if dir_option == 'STATIC_FILES' and p[-2:] == '/-':
8743b7226dc7 Fix issue with retreiving raw template files using the @@file mechanism.
John Rouillard <rouilj@ieee.org>
parents: 5220
diff changeset
1829 raise NotFound(file)
8743b7226dc7 Fix issue with retreiving raw template files using the @@file mechanism.
John Rouillard <rouilj@ieee.org>
parents: 5220
diff changeset
1830
8743b7226dc7 Fix issue with retreiving raw template files using the @@file mechanism.
John Rouillard <rouilj@ieee.org>
parents: 5220
diff changeset
1831 # ensure the load doesn't try to poke outside
8743b7226dc7 Fix issue with retreiving raw template files using the @@file mechanism.
John Rouillard <rouilj@ieee.org>
parents: 5220
diff changeset
1832 # of the static files directory
8743b7226dc7 Fix issue with retreiving raw template files using the @@file mechanism.
John Rouillard <rouilj@ieee.org>
parents: 5220
diff changeset
1833 p = os.path.normpath(p)
8743b7226dc7 Fix issue with retreiving raw template files using the @@file mechanism.
John Rouillard <rouilj@ieee.org>
parents: 5220
diff changeset
1834 filename = os.path.normpath(os.path.join(p, file))
8743b7226dc7 Fix issue with retreiving raw template files using the @@file mechanism.
John Rouillard <rouilj@ieee.org>
parents: 5220
diff changeset
1835 if os.path.isfile(filename) and filename.startswith(p):
8743b7226dc7 Fix issue with retreiving raw template files using the @@file mechanism.
John Rouillard <rouilj@ieee.org>
parents: 5220
diff changeset
1836 break # inner loop over list of directories
8743b7226dc7 Fix issue with retreiving raw template files using the @@file mechanism.
John Rouillard <rouilj@ieee.org>
parents: 5220
diff changeset
1837 else:
8743b7226dc7 Fix issue with retreiving raw template files using the @@file mechanism.
John Rouillard <rouilj@ieee.org>
parents: 5220
diff changeset
1838 # reset filename to None as sentinel for use below.
8743b7226dc7 Fix issue with retreiving raw template files using the @@file mechanism.
John Rouillard <rouilj@ieee.org>
parents: 5220
diff changeset
1839 filename = None
8743b7226dc7 Fix issue with retreiving raw template files using the @@file mechanism.
John Rouillard <rouilj@ieee.org>
parents: 5220
diff changeset
1840
8743b7226dc7 Fix issue with retreiving raw template files using the @@file mechanism.
John Rouillard <rouilj@ieee.org>
parents: 5220
diff changeset
1841 # break out of outer loop over options
8743b7226dc7 Fix issue with retreiving raw template files using the @@file mechanism.
John Rouillard <rouilj@ieee.org>
parents: 5220
diff changeset
1842 if filename:
2864
930e780c751f support STATIC_FILES directory in addition to TEMPLATES
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2853
diff changeset
1843 break
5231
8743b7226dc7 Fix issue with retreiving raw template files using the @@file mechanism.
John Rouillard <rouilj@ieee.org>
parents: 5220
diff changeset
1844
8743b7226dc7 Fix issue with retreiving raw template files using the @@file mechanism.
John Rouillard <rouilj@ieee.org>
parents: 5220
diff changeset
1845 if filename is None: # we didn't find a filename
4362
74476eaac38a more modernisation
Richard Jones <richard@users.sourceforge.net>
parents: 4344
diff changeset
1846 raise NotFound(file)
1946
c538a64b94a7 Refactored CGI file serving so that FileClass contents are...
Richard Jones <richard@users.sourceforge.net>
parents: 1937
diff changeset
1847
c538a64b94a7 Refactored CGI file serving so that FileClass contents are...
Richard Jones <richard@users.sourceforge.net>
parents: 1937
diff changeset
1848 # last-modified time
c538a64b94a7 Refactored CGI file serving so that FileClass contents are...
Richard Jones <richard@users.sourceforge.net>
parents: 1937
diff changeset
1849 lmt = os.stat(filename)[stat.ST_MTIME]
c538a64b94a7 Refactored CGI file serving so that FileClass contents are...
Richard Jones <richard@users.sourceforge.net>
parents: 1937
diff changeset
1850
c538a64b94a7 Refactored CGI file serving so that FileClass contents are...
Richard Jones <richard@users.sourceforge.net>
parents: 1937
diff changeset
1851 # detemine meta-type
c538a64b94a7 Refactored CGI file serving so that FileClass contents are...
Richard Jones <richard@users.sourceforge.net>
parents: 1937
diff changeset
1852 file = str(file)
c538a64b94a7 Refactored CGI file serving so that FileClass contents are...
Richard Jones <richard@users.sourceforge.net>
parents: 1937
diff changeset
1853 mime_type = mimetypes.guess_type(file)[0]
c538a64b94a7 Refactored CGI file serving so that FileClass contents are...
Richard Jones <richard@users.sourceforge.net>
parents: 1937
diff changeset
1854 if not mime_type:
c538a64b94a7 Refactored CGI file serving so that FileClass contents are...
Richard Jones <richard@users.sourceforge.net>
parents: 1937
diff changeset
1855 if file.endswith('.css'):
c538a64b94a7 Refactored CGI file serving so that FileClass contents are...
Richard Jones <richard@users.sourceforge.net>
parents: 1937
diff changeset
1856 mime_type = 'text/css'
c538a64b94a7 Refactored CGI file serving so that FileClass contents are...
Richard Jones <richard@users.sourceforge.net>
parents: 1937
diff changeset
1857 else:
c538a64b94a7 Refactored CGI file serving so that FileClass contents are...
Richard Jones <richard@users.sourceforge.net>
parents: 1937
diff changeset
1858 mime_type = 'text/plain'
c538a64b94a7 Refactored CGI file serving so that FileClass contents are...
Richard Jones <richard@users.sourceforge.net>
parents: 1937
diff changeset
1859
5980
54d0080769f9 Support setting cache-control headers for static files
John Rouillard <rouilj@ieee.org>
parents: 5946
diff changeset
1860 # get filename: given a/b/c.js extract c.js
54d0080769f9 Support setting cache-control headers for static files
John Rouillard <rouilj@ieee.org>
parents: 5946
diff changeset
1861 fn=file.rpartition("/")[2]
54d0080769f9 Support setting cache-control headers for static files
John Rouillard <rouilj@ieee.org>
parents: 5946
diff changeset
1862 if fn in self.Cache_Control:
54d0080769f9 Support setting cache-control headers for static files
John Rouillard <rouilj@ieee.org>
parents: 5946
diff changeset
1863 # if filename matches, don't use cache control
54d0080769f9 Support setting cache-control headers for static files
John Rouillard <rouilj@ieee.org>
parents: 5946
diff changeset
1864 # for mime type.
54d0080769f9 Support setting cache-control headers for static files
John Rouillard <rouilj@ieee.org>
parents: 5946
diff changeset
1865 self.additional_headers['Cache-Control'] = \
54d0080769f9 Support setting cache-control headers for static files
John Rouillard <rouilj@ieee.org>
parents: 5946
diff changeset
1866 self.Cache_Control[fn]
54d0080769f9 Support setting cache-control headers for static files
John Rouillard <rouilj@ieee.org>
parents: 5946
diff changeset
1867 elif mime_type in self.Cache_Control:
54d0080769f9 Support setting cache-control headers for static files
John Rouillard <rouilj@ieee.org>
parents: 5946
diff changeset
1868 self.additional_headers['Cache-Control'] = \
54d0080769f9 Support setting cache-control headers for static files
John Rouillard <rouilj@ieee.org>
parents: 5946
diff changeset
1869 self.Cache_Control[mime_type]
54d0080769f9 Support setting cache-control headers for static files
John Rouillard <rouilj@ieee.org>
parents: 5946
diff changeset
1870
4047
e70643990e9c Support the use of sendfile() for file transfer, if available.
Stefan Seefeld <stefan@seefeld.name>
parents: 4046
diff changeset
1871 self._serve_file(lmt, mime_type, '', filename)
1946
c538a64b94a7 Refactored CGI file serving so that FileClass contents are...
Richard Jones <richard@users.sourceforge.net>
parents: 1937
diff changeset
1872
4047
e70643990e9c Support the use of sendfile() for file transfer, if available.
Stefan Seefeld <stefan@seefeld.name>
parents: 4046
diff changeset
1873 def _serve_file(self, lmt, mime_type, content=None, filename=None):
4065
1e28d58c6d1c Uniformly use """...""" instead of '''...''' for comments.
Stefan Seefeld <stefan@seefeld.name>
parents: 4064
diff changeset
1874 """ guts of serve_file() and serve_static_file()
1e28d58c6d1c Uniformly use """...""" instead of '''...''' for comments.
Stefan Seefeld <stefan@seefeld.name>
parents: 4064
diff changeset
1875 """
4047
e70643990e9c Support the use of sendfile() for file transfer, if available.
Stefan Seefeld <stefan@seefeld.name>
parents: 4046
diff changeset
1876
3736
a2d22d0de0bc WSGI support via roundup.cgi.wsgi_handler
Richard Jones <richard@users.sourceforge.net>
parents: 3687
diff changeset
1877 # spit out headers
4980
13f8f88ad984 Replace rfc822 imports with email package (issue2550870)
John Kristensen <john@jerrykan.com>
parents: 4979
diff changeset
1878 self.additional_headers['Last-Modified'] = email.utils.formatdate(lmt)
3736
a2d22d0de0bc WSGI support via roundup.cgi.wsgi_handler
Richard Jones <richard@users.sourceforge.net>
parents: 3687
diff changeset
1879
1498
203f6a154b30 even better if-modified-since handling for cgi-bin
Andrey Lebedev <kedder@users.sourceforge.net>
parents: 1497
diff changeset
1880 ims = None
1469
79d8956de3f5 implemented last-modified and if-modified-since support
Richard Jones <richard@users.sourceforge.net>
parents: 1468
diff changeset
1881 # see if there's an if-modified-since...
6458
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
1882 # used if this is run behind a non-caching http proxy
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
1883 if hasattr(self.request, 'headers'):
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
1884 ims = self.request.headers.get('if-modified-since')
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
1885 elif 'HTTP_IF_MODIFIED_SINCE' in self.env:
1497
2704d8438823 better if-modified-since handling for cgi-bin
Richard Jones <richard@users.sourceforge.net>
parents: 1477
diff changeset
1886 # cgi will put the header in the env var
1469
79d8956de3f5 implemented last-modified and if-modified-since support
Richard Jones <richard@users.sourceforge.net>
parents: 1468
diff changeset
1887 ims = self.env['HTTP_IF_MODIFIED_SINCE']
79d8956de3f5 implemented last-modified and if-modified-since support
Richard Jones <richard@users.sourceforge.net>
parents: 1468
diff changeset
1888 if ims:
4980
13f8f88ad984 Replace rfc822 imports with email package (issue2550870)
John Kristensen <john@jerrykan.com>
parents: 4979
diff changeset
1889 ims = email.utils.parsedate(ims)[:6]
3800
75d3896929bb really fix the last-modified code
Richard Jones <richard@users.sourceforge.net>
parents: 3796
diff changeset
1890 lmtt = time.gmtime(lmt)[:6]
1469
79d8956de3f5 implemented last-modified and if-modified-since support
Richard Jones <richard@users.sourceforge.net>
parents: 1468
diff changeset
1891 if lmtt <= ims:
6458
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
1892 if (self.determine_content_encoding()):
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
1893 # set vary header as though we were returning 200
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
1894 # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Vary
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
1895 self.setVary("Accept-Encoding")
1469
79d8956de3f5 implemented last-modified and if-modified-since support
Richard Jones <richard@users.sourceforge.net>
parents: 1468
diff changeset
1896 raise NotModified
79d8956de3f5 implemented last-modified and if-modified-since support
Richard Jones <richard@users.sourceforge.net>
parents: 1468
diff changeset
1897
6548
de5f5f9c02f2 Fix spurious content-ty on 304; xfail css Cache-Control
John Rouillard <rouilj@ieee.org>
parents: 6546
diff changeset
1898 # don't set until we are sure we are sending a response body.
de5f5f9c02f2 Fix spurious content-ty on 304; xfail css Cache-Control
John Rouillard <rouilj@ieee.org>
parents: 6546
diff changeset
1899 self.additional_headers['Content-Type'] = mime_type
de5f5f9c02f2 Fix spurious content-ty on 304; xfail css Cache-Control
John Rouillard <rouilj@ieee.org>
parents: 6546
diff changeset
1900
4047
e70643990e9c Support the use of sendfile() for file transfer, if available.
Stefan Seefeld <stefan@seefeld.name>
parents: 4046
diff changeset
1901 if filename:
4064
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
1902 self.write_file(filename)
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
1903 else:
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
1904 self.additional_headers['Content-Length'] = str(len(content))
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
1905 self.write(content)
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
1906
4543
d16d9bf655d8 - fix handling of traceback mails to the roundup admin
Ralf Schlatterbeck <schlatterbeck@users.sourceforge.net>
parents: 4530
diff changeset
1907 def send_error_to_admin(self, subject, html, txt):
d16d9bf655d8 - fix handling of traceback mails to the roundup admin
Ralf Schlatterbeck <schlatterbeck@users.sourceforge.net>
parents: 4530
diff changeset
1908 """Send traceback information to admin via email.
d16d9bf655d8 - fix handling of traceback mails to the roundup admin
Ralf Schlatterbeck <schlatterbeck@users.sourceforge.net>
parents: 4530
diff changeset
1909 We send both, the formatted html (with more information) and
d16d9bf655d8 - fix handling of traceback mails to the roundup admin
Ralf Schlatterbeck <schlatterbeck@users.sourceforge.net>
parents: 4530
diff changeset
1910 the text version of the traceback. We use
d16d9bf655d8 - fix handling of traceback mails to the roundup admin
Ralf Schlatterbeck <schlatterbeck@users.sourceforge.net>
parents: 4530
diff changeset
1911 multipart/alternative so the receiver can chose which version
d16d9bf655d8 - fix handling of traceback mails to the roundup admin
Ralf Schlatterbeck <schlatterbeck@users.sourceforge.net>
parents: 4530
diff changeset
1912 to display.
d16d9bf655d8 - fix handling of traceback mails to the roundup admin
Ralf Schlatterbeck <schlatterbeck@users.sourceforge.net>
parents: 4530
diff changeset
1913 """
4264
b1e614c6759f Improve error reporting.
Stefan Seefeld <stefan@seefeld.name>
parents: 4263
diff changeset
1914 to = [self.mailer.config.ADMIN_EMAIL]
4543
d16d9bf655d8 - fix handling of traceback mails to the roundup admin
Ralf Schlatterbeck <schlatterbeck@users.sourceforge.net>
parents: 4530
diff changeset
1915 message = MIMEMultipart('alternative')
d16d9bf655d8 - fix handling of traceback mails to the roundup admin
Ralf Schlatterbeck <schlatterbeck@users.sourceforge.net>
parents: 4530
diff changeset
1916 self.mailer.set_message_attributes(message, to, subject)
5518
db3a95f28b3c fixed typos in send_error_to_admin
Christof Meerwald <cmeerw@cmeerw.org>
parents: 5493
diff changeset
1917 part = self.mailer.get_text_message('utf-8', 'html')
5493
725266c03eab updated mailgw to no longer use mimetools based on jerrykan's patch
Christof Meerwald <cmeerw@cmeerw.org>
parents: 5488
diff changeset
1918 part.set_payload(html, part.get_charset())
4543
d16d9bf655d8 - fix handling of traceback mails to the roundup admin
Ralf Schlatterbeck <schlatterbeck@users.sourceforge.net>
parents: 4530
diff changeset
1919 message.attach(part)
5518
db3a95f28b3c fixed typos in send_error_to_admin
Christof Meerwald <cmeerw@cmeerw.org>
parents: 5493
diff changeset
1920 part = self.mailer.get_text_message()
db3a95f28b3c fixed typos in send_error_to_admin
Christof Meerwald <cmeerw@cmeerw.org>
parents: 5493
diff changeset
1921 part.set_payload(txt, part.get_charset())
4543
d16d9bf655d8 - fix handling of traceback mails to the roundup admin
Ralf Schlatterbeck <schlatterbeck@users.sourceforge.net>
parents: 4530
diff changeset
1922 message.attach(part)
4523
a03646a02f68 Fix issue2550691 where a Unix From-Header was sometimes inserted...
Ralf Schlatterbeck <schlatterbeck@users.sourceforge.net>
parents: 4384
diff changeset
1923 self.mailer.smtp_send(to, message.as_string())
4648
e645820e8556 Clean up whitespace in client.py
Ezio Melotti <ezio.melotti@gmail.com>
parents: 4640
diff changeset
1924
4265
e24a6ca34448 Improve login failure response.
Stefan Seefeld <stefan@seefeld.name>
parents: 4264
diff changeset
1925 def renderFrontPage(self, message):
e24a6ca34448 Improve login failure response.
Stefan Seefeld <stefan@seefeld.name>
parents: 4264
diff changeset
1926 """Return the front page of the tracker."""
4648
e645820e8556 Clean up whitespace in client.py
Ezio Melotti <ezio.melotti@gmail.com>
parents: 4640
diff changeset
1927
4265
e24a6ca34448 Improve login failure response.
Stefan Seefeld <stefan@seefeld.name>
parents: 4264
diff changeset
1928 self.classname = self.nodeid = None
e24a6ca34448 Improve login failure response.
Stefan Seefeld <stefan@seefeld.name>
parents: 4264
diff changeset
1929 self.template = ''
4880
ca692423e401 Different approach to fix XSS in issue2550817
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4851
diff changeset
1930 self.add_error_message(message)
4265
e24a6ca34448 Improve login failure response.
Stefan Seefeld <stefan@seefeld.name>
parents: 4264
diff changeset
1931 self.write_html(self.renderContext())
e24a6ca34448 Improve login failure response.
Stefan Seefeld <stefan@seefeld.name>
parents: 4264
diff changeset
1932
4740
fe9568a6cbd6 Untangle template selection logic from template loading functionality.
anatoly techtonik <techtonik@gmail.com>
parents: 4739
diff changeset
1933 def selectTemplate(self, name, view):
4880
ca692423e401 Different approach to fix XSS in issue2550817
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4851
diff changeset
1934 """ Choose existing template for the given combination of
ca692423e401 Different approach to fix XSS in issue2550817
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4851
diff changeset
1935 classname (name parameter) and template request variable
ca692423e401 Different approach to fix XSS in issue2550817
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4851
diff changeset
1936 (view parameter) and return its name.
ca692423e401 Different approach to fix XSS in issue2550817
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4851
diff changeset
1937
5185
349bef975367 Make @template support two alternate templates for error and ok cases.
John Rouillard <rouilj@ieee.org>
parents: 5166
diff changeset
1938 View can be a single template or two templates separated
349bef975367 Make @template support two alternate templates for error and ok cases.
John Rouillard <rouilj@ieee.org>
parents: 5166
diff changeset
1939 by a vbar '|' character. If the Client object has a
349bef975367 Make @template support two alternate templates for error and ok cases.
John Rouillard <rouilj@ieee.org>
parents: 5166
diff changeset
1940 non-empty _error_message attribute, the right hand
349bef975367 Make @template support two alternate templates for error and ok cases.
John Rouillard <rouilj@ieee.org>
parents: 5166
diff changeset
1941 template (error template) will be used. If the
349bef975367 Make @template support two alternate templates for error and ok cases.
John Rouillard <rouilj@ieee.org>
parents: 5166
diff changeset
1942 _error_message is empty, the left hand template (ok
349bef975367 Make @template support two alternate templates for error and ok cases.
John Rouillard <rouilj@ieee.org>
parents: 5166
diff changeset
1943 template) will be used.
349bef975367 Make @template support two alternate templates for error and ok cases.
John Rouillard <rouilj@ieee.org>
parents: 5166
diff changeset
1944
4880
ca692423e401 Different approach to fix XSS in issue2550817
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4851
diff changeset
1945 In most cases the name will be "classname.view", but
ca692423e401 Different approach to fix XSS in issue2550817
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4851
diff changeset
1946 if "view" is None, then template name "classname" will
ca692423e401 Different approach to fix XSS in issue2550817
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4851
diff changeset
1947 be returned.
ca692423e401 Different approach to fix XSS in issue2550817
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4851
diff changeset
1948
ca692423e401 Different approach to fix XSS in issue2550817
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4851
diff changeset
1949 If "classname.view" template doesn't exist, the
4740
fe9568a6cbd6 Untangle template selection logic from template loading functionality.
anatoly techtonik <techtonik@gmail.com>
parents: 4739
diff changeset
1950 "_generic.view" is used as a fallback.
fe9568a6cbd6 Untangle template selection logic from template loading functionality.
anatoly techtonik <techtonik@gmail.com>
parents: 4739
diff changeset
1951
fe9568a6cbd6 Untangle template selection logic from template loading functionality.
anatoly techtonik <techtonik@gmail.com>
parents: 4739
diff changeset
1952 [ ] cover with tests
fe9568a6cbd6 Untangle template selection logic from template loading functionality.
anatoly techtonik <techtonik@gmail.com>
parents: 4739
diff changeset
1953 """
5185
349bef975367 Make @template support two alternate templates for error and ok cases.
John Rouillard <rouilj@ieee.org>
parents: 5166
diff changeset
1954
349bef975367 Make @template support two alternate templates for error and ok cases.
John Rouillard <rouilj@ieee.org>
parents: 5166
diff changeset
1955 # determine if view is oktmpl|errortmpl. If so assign the
349bef975367 Make @template support two alternate templates for error and ok cases.
John Rouillard <rouilj@ieee.org>
parents: 5166
diff changeset
1956 # right one to the view parameter. If we don't have alternate
349bef975367 Make @template support two alternate templates for error and ok cases.
John Rouillard <rouilj@ieee.org>
parents: 5166
diff changeset
1957 # templates, just leave view alone.
5188
8768a95c9a4f Small fix. Make sure view is defined before trying to find('|') in it.
John Rouillard <rouilj@ieee.org>
parents: 5185
diff changeset
1958 if (view and view.find('|') != -1 ):
5185
349bef975367 Make @template support two alternate templates for error and ok cases.
John Rouillard <rouilj@ieee.org>
parents: 5166
diff changeset
1959 # we have alternate templates, parse them apart.
349bef975367 Make @template support two alternate templates for error and ok cases.
John Rouillard <rouilj@ieee.org>
parents: 5166
diff changeset
1960 (oktmpl, errortmpl) = view.split("|", 2)
349bef975367 Make @template support two alternate templates for error and ok cases.
John Rouillard <rouilj@ieee.org>
parents: 5166
diff changeset
1961 if self._error_message:
349bef975367 Make @template support two alternate templates for error and ok cases.
John Rouillard <rouilj@ieee.org>
parents: 5166
diff changeset
1962 # we have an error, use errortmpl
349bef975367 Make @template support two alternate templates for error and ok cases.
John Rouillard <rouilj@ieee.org>
parents: 5166
diff changeset
1963 view = errortmpl
349bef975367 Make @template support two alternate templates for error and ok cases.
John Rouillard <rouilj@ieee.org>
parents: 5166
diff changeset
1964 else:
349bef975367 Make @template support two alternate templates for error and ok cases.
John Rouillard <rouilj@ieee.org>
parents: 5166
diff changeset
1965 # no error message recorded, use oktmpl
349bef975367 Make @template support two alternate templates for error and ok cases.
John Rouillard <rouilj@ieee.org>
parents: 5166
diff changeset
1966 view = oktmpl
349bef975367 Make @template support two alternate templates for error and ok cases.
John Rouillard <rouilj@ieee.org>
parents: 5166
diff changeset
1967
4739
94be76e04140 templating: Move template selection logic from the template loaders
anatoly techtonik <techtonik@gmail.com>
parents: 4728
diff changeset
1968 loader = self.instance.templates
94be76e04140 templating: Move template selection logic from the template loaders
anatoly techtonik <techtonik@gmail.com>
parents: 4728
diff changeset
1969
94be76e04140 templating: Move template selection logic from the template loaders
anatoly techtonik <techtonik@gmail.com>
parents: 4728
diff changeset
1970 # if classname is not set, use "home" template
94be76e04140 templating: Move template selection logic from the template loaders
anatoly techtonik <techtonik@gmail.com>
parents: 4728
diff changeset
1971 if name is None:
94be76e04140 templating: Move template selection logic from the template loaders
anatoly techtonik <techtonik@gmail.com>
parents: 4728
diff changeset
1972 name = 'home'
94be76e04140 templating: Move template selection logic from the template loaders
anatoly techtonik <techtonik@gmail.com>
parents: 4728
diff changeset
1973
4740
fe9568a6cbd6 Untangle template selection logic from template loading functionality.
anatoly techtonik <techtonik@gmail.com>
parents: 4739
diff changeset
1974 tplname = name
fe9568a6cbd6 Untangle template selection logic from template loading functionality.
anatoly techtonik <techtonik@gmail.com>
parents: 4739
diff changeset
1975 if view:
5154
f608eeecf638 issue2550891: Allow subdir in template value. Anthony (antmail)
John Rouillard <rouilj@ieee.org>
parents: 5119
diff changeset
1976 # Support subdirectories for templates. Value is path/to/VIEW
f608eeecf638 issue2550891: Allow subdir in template value. Anthony (antmail)
John Rouillard <rouilj@ieee.org>
parents: 5119
diff changeset
1977 # or just VIEW if the template is in the html directory of
f608eeecf638 issue2550891: Allow subdir in template value. Anthony (antmail)
John Rouillard <rouilj@ieee.org>
parents: 5119
diff changeset
1978 # the tracker.
f608eeecf638 issue2550891: Allow subdir in template value. Anthony (antmail)
John Rouillard <rouilj@ieee.org>
parents: 5119
diff changeset
1979 slash_loc = view.rfind("/")
f608eeecf638 issue2550891: Allow subdir in template value. Anthony (antmail)
John Rouillard <rouilj@ieee.org>
parents: 5119
diff changeset
1980 if slash_loc == -1:
f608eeecf638 issue2550891: Allow subdir in template value. Anthony (antmail)
John Rouillard <rouilj@ieee.org>
parents: 5119
diff changeset
1981 # try plain class.view
f608eeecf638 issue2550891: Allow subdir in template value. Anthony (antmail)
John Rouillard <rouilj@ieee.org>
parents: 5119
diff changeset
1982 tplname = '%s.%s' % (name, view)
f608eeecf638 issue2550891: Allow subdir in template value. Anthony (antmail)
John Rouillard <rouilj@ieee.org>
parents: 5119
diff changeset
1983 else:
f608eeecf638 issue2550891: Allow subdir in template value. Anthony (antmail)
John Rouillard <rouilj@ieee.org>
parents: 5119
diff changeset
1984 # try path/class.view
f608eeecf638 issue2550891: Allow subdir in template value. Anthony (antmail)
John Rouillard <rouilj@ieee.org>
parents: 5119
diff changeset
1985 tplname = '%s/%s.%s'%(
f608eeecf638 issue2550891: Allow subdir in template value. Anthony (antmail)
John Rouillard <rouilj@ieee.org>
parents: 5119
diff changeset
1986 view[:slash_loc], name, view[slash_loc+1:])
4740
fe9568a6cbd6 Untangle template selection logic from template loading functionality.
anatoly techtonik <techtonik@gmail.com>
parents: 4739
diff changeset
1987
fe9568a6cbd6 Untangle template selection logic from template loading functionality.
anatoly techtonik <techtonik@gmail.com>
parents: 4739
diff changeset
1988 if loader.check(tplname):
fe9568a6cbd6 Untangle template selection logic from template loading functionality.
anatoly techtonik <techtonik@gmail.com>
parents: 4739
diff changeset
1989 return tplname
fe9568a6cbd6 Untangle template selection logic from template loading functionality.
anatoly techtonik <techtonik@gmail.com>
parents: 4739
diff changeset
1990
fe9568a6cbd6 Untangle template selection logic from template loading functionality.
anatoly techtonik <techtonik@gmail.com>
parents: 4739
diff changeset
1991 # rendering class/context with generic template for this view.
fe9568a6cbd6 Untangle template selection logic from template loading functionality.
anatoly techtonik <techtonik@gmail.com>
parents: 4739
diff changeset
1992 # with no view it's impossible to choose which generic template to use
fe9568a6cbd6 Untangle template selection logic from template loading functionality.
anatoly techtonik <techtonik@gmail.com>
parents: 4739
diff changeset
1993 if not view:
fe9568a6cbd6 Untangle template selection logic from template loading functionality.
anatoly techtonik <techtonik@gmail.com>
parents: 4739
diff changeset
1994 raise templating.NoTemplate('Template "%s" doesn\'t exist' % name)
fe9568a6cbd6 Untangle template selection logic from template loading functionality.
anatoly techtonik <techtonik@gmail.com>
parents: 4739
diff changeset
1995
5154
f608eeecf638 issue2550891: Allow subdir in template value. Anthony (antmail)
John Rouillard <rouilj@ieee.org>
parents: 5119
diff changeset
1996 if slash_loc == -1:
f608eeecf638 issue2550891: Allow subdir in template value. Anthony (antmail)
John Rouillard <rouilj@ieee.org>
parents: 5119
diff changeset
1997 generic = '_generic.%s' % view
f608eeecf638 issue2550891: Allow subdir in template value. Anthony (antmail)
John Rouillard <rouilj@ieee.org>
parents: 5119
diff changeset
1998 else:
f608eeecf638 issue2550891: Allow subdir in template value. Anthony (antmail)
John Rouillard <rouilj@ieee.org>
parents: 5119
diff changeset
1999 generic = '%s/_generic.%s' % (view[:slash_loc], view[slash_loc+1:])
4740
fe9568a6cbd6 Untangle template selection logic from template loading functionality.
anatoly techtonik <techtonik@gmail.com>
parents: 4739
diff changeset
2000 if loader.check(generic):
fe9568a6cbd6 Untangle template selection logic from template loading functionality.
anatoly techtonik <techtonik@gmail.com>
parents: 4739
diff changeset
2001 return generic
fe9568a6cbd6 Untangle template selection logic from template loading functionality.
anatoly techtonik <techtonik@gmail.com>
parents: 4739
diff changeset
2002
fe9568a6cbd6 Untangle template selection logic from template loading functionality.
anatoly techtonik <techtonik@gmail.com>
parents: 4739
diff changeset
2003 raise templating.NoTemplate('No template file exists for templating '
fe9568a6cbd6 Untangle template selection logic from template loading functionality.
anatoly techtonik <techtonik@gmail.com>
parents: 4739
diff changeset
2004 '"%s" with template "%s" (neither "%s" nor "%s")' % (name, view,
fe9568a6cbd6 Untangle template selection logic from template loading functionality.
anatoly techtonik <techtonik@gmail.com>
parents: 4739
diff changeset
2005 tplname, generic))
4739
94be76e04140 templating: Move template selection logic from the template loaders
anatoly techtonik <techtonik@gmail.com>
parents: 4728
diff changeset
2006
1204
b862bbf2067a Replaced the content() callback ickiness with Page Template macro usage
Richard Jones <richard@users.sourceforge.net>
parents: 1196
diff changeset
2007 def renderContext(self):
4065
1e28d58c6d1c Uniformly use """...""" instead of '''...''' for comments.
Stefan Seefeld <stefan@seefeld.name>
parents: 4064
diff changeset
2008 """ Return a PageTemplate for the named page
1e28d58c6d1c Uniformly use """...""" instead of '''...''' for comments.
Stefan Seefeld <stefan@seefeld.name>
parents: 4064
diff changeset
2009 """
6382
b35a50d02890 Fix issue2551129 - Template not found return 500 and traceback
John Rouillard <rouilj@ieee.org>
parents: 6267
diff changeset
2010 try:
b35a50d02890 Fix issue2551129 - Template not found return 500 and traceback
John Rouillard <rouilj@ieee.org>
parents: 6267
diff changeset
2011 tplname = self.selectTemplate(self.classname, self.template)
1204
b862bbf2067a Replaced the content() callback ickiness with Page Template macro usage
Richard Jones <richard@users.sourceforge.net>
parents: 1196
diff changeset
2012
6382
b35a50d02890 Fix issue2551129 - Template not found return 500 and traceback
John Rouillard <rouilj@ieee.org>
parents: 6267
diff changeset
2013 # catch errors so we can handle PT rendering errors more nicely
b35a50d02890 Fix issue2551129 - Template not found return 500 and traceback
John Rouillard <rouilj@ieee.org>
parents: 6267
diff changeset
2014 args = {
b35a50d02890 Fix issue2551129 - Template not found return 500 and traceback
John Rouillard <rouilj@ieee.org>
parents: 6267
diff changeset
2015 'ok_message': self._ok_message,
b35a50d02890 Fix issue2551129 - Template not found return 500 and traceback
John Rouillard <rouilj@ieee.org>
parents: 6267
diff changeset
2016 'error_message': self._error_message
b35a50d02890 Fix issue2551129 - Template not found return 500 and traceback
John Rouillard <rouilj@ieee.org>
parents: 6267
diff changeset
2017 }
4740
fe9568a6cbd6 Untangle template selection logic from template loading functionality.
anatoly techtonik <techtonik@gmail.com>
parents: 4739
diff changeset
2018 pt = self.instance.templates.load(tplname)
1016
d6c13142e7b9 Keep a cache of compiled PageTemplates.
Richard Jones <richard@users.sourceforge.net>
parents: 1008
diff changeset
2019 # let the template render figure stuff out
6588
91ab3e0ffcd0 Summary: Add test cases for sqlite fts
John Rouillard <rouilj@ieee.org>
parents: 6550
diff changeset
2020 try:
91ab3e0ffcd0 Summary: Add test cases for sqlite fts
John Rouillard <rouilj@ieee.org>
parents: 6550
diff changeset
2021 result = pt.render(self, None, None, **args)
91ab3e0ffcd0 Summary: Add test cases for sqlite fts
John Rouillard <rouilj@ieee.org>
parents: 6550
diff changeset
2022 except IndexerQueryError as e:
91ab3e0ffcd0 Summary: Add test cases for sqlite fts
John Rouillard <rouilj@ieee.org>
parents: 6550
diff changeset
2023 result = self.renderError(e.args[0])
91ab3e0ffcd0 Summary: Add test cases for sqlite fts
John Rouillard <rouilj@ieee.org>
parents: 6550
diff changeset
2024
1967
d30cd44321f2 commit old file-serving bugfix, and new pt content-type fix
Richard Jones <richard@users.sourceforge.net>
parents: 1946
diff changeset
2025 self.additional_headers['Content-Type'] = pt.content_type
2942
a50e4f7c9276 look for CGI_SHOW_TIMING in self.env instead of os.environ;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2940
diff changeset
2026 if self.env.get('CGI_SHOW_TIMING', ''):
a50e4f7c9276 look for CGI_SHOW_TIMING in self.env instead of os.environ;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2940
diff changeset
2027 if self.env['CGI_SHOW_TIMING'].upper() == 'COMMENT':
a50e4f7c9276 look for CGI_SHOW_TIMING in self.env instead of os.environ;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2940
diff changeset
2028 timings = {'starttag': '<!-- ', 'endtag': ' -->'}
a50e4f7c9276 look for CGI_SHOW_TIMING in self.env instead of os.environ;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2940
diff changeset
2029 else:
a50e4f7c9276 look for CGI_SHOW_TIMING in self.env instead of os.environ;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2940
diff changeset
2030 timings = {'starttag': '<p>', 'endtag': '</p>'}
a50e4f7c9276 look for CGI_SHOW_TIMING in self.env instead of os.environ;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2940
diff changeset
2031 timings['seconds'] = time.time()-self.start
a50e4f7c9276 look for CGI_SHOW_TIMING in self.env instead of os.environ;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2940
diff changeset
2032 s = self._('%(starttag)sTime elapsed: %(seconds)fs%(endtag)s\n'
a50e4f7c9276 look for CGI_SHOW_TIMING in self.env instead of os.environ;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2940
diff changeset
2033 ) % timings
2237
f624fc20f8fe added capturing of stats
Richard Jones <richard@users.sourceforge.net>
parents: 2233
diff changeset
2034 if hasattr(self.db, 'stats'):
2942
a50e4f7c9276 look for CGI_SHOW_TIMING in self.env instead of os.environ;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2940
diff changeset
2035 timings.update(self.db.stats)
a50e4f7c9276 look for CGI_SHOW_TIMING in self.env instead of os.environ;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2940
diff changeset
2036 s += self._("%(starttag)sCache hits: %(cache_hits)d,"
a50e4f7c9276 look for CGI_SHOW_TIMING in self.env instead of os.environ;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2940
diff changeset
2037 " misses %(cache_misses)d."
a50e4f7c9276 look for CGI_SHOW_TIMING in self.env instead of os.environ;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2940
diff changeset
2038 " Loading items: %(get_items)f secs."
a50e4f7c9276 look for CGI_SHOW_TIMING in self.env instead of os.environ;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2940
diff changeset
2039 " Filtering: %(filtering)f secs."
a50e4f7c9276 look for CGI_SHOW_TIMING in self.env instead of os.environ;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2940
diff changeset
2040 "%(endtag)s\n") % timings
2237
f624fc20f8fe added capturing of stats
Richard Jones <richard@users.sourceforge.net>
parents: 2233
diff changeset
2041 s += '</body>'
2230
ca2664e095be disable forking server when os.fork() not available [SF#938586]
Richard Jones <richard@users.sourceforge.net>
parents: 2183
diff changeset
2042 result = result.replace('</body>', s)
1967
d30cd44321f2 commit old file-serving bugfix, and new pt content-type fix
Richard Jones <richard@users.sourceforge.net>
parents: 1946
diff changeset
2043 return result
5248
198b6e810c67 Use Python-3-compatible 'as' syntax for except statements
Eric S. Raymond <esr@thyrsus.com>
parents: 5231
diff changeset
2044 except templating.NoTemplate as message:
6382
b35a50d02890 Fix issue2551129 - Template not found return 500 and traceback
John Rouillard <rouilj@ieee.org>
parents: 6267
diff changeset
2045 self.response_code = 400
5802
0e6d45413e88 catching last couple of cgi.escape references.
John Rouillard <rouilj@ieee.org>
parents: 5775
diff changeset
2046 return '<strong>%s</strong>'%html_escape(str(message))
5248
198b6e810c67 Use Python-3-compatible 'as' syntax for except statements
Eric S. Raymond <esr@thyrsus.com>
parents: 5231
diff changeset
2047 except templating.Unauthorised as message:
5802
0e6d45413e88 catching last couple of cgi.escape references.
John Rouillard <rouilj@ieee.org>
parents: 5775
diff changeset
2048 raise Unauthorised(html_escape(str(message)))
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
2049 except:
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
2050 # everything else
4045
82213b1971b4 Only feed back traceback to web users if config.WEB_DEBUG is True
Stefan Seefeld <stefan@seefeld.name>
parents: 4027
diff changeset
2051 if self.instance.config.WEB_DEBUG:
82213b1971b4 Only feed back traceback to web users if config.WEB_DEBUG is True
Stefan Seefeld <stefan@seefeld.name>
parents: 4027
diff changeset
2052 return cgitb.pt_html(i18n=self.translator)
82213b1971b4 Only feed back traceback to web users if config.WEB_DEBUG is True
Stefan Seefeld <stefan@seefeld.name>
parents: 4027
diff changeset
2053 exc_info = sys.exc_info()
82213b1971b4 Only feed back traceback to web users if config.WEB_DEBUG is True
Stefan Seefeld <stefan@seefeld.name>
parents: 4027
diff changeset
2054 try:
82213b1971b4 Only feed back traceback to web users if config.WEB_DEBUG is True
Stefan Seefeld <stefan@seefeld.name>
parents: 4027
diff changeset
2055 # If possible, send the HTML page template traceback
82213b1971b4 Only feed back traceback to web users if config.WEB_DEBUG is True
Stefan Seefeld <stefan@seefeld.name>
parents: 4027
diff changeset
2056 # to the administrator.
82213b1971b4 Only feed back traceback to web users if config.WEB_DEBUG is True
Stefan Seefeld <stefan@seefeld.name>
parents: 4027
diff changeset
2057 subject = "Templating Error: %s" % exc_info[1]
4543
d16d9bf655d8 - fix handling of traceback mails to the roundup admin
Ralf Schlatterbeck <schlatterbeck@users.sourceforge.net>
parents: 4530
diff changeset
2058 self.send_error_to_admin(subject, cgitb.pt_html(), format_exc())
4045
82213b1971b4 Only feed back traceback to web users if config.WEB_DEBUG is True
Stefan Seefeld <stefan@seefeld.name>
parents: 4027
diff changeset
2059 # Now report the error to the user.
4880
ca692423e401 Different approach to fix XSS in issue2550817
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4851
diff changeset
2060 return self._(default_err_msg)
4045
82213b1971b4 Only feed back traceback to web users if config.WEB_DEBUG is True
Stefan Seefeld <stefan@seefeld.name>
parents: 4027
diff changeset
2061 except:
82213b1971b4 Only feed back traceback to web users if config.WEB_DEBUG is True
Stefan Seefeld <stefan@seefeld.name>
parents: 4027
diff changeset
2062 # Reraise the original exception. The user will
82213b1971b4 Only feed back traceback to web users if config.WEB_DEBUG is True
Stefan Seefeld <stefan@seefeld.name>
parents: 4027
diff changeset
2063 # receive an error message, and the adminstrator will
82213b1971b4 Only feed back traceback to web users if config.WEB_DEBUG is True
Stefan Seefeld <stefan@seefeld.name>
parents: 4027
diff changeset
2064 # receive a traceback, albeit with less information
82213b1971b4 Only feed back traceback to web users if config.WEB_DEBUG is True
Stefan Seefeld <stefan@seefeld.name>
parents: 4027
diff changeset
2065 # than the one we tried to generate above.
5378
35ea9b1efc14 Python 3 preparation: "raise" syntax.
Joseph Myers <jsm@polyomino.org.uk>
parents: 5356
diff changeset
2066 if sys.version_info[0] > 2:
35ea9b1efc14 Python 3 preparation: "raise" syntax.
Joseph Myers <jsm@polyomino.org.uk>
parents: 5356
diff changeset
2067 raise exc_info[0](exc_info[1]).with_traceback(exc_info[2])
35ea9b1efc14 Python 3 preparation: "raise" syntax.
Joseph Myers <jsm@polyomino.org.uk>
parents: 5356
diff changeset
2068 else:
6014
6ed03d01491d Bandit - ignore use of exec which re-raises exception
John Rouillard <rouilj@ieee.org>
parents: 5980
diff changeset
2069 exec('raise exc_info[0], exc_info[1], exc_info[2]') # nosec
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
2070
6588
91ab3e0ffcd0 Summary: Add test cases for sqlite fts
John Rouillard <rouilj@ieee.org>
parents: 6550
diff changeset
2071 def renderError(self, error, response_code=400, use_template=True):
91ab3e0ffcd0 Summary: Add test cases for sqlite fts
John Rouillard <rouilj@ieee.org>
parents: 6550
diff changeset
2072 self.response_code = response_code
91ab3e0ffcd0 Summary: Add test cases for sqlite fts
John Rouillard <rouilj@ieee.org>
parents: 6550
diff changeset
2073
91ab3e0ffcd0 Summary: Add test cases for sqlite fts
John Rouillard <rouilj@ieee.org>
parents: 6550
diff changeset
2074 # see if error message already logged add if not
91ab3e0ffcd0 Summary: Add test cases for sqlite fts
John Rouillard <rouilj@ieee.org>
parents: 6550
diff changeset
2075 if error not in self._error_message:
91ab3e0ffcd0 Summary: Add test cases for sqlite fts
John Rouillard <rouilj@ieee.org>
parents: 6550
diff changeset
2076 self.add_error_message(error, escape=True)
91ab3e0ffcd0 Summary: Add test cases for sqlite fts
John Rouillard <rouilj@ieee.org>
parents: 6550
diff changeset
2077
91ab3e0ffcd0 Summary: Add test cases for sqlite fts
John Rouillard <rouilj@ieee.org>
parents: 6550
diff changeset
2078 # allow use of template for a specific code
91ab3e0ffcd0 Summary: Add test cases for sqlite fts
John Rouillard <rouilj@ieee.org>
parents: 6550
diff changeset
2079 trial_templates = []
91ab3e0ffcd0 Summary: Add test cases for sqlite fts
John Rouillard <rouilj@ieee.org>
parents: 6550
diff changeset
2080 if use_template:
91ab3e0ffcd0 Summary: Add test cases for sqlite fts
John Rouillard <rouilj@ieee.org>
parents: 6550
diff changeset
2081 if response_code == 400:
91ab3e0ffcd0 Summary: Add test cases for sqlite fts
John Rouillard <rouilj@ieee.org>
parents: 6550
diff changeset
2082 trial_templates = [ "400" ]
91ab3e0ffcd0 Summary: Add test cases for sqlite fts
John Rouillard <rouilj@ieee.org>
parents: 6550
diff changeset
2083 else:
91ab3e0ffcd0 Summary: Add test cases for sqlite fts
John Rouillard <rouilj@ieee.org>
parents: 6550
diff changeset
2084 trial_templates = [ str(response_code), "400" ]
91ab3e0ffcd0 Summary: Add test cases for sqlite fts
John Rouillard <rouilj@ieee.org>
parents: 6550
diff changeset
2085
91ab3e0ffcd0 Summary: Add test cases for sqlite fts
John Rouillard <rouilj@ieee.org>
parents: 6550
diff changeset
2086 tplname = None
91ab3e0ffcd0 Summary: Add test cases for sqlite fts
John Rouillard <rouilj@ieee.org>
parents: 6550
diff changeset
2087 for rcode in trial_templates:
91ab3e0ffcd0 Summary: Add test cases for sqlite fts
John Rouillard <rouilj@ieee.org>
parents: 6550
diff changeset
2088 try:
91ab3e0ffcd0 Summary: Add test cases for sqlite fts
John Rouillard <rouilj@ieee.org>
parents: 6550
diff changeset
2089 tplname = self.selectTemplate(self.classname, rcode)
91ab3e0ffcd0 Summary: Add test cases for sqlite fts
John Rouillard <rouilj@ieee.org>
parents: 6550
diff changeset
2090 break
91ab3e0ffcd0 Summary: Add test cases for sqlite fts
John Rouillard <rouilj@ieee.org>
parents: 6550
diff changeset
2091 except templating.NoTemplate:
91ab3e0ffcd0 Summary: Add test cases for sqlite fts
John Rouillard <rouilj@ieee.org>
parents: 6550
diff changeset
2092 pass
91ab3e0ffcd0 Summary: Add test cases for sqlite fts
John Rouillard <rouilj@ieee.org>
parents: 6550
diff changeset
2093
91ab3e0ffcd0 Summary: Add test cases for sqlite fts
John Rouillard <rouilj@ieee.org>
parents: 6550
diff changeset
2094 if not tplname:
91ab3e0ffcd0 Summary: Add test cases for sqlite fts
John Rouillard <rouilj@ieee.org>
parents: 6550
diff changeset
2095 # call string of serious error to get basic html
91ab3e0ffcd0 Summary: Add test cases for sqlite fts
John Rouillard <rouilj@ieee.org>
parents: 6550
diff changeset
2096 # response.
91ab3e0ffcd0 Summary: Add test cases for sqlite fts
John Rouillard <rouilj@ieee.org>
parents: 6550
diff changeset
2097 return str(SeriousError(error))
91ab3e0ffcd0 Summary: Add test cases for sqlite fts
John Rouillard <rouilj@ieee.org>
parents: 6550
diff changeset
2098
91ab3e0ffcd0 Summary: Add test cases for sqlite fts
John Rouillard <rouilj@ieee.org>
parents: 6550
diff changeset
2099 args = {
91ab3e0ffcd0 Summary: Add test cases for sqlite fts
John Rouillard <rouilj@ieee.org>
parents: 6550
diff changeset
2100 'ok_message': self._ok_message,
91ab3e0ffcd0 Summary: Add test cases for sqlite fts
John Rouillard <rouilj@ieee.org>
parents: 6550
diff changeset
2101 'error_message': self._error_message
91ab3e0ffcd0 Summary: Add test cases for sqlite fts
John Rouillard <rouilj@ieee.org>
parents: 6550
diff changeset
2102 }
91ab3e0ffcd0 Summary: Add test cases for sqlite fts
John Rouillard <rouilj@ieee.org>
parents: 6550
diff changeset
2103
91ab3e0ffcd0 Summary: Add test cases for sqlite fts
John Rouillard <rouilj@ieee.org>
parents: 6550
diff changeset
2104 try:
91ab3e0ffcd0 Summary: Add test cases for sqlite fts
John Rouillard <rouilj@ieee.org>
parents: 6550
diff changeset
2105 pt = self.instance.templates.load(tplname)
91ab3e0ffcd0 Summary: Add test cases for sqlite fts
John Rouillard <rouilj@ieee.org>
parents: 6550
diff changeset
2106 return pt.render(self, None, None, **args)
91ab3e0ffcd0 Summary: Add test cases for sqlite fts
John Rouillard <rouilj@ieee.org>
parents: 6550
diff changeset
2107 except Exception:
91ab3e0ffcd0 Summary: Add test cases for sqlite fts
John Rouillard <rouilj@ieee.org>
parents: 6550
diff changeset
2108 # report original error
91ab3e0ffcd0 Summary: Add test cases for sqlite fts
John Rouillard <rouilj@ieee.org>
parents: 6550
diff changeset
2109 return str(SeriousError(error))
91ab3e0ffcd0 Summary: Add test cases for sqlite fts
John Rouillard <rouilj@ieee.org>
parents: 6550
diff changeset
2110
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
2111 # these are the actions that are available
2904
b1ad7add1a2c back out
Richard Jones <richard@users.sourceforge.net>
parents: 2903
diff changeset
2112 actions = (
5073
d0aa596daca8 Remove 'import *' statement from cgi/client.py
John Kristensen <john@jerrykan.com>
parents: 5044
diff changeset
2113 ('edit', actions.EditItemAction),
d0aa596daca8 Remove 'import *' statement from cgi/client.py
John Kristensen <john@jerrykan.com>
parents: 5044
diff changeset
2114 ('editcsv', actions.EditCSVAction),
d0aa596daca8 Remove 'import *' statement from cgi/client.py
John Kristensen <john@jerrykan.com>
parents: 5044
diff changeset
2115 ('new', actions.NewItemAction),
d0aa596daca8 Remove 'import *' statement from cgi/client.py
John Kristensen <john@jerrykan.com>
parents: 5044
diff changeset
2116 ('register', actions.RegisterAction),
d0aa596daca8 Remove 'import *' statement from cgi/client.py
John Kristensen <john@jerrykan.com>
parents: 5044
diff changeset
2117 ('confrego', actions.ConfRegoAction),
d0aa596daca8 Remove 'import *' statement from cgi/client.py
John Kristensen <john@jerrykan.com>
parents: 5044
diff changeset
2118 ('passrst', actions.PassResetAction),
d0aa596daca8 Remove 'import *' statement from cgi/client.py
John Kristensen <john@jerrykan.com>
parents: 5044
diff changeset
2119 ('login', actions.LoginAction),
d0aa596daca8 Remove 'import *' statement from cgi/client.py
John Kristensen <john@jerrykan.com>
parents: 5044
diff changeset
2120 ('logout', actions.LogoutAction),
d0aa596daca8 Remove 'import *' statement from cgi/client.py
John Kristensen <john@jerrykan.com>
parents: 5044
diff changeset
2121 ('search', actions.SearchAction),
5119
748ba87e1aca Added a new cgi action restore. The opposite of (and a clone of) the existing retire action.
John Rouillard <rouilj@ieee.org>
parents: 5079
diff changeset
2122 ('restore', actions.RestoreAction),
5073
d0aa596daca8 Remove 'import *' statement from cgi/client.py
John Kristensen <john@jerrykan.com>
parents: 5044
diff changeset
2123 ('retire', actions.RetireAction),
d0aa596daca8 Remove 'import *' statement from cgi/client.py
John Kristensen <john@jerrykan.com>
parents: 5044
diff changeset
2124 ('show', actions.ShowAction),
d0aa596daca8 Remove 'import *' statement from cgi/client.py
John Kristensen <john@jerrykan.com>
parents: 5044
diff changeset
2125 ('export_csv', actions.ExportCSVAction),
5614
be99aa02c616 issue2550833 enhance the export csv action to include the keys for
John Rouillard <rouilj@ieee.org>
parents: 5608
diff changeset
2126 ('export_csv_id', actions.ExportCSVWithIdAction),
2904
b1ad7add1a2c back out
Richard Jones <richard@users.sourceforge.net>
parents: 2903
diff changeset
2127 )
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
2128 def handle_action(self):
4065
1e28d58c6d1c Uniformly use """...""" instead of '''...''' for comments.
Stefan Seefeld <stefan@seefeld.name>
parents: 4064
diff changeset
2129 """ Determine whether there should be an Action called.
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
2130
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
2131 The action is defined by the form variable :action which
1477
ed725179953d Added password reset facility for forgotten passwords.
Richard Jones <richard@users.sourceforge.net>
parents: 1472
diff changeset
2132 identifies the method on this object to call. The actions
2904
b1ad7add1a2c back out
Richard Jones <richard@users.sourceforge.net>
parents: 2903
diff changeset
2133 are defined in the "actions" sequence on this class.
2045
d124af927369 Forward-porting of fixes from the maintenance branch.
Richard Jones <richard@users.sourceforge.net>
parents: 2032
diff changeset
2134
d124af927369 Forward-porting of fixes from the maintenance branch.
Richard Jones <richard@users.sourceforge.net>
parents: 2032
diff changeset
2135 Actions may return a page (by default HTML) to return to the
d124af927369 Forward-porting of fixes from the maintenance branch.
Richard Jones <richard@users.sourceforge.net>
parents: 2032
diff changeset
2136 user, bypassing the usual template rendering.
3388
0c66acaea802 present Reject exception messages to web users [SF#1237685]
Richard Jones <richard@users.sourceforge.net>
parents: 3356
diff changeset
2137
0c66acaea802 present Reject exception messages to web users [SF#1237685]
Richard Jones <richard@users.sourceforge.net>
parents: 3356
diff changeset
2138 We explicitly catch Reject and ValueError exceptions and
0c66acaea802 present Reject exception messages to web users [SF#1237685]
Richard Jones <richard@users.sourceforge.net>
parents: 3356
diff changeset
2139 present their messages to the user.
4065
1e28d58c6d1c Uniformly use """...""" instead of '''...''' for comments.
Stefan Seefeld <stefan@seefeld.name>
parents: 4064
diff changeset
2140 """
4804
bc4144417861 More fixes for form TypeError
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4802
diff changeset
2141 action = None
bc4144417861 More fixes for form TypeError
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4802
diff changeset
2142 try:
bc4144417861 More fixes for form TypeError
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4802
diff changeset
2143 if ':action' in self.form:
bc4144417861 More fixes for form TypeError
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4802
diff changeset
2144 action = self.form[':action']
bc4144417861 More fixes for form TypeError
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4802
diff changeset
2145 elif '@action' in self.form:
bc4144417861 More fixes for form TypeError
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4802
diff changeset
2146 action = self.form['@action']
bc4144417861 More fixes for form TypeError
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4802
diff changeset
2147 except TypeError:
bc4144417861 More fixes for form TypeError
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4802
diff changeset
2148 pass
bc4144417861 More fixes for form TypeError
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4802
diff changeset
2149 if action is None:
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
2150 return None
2638
18e86941c950 Load up extensions in the tracker "extensions" directory.
Richard Jones <richard@users.sourceforge.net>
parents: 2592
diff changeset
2151
4367
fa5587802af9 Handle multiple @action values from broken trackers
Richard Jones <richard@users.sourceforge.net>
parents: 4362
diff changeset
2152 if isinstance(action, list):
fa5587802af9 Handle multiple @action values from broken trackers
Richard Jones <richard@users.sourceforge.net>
parents: 4362
diff changeset
2153 raise SeriousError('broken form: multiple @action values submitted')
fa5587802af9 Handle multiple @action values from broken trackers
Richard Jones <richard@users.sourceforge.net>
parents: 4362
diff changeset
2154 else:
fa5587802af9 Handle multiple @action values from broken trackers
Richard Jones <richard@users.sourceforge.net>
parents: 4362
diff changeset
2155 action = action.value.lower()
fa5587802af9 Handle multiple @action values from broken trackers
Richard Jones <richard@users.sourceforge.net>
parents: 4362
diff changeset
2156
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
2157 try:
2948
deda13909085 factor out get_action_class so it may be called from other places
Richard Jones <richard@users.sourceforge.net>
parents: 2947
diff changeset
2158 action_klass = self.get_action_class(action)
2019
8fab5d394f22 Call actions in a different way so we won't hide any bad TypeErrors.
Johannes Gijsbers <jlgijsbers@users.sourceforge.net>
parents: 2018
diff changeset
2159
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
2160 # call the mapped action
2019
8fab5d394f22 Call actions in a different way so we won't hide any bad TypeErrors.
Johannes Gijsbers <jlgijsbers@users.sourceforge.net>
parents: 2018
diff changeset
2161 if isinstance(action_klass, type('')):
8fab5d394f22 Call actions in a different way so we won't hide any bad TypeErrors.
Johannes Gijsbers <jlgijsbers@users.sourceforge.net>
parents: 2018
diff changeset
2162 # old way of specifying actions
2045
d124af927369 Forward-porting of fixes from the maintenance branch.
Richard Jones <richard@users.sourceforge.net>
parents: 2032
diff changeset
2163 return getattr(self, action_klass)()
2019
8fab5d394f22 Call actions in a different way so we won't hide any bad TypeErrors.
Johannes Gijsbers <jlgijsbers@users.sourceforge.net>
parents: 2018
diff changeset
2164 else:
2045
d124af927369 Forward-porting of fixes from the maintenance branch.
Richard Jones <richard@users.sourceforge.net>
parents: 2032
diff changeset
2165 return action_klass(self).execute()
5248
198b6e810c67 Use Python-3-compatible 'as' syntax for except statements
Eric S. Raymond <esr@thyrsus.com>
parents: 5231
diff changeset
2166 except (ValueError, Reject) as err:
5004
494d255043c9 Display errors containing HTML with RejectRaw (issue2550847)
John Kristensen <john@jerrykan.com>
parents: 4980
diff changeset
2167 escape = not isinstance(err, RejectRaw)
494d255043c9 Display errors containing HTML with RejectRaw (issue2550847)
John Kristensen <john@jerrykan.com>
parents: 4980
diff changeset
2168 self.add_error_message(str(err), escape=escape)
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
2169
2948
deda13909085 factor out get_action_class so it may be called from other places
Richard Jones <richard@users.sourceforge.net>
parents: 2947
diff changeset
2170 def get_action_class(self, action_name):
deda13909085 factor out get_action_class so it may be called from other places
Richard Jones <richard@users.sourceforge.net>
parents: 2947
diff changeset
2171 if (hasattr(self.instance, 'cgi_actions') and
4362
74476eaac38a more modernisation
Richard Jones <richard@users.sourceforge.net>
parents: 4344
diff changeset
2172 action_name in self.instance.cgi_actions):
2948
deda13909085 factor out get_action_class so it may be called from other places
Richard Jones <richard@users.sourceforge.net>
parents: 2947
diff changeset
2173 # tracker-defined action
deda13909085 factor out get_action_class so it may be called from other places
Richard Jones <richard@users.sourceforge.net>
parents: 2947
diff changeset
2174 action_klass = self.instance.cgi_actions[action_name]
deda13909085 factor out get_action_class so it may be called from other places
Richard Jones <richard@users.sourceforge.net>
parents: 2947
diff changeset
2175 else:
deda13909085 factor out get_action_class so it may be called from other places
Richard Jones <richard@users.sourceforge.net>
parents: 2947
diff changeset
2176 # go with a default
deda13909085 factor out get_action_class so it may be called from other places
Richard Jones <richard@users.sourceforge.net>
parents: 2947
diff changeset
2177 for name, action_klass in self.actions:
deda13909085 factor out get_action_class so it may be called from other places
Richard Jones <richard@users.sourceforge.net>
parents: 2947
diff changeset
2178 if name == action_name:
deda13909085 factor out get_action_class so it may be called from other places
Richard Jones <richard@users.sourceforge.net>
parents: 2947
diff changeset
2179 break
deda13909085 factor out get_action_class so it may be called from other places
Richard Jones <richard@users.sourceforge.net>
parents: 2947
diff changeset
2180 else:
5802
0e6d45413e88 catching last couple of cgi.escape references.
John Rouillard <rouilj@ieee.org>
parents: 5775
diff changeset
2181 raise ValueError('No such action "%s"'%html_escape(action_name))
2948
deda13909085 factor out get_action_class so it may be called from other places
Richard Jones <richard@users.sourceforge.net>
parents: 2947
diff changeset
2182 return action_klass
deda13909085 factor out get_action_class so it may be called from other places
Richard Jones <richard@users.sourceforge.net>
parents: 2947
diff changeset
2183
3760
b8f52d030f1a ignore common network errors, like "Connection reset by peer"
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3736
diff changeset
2184 def _socket_op(self, call, *args, **kwargs):
b8f52d030f1a ignore common network errors, like "Connection reset by peer"
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3736
diff changeset
2185 """Execute socket-related operation, catch common network errors
b8f52d030f1a ignore common network errors, like "Connection reset by peer"
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3736
diff changeset
2186
b8f52d030f1a ignore common network errors, like "Connection reset by peer"
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3736
diff changeset
2187 Parameters:
b8f52d030f1a ignore common network errors, like "Connection reset by peer"
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3736
diff changeset
2188 call: a callable to execute
b8f52d030f1a ignore common network errors, like "Connection reset by peer"
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3736
diff changeset
2189 args, kwargs: call arguments
b8f52d030f1a ignore common network errors, like "Connection reset by peer"
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3736
diff changeset
2190
b8f52d030f1a ignore common network errors, like "Connection reset by peer"
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3736
diff changeset
2191 """
b8f52d030f1a ignore common network errors, like "Connection reset by peer"
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3736
diff changeset
2192 try:
b8f52d030f1a ignore common network errors, like "Connection reset by peer"
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3736
diff changeset
2193 call(*args, **kwargs)
5248
198b6e810c67 Use Python-3-compatible 'as' syntax for except statements
Eric S. Raymond <esr@thyrsus.com>
parents: 5231
diff changeset
2194 except socket.error as err:
3807
c27aafab067d Band-aid over handling of netework errors.
Ralf Schlatterbeck <schlatterbeck@users.sourceforge.net>
parents: 3800
diff changeset
2195 err_errno = getattr (err, 'errno', None)
3808
36eb9e8faf30 Real handling of network errors.
Ralf Schlatterbeck <schlatterbeck@users.sourceforge.net>
parents: 3807
diff changeset
2196 if err_errno is None:
36eb9e8faf30 Real handling of network errors.
Ralf Schlatterbeck <schlatterbeck@users.sourceforge.net>
parents: 3807
diff changeset
2197 try:
36eb9e8faf30 Real handling of network errors.
Ralf Schlatterbeck <schlatterbeck@users.sourceforge.net>
parents: 3807
diff changeset
2198 err_errno = err[0]
36eb9e8faf30 Real handling of network errors.
Ralf Schlatterbeck <schlatterbeck@users.sourceforge.net>
parents: 3807
diff changeset
2199 except TypeError:
36eb9e8faf30 Real handling of network errors.
Ralf Schlatterbeck <schlatterbeck@users.sourceforge.net>
parents: 3807
diff changeset
2200 pass
3807
c27aafab067d Band-aid over handling of netework errors.
Ralf Schlatterbeck <schlatterbeck@users.sourceforge.net>
parents: 3800
diff changeset
2201 if err_errno not in self.IGNORE_NET_ERRORS:
3760
b8f52d030f1a ignore common network errors, like "Connection reset by peer"
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3736
diff changeset
2202 raise
4064
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2203 except IOError:
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2204 # Apache's mod_python will raise IOError -- without an
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2205 # accompanying errno -- when a write to the client fails.
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2206 # A common case is that the client has closed the
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2207 # connection. There's no way to be certain that this is
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2208 # the situation that has occurred here, but that is the
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2209 # most likely case.
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2210 pass
3760
b8f52d030f1a ignore common network errors, like "Connection reset by peer"
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3736
diff changeset
2211
6458
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2212 def determine_content_encoding(self, list_all=False, precompressed=False):
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2213
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2214 encoding_list = []
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2215
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2216 # FIXME: Should parse for q= values and properly order
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2217 # the request encodings. Also should handle identity coding.
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2218 # Then return first acceptable by q value.
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2219 # This code always uses order: zstd, br, gzip. It will send identity
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2220 # even if identity excluded rather than returning 406.
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2221 accept_encoding = self.request.headers.get('accept-encoding') or []
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2222
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2223 if accept_encoding:
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2224 for enc in ['zstd', 'br', 'gzip']:
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2225 if ((enc in self.compressors) or precompressed) and \
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2226 (enc in accept_encoding):
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2227 if not list_all:
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2228 return enc
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2229 else:
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2230 encoding_list.append(enc)
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2231
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2232 # Return value must evaluate to false in boolean context if no
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2233 # acceptable encoding is found. If an (non-identity) encoding
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2234 # is found the Vary header will include accept-encoding.
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2235 # What to return if the identity encoding is unacceptable?
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2236 # Maybe raise a 406 from here?
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2237 if not list_all:
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2238 return None
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2239 else:
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2240 return encoding_list
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2241
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2242 def setVary(self, header):
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2243 '''Vary header will include the new header. This will append
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2244 if Vary exists.'''
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2245
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2246 if ('Vary' in self.additional_headers):
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2247 self.additional_headers['Vary'] += ", %s"%header
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2248 else:
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2249 self.additional_headers['Vary'] = header
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2250
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2251 def compress_encode(self, byte_content, quality=4):
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2252
6467
679ec82798e9 Fix typo referencing config.
John Rouillard <rouilj@ieee.org>
parents: 6458
diff changeset
2253 if not self.instance.config.WEB_DYNAMIC_COMPRESSION:
6458
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2254 # dynamic compression disabled.
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2255 return byte_content
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2256
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2257 # don't compress small content
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2258 if len(byte_content) < 100:
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2259 return byte_content
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2260
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2261 # abort if already encoded (e.g. served from
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2262 # precompressed file or cache on disk)
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2263 if ('Content-Encoding' in self.additional_headers):
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2264 return byte_content
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2265
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2266 # abort if file-type already compressed
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2267 if ('Content-Type' in self.additional_headers) and \
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2268 (self.additional_headers['Content-Type'] in \
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2269 self.precompressed_mime_types):
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2270 return byte_content
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2271
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2272 encoder = None
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2273 # return same content if unable to compress
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2274 new_content = byte_content
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2275
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2276
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2277 encoder = self.determine_content_encoding()
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2278
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2279 if encoder == 'zstd':
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2280 new_content = self.zstd.ZSTD_compress(byte_content, 3)
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2281 elif encoder == 'br':
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2282 # lgblock=0 sets value from quality
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2283 new_content = self.brotli.compress(byte_content,
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2284 quality=quality,
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2285 mode=1,
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2286 lgblock=0)
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2287 elif encoder == 'gzip':
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2288 try:
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2289 new_content = self.gzip.compress(byte_content, compresslevel=5)
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2290 except AttributeError:
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2291 try:
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2292 from StringIO import cStringIO as IOBuff
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2293 except ImportError:
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2294 # python 3
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2295 # however this code should not be needed under python3
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2296 # since py3 gzip library has compress() method.
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2297 from io import BytesIO as IOBuff
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2298
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2299 out = IOBuff()
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2300 # handle under python2
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2301 f = self.gzip.GzipFile(fileobj=out, mode='w', compresslevel=5)
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2302 f.write(byte_content)
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2303 f.close()
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2304 new_content = out.getvalue()
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2305
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2306 if encoder:
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2307 # we changed the data, change existing content-length header
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2308 # and add Content-Encoding and Vary header.
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2309 self.additional_headers['Content-Length'] = str(len(new_content))
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2310 self.additional_headers['Content-Encoding'] = encoder
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2311 self.setVary('Accept-Encoding')
6539
f8df7fed18f6 issue2551175 - Make ETag content-encoding aware.
John Rouillard <rouilj@ieee.org>
parents: 6509
diff changeset
2312 try:
f8df7fed18f6 issue2551175 - Make ETag content-encoding aware.
John Rouillard <rouilj@ieee.org>
parents: 6509
diff changeset
2313 current_etag = self.additional_headers['ETag']
f8df7fed18f6 issue2551175 - Make ETag content-encoding aware.
John Rouillard <rouilj@ieee.org>
parents: 6509
diff changeset
2314 except KeyError:
f8df7fed18f6 issue2551175 - Make ETag content-encoding aware.
John Rouillard <rouilj@ieee.org>
parents: 6509
diff changeset
2315 pass # etag not set for non-rest endpoints
f8df7fed18f6 issue2551175 - Make ETag content-encoding aware.
John Rouillard <rouilj@ieee.org>
parents: 6509
diff changeset
2316 else:
f8df7fed18f6 issue2551175 - Make ETag content-encoding aware.
John Rouillard <rouilj@ieee.org>
parents: 6509
diff changeset
2317 etag_end = current_etag.rindex('"')
f8df7fed18f6 issue2551175 - Make ETag content-encoding aware.
John Rouillard <rouilj@ieee.org>
parents: 6509
diff changeset
2318 self.additional_headers['ETag'] = ( current_etag[:etag_end] +
f8df7fed18f6 issue2551175 - Make ETag content-encoding aware.
John Rouillard <rouilj@ieee.org>
parents: 6509
diff changeset
2319 '-' + encoder + current_etag[etag_end:])
6458
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2320
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2321 return new_content
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2322
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
2323 def write(self, content):
6458
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2324 if not self.headers_done and self.env['REQUEST_METHOD'] != 'HEAD':
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2325 # compress_encode modifies headers, must run before self.header()
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2326 content = self.compress_encode(bs2b(content))
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2327
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
2328 if not self.headers_done:
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
2329 self.header()
2592
5a8d9465827e implement the HTTP HEAD command [SF#992544]
Richard Jones <richard@users.sourceforge.net>
parents: 2565
diff changeset
2330 if self.env['REQUEST_METHOD'] != 'HEAD':
3760
b8f52d030f1a ignore common network errors, like "Connection reset by peer"
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3736
diff changeset
2331 self._socket_op(self.request.wfile.write, content)
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
2332
2279
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
2333 def write_html(self, content):
6458
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2334 if sys.version_info[0] > 2:
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2335 # An action setting appropriate headers for a non-HTML
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2336 # response may return a bytes object directly.
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2337 if not isinstance(content, bytes):
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2338 content = content.encode(self.charset, 'xmlcharrefreplace')
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2339 elif self.charset != self.STORAGE_CHARSET:
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2340 # recode output
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2341 content = content.decode(self.STORAGE_CHARSET, 'replace')
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2342 content = content.encode(self.charset, 'xmlcharrefreplace')
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2343
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2344 if self.env['REQUEST_METHOD'] != 'HEAD' and not self.headers_done:
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2345 # compress_encode modifies headers, must run before self.header()
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2346 content = self.compress_encode(bs2b(content))
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2347
2279
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
2348 if not self.headers_done:
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
2349 # at this point, we are sure about Content-Type
4362
74476eaac38a more modernisation
Richard Jones <richard@users.sourceforge.net>
parents: 4344
diff changeset
2350 if 'Content-Type' not in self.additional_headers:
3867
2563ddf71cd7 Enabled over-riding of content-type in web interface (thanks John Mitchell)
Richard Jones <richard@users.sourceforge.net>
parents: 3808
diff changeset
2351 self.additional_headers['Content-Type'] = \
2563ddf71cd7 Enabled over-riding of content-type in web interface (thanks John Mitchell)
Richard Jones <richard@users.sourceforge.net>
parents: 3808
diff changeset
2352 'text/html; charset=%s' % self.charset
6509
1fc765ef6379 Fix 204 responses, hangs and crashes with REST.
John Rouillard <rouilj@ieee.org>
parents: 6504
diff changeset
2353 if 'Content-Length' not in self.additional_headers:
6550
15ae655c2014 header values should always be strings (at least "flup" cares)
Christof Meerwald <cmeerw@cmeerw.org>
parents: 6548
diff changeset
2354 self.additional_headers['Content-Length'] = str(len(content))
2279
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
2355 self.header()
2592
5a8d9465827e implement the HTTP HEAD command [SF#992544]
Richard Jones <richard@users.sourceforge.net>
parents: 2565
diff changeset
2356
5a8d9465827e implement the HTTP HEAD command [SF#992544]
Richard Jones <richard@users.sourceforge.net>
parents: 2565
diff changeset
2357 if self.env['REQUEST_METHOD'] == 'HEAD':
5a8d9465827e implement the HTTP HEAD command [SF#992544]
Richard Jones <richard@users.sourceforge.net>
parents: 2565
diff changeset
2358 # client doesn't care about content
5a8d9465827e implement the HTTP HEAD command [SF#992544]
Richard Jones <richard@users.sourceforge.net>
parents: 2565
diff changeset
2359 return
5a8d9465827e implement the HTTP HEAD command [SF#992544]
Richard Jones <richard@users.sourceforge.net>
parents: 2565
diff changeset
2360
5a8d9465827e implement the HTTP HEAD command [SF#992544]
Richard Jones <richard@users.sourceforge.net>
parents: 2565
diff changeset
2361 # and write
3760
b8f52d030f1a ignore common network errors, like "Connection reset by peer"
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3736
diff changeset
2362 self._socket_op(self.request.wfile.write, content)
2279
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
2363
4064
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2364 def http_strip(self, content):
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2365 """Remove HTTP Linear White Space from 'content'.
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2366
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2367 'content' -- A string.
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2368
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2369 returns -- 'content', with all leading and trailing LWS
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2370 removed."""
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2371
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2372 # RFC 2616 2.2: Basic Rules
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2373 #
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2374 # LWS = [CRLF] 1*( SP | HT )
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2375 return content.strip(" \r\n\t")
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2376
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2377 def http_split(self, content):
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2378 """Split an HTTP list.
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2379
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2380 'content' -- A string, giving a list of items.
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2381
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2382 returns -- A sequence of strings, containing the elements of
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2383 the list."""
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2384
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2385 # RFC 2616 2.1: Augmented BNF
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2386 #
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2387 # Grammar productions of the form "#rule" indicate a
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2388 # comma-separated list of elements matching "rule". LWS
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2389 # is then removed from each element, and empty elements
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2390 # removed.
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2391
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2392 # Split at commas.
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2393 elements = content.split(",")
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2394 # Remove linear whitespace at either end of the string.
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2395 elements = [self.http_strip(e) for e in elements]
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2396 # Remove any now-empty elements.
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2397 return [e for e in elements if e]
4648
e645820e8556 Clean up whitespace in client.py
Ezio Melotti <ezio.melotti@gmail.com>
parents: 4640
diff changeset
2398
4064
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2399 def handle_range_header(self, length, etag):
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2400 """Handle the 'Range' and 'If-Range' headers.
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2401
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2402 'length' -- the length of the content available for the
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2403 resource.
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2404
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2405 'etag' -- the entity tag for this resources.
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2406
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2407 returns -- If the request headers (including 'Range' and
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2408 'If-Range') indicate that only a portion of the entity should
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2409 be returned, then the return value is a pair '(offfset,
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2410 length)' indicating the first byte and number of bytes of the
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2411 content that should be returned to the client. In addition,
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2412 this method will set 'self.response_code' to indicate Partial
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2413 Content. In all other cases, the return value is 'None'. If
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2414 appropriate, 'self.response_code' will be
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2415 set to indicate 'REQUESTED_RANGE_NOT_SATISFIABLE'. In that
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2416 case, the caller should not send any data to the client."""
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2417
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2418 # RFC 2616 14.35: Range
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2419 #
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2420 # See if the Range header is present.
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2421 ranges_specifier = self.env.get("HTTP_RANGE")
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2422 if ranges_specifier is None:
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2423 return None
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2424 # RFC 2616 14.27: If-Range
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2425 #
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2426 # Check to see if there is an If-Range header.
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2427 # Because the specification says:
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2428 #
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2429 # The If-Range header ... MUST be ignored if the request
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2430 # does not include a Range header, we check for If-Range
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2431 # after checking for Range.
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2432 if_range = self.env.get("HTTP_IF_RANGE")
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2433 if if_range:
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2434 # The grammar for the If-Range header is:
4648
e645820e8556 Clean up whitespace in client.py
Ezio Melotti <ezio.melotti@gmail.com>
parents: 4640
diff changeset
2435 #
4064
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2436 # If-Range = "If-Range" ":" ( entity-tag | HTTP-date )
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2437 # entity-tag = [ weak ] opaque-tag
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2438 # weak = "W/"
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2439 # opaque-tag = quoted-string
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2440 #
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2441 # We only support strong entity tags.
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2442 if_range = self.http_strip(if_range)
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2443 if (not if_range.startswith('"')
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2444 or not if_range.endswith('"')):
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2445 return None
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2446 # If the condition doesn't match the entity tag, then we
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2447 # must send the client the entire file.
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2448 if if_range != etag:
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2449 return
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2450 # The grammar for the Range header value is:
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2451 #
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2452 # ranges-specifier = byte-ranges-specifier
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2453 # byte-ranges-specifier = bytes-unit "=" byte-range-set
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2454 # byte-range-set = 1#( byte-range-spec | suffix-byte-range-spec )
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2455 # byte-range-spec = first-byte-pos "-" [last-byte-pos]
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2456 # first-byte-pos = 1*DIGIT
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2457 # last-byte-pos = 1*DIGIT
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2458 # suffix-byte-range-spec = "-" suffix-length
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2459 # suffix-length = 1*DIGIT
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2460 #
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2461 # Look for the "=" separating the units from the range set.
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2462 specs = ranges_specifier.split("=", 1)
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2463 if len(specs) != 2:
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2464 return None
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2465 # Check that the bytes-unit is in fact "bytes". If it is not,
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2466 # we do not know how to process this range.
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2467 bytes_unit = self.http_strip(specs[0])
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2468 if bytes_unit != "bytes":
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2469 return None
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2470 # Seperate the range-set into range-specs.
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2471 byte_range_set = self.http_strip(specs[1])
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2472 byte_range_specs = self.http_split(byte_range_set)
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2473 # We only handle exactly one range at this time.
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2474 if len(byte_range_specs) != 1:
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2475 return None
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2476 # Parse the spec.
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2477 byte_range_spec = byte_range_specs[0]
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2478 pos = byte_range_spec.split("-", 1)
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2479 if len(pos) != 2:
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2480 return None
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2481 # Get the first and last bytes.
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2482 first = self.http_strip(pos[0])
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2483 last = self.http_strip(pos[1])
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2484 # We do not handle suffix ranges.
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2485 if not first:
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2486 return None
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2487 # Convert the first and last positions to integers.
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2488 try:
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2489 first = int(first)
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2490 if last:
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2491 last = int(last)
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2492 else:
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2493 last = length - 1
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2494 except:
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2495 # The positions could not be parsed as integers.
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2496 return None
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2497 # Check that the range makes sense.
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2498 if (first < 0 or last < 0 or last < first):
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2499 return None
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2500 if last >= length:
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2501 # RFC 2616 10.4.17: 416 Requested Range Not Satisfiable
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2502 #
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2503 # If there is an If-Range header, RFC 2616 says that we
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2504 # should just ignore the invalid Range header.
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2505 if if_range:
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2506 return None
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2507 # Return code 416 with a Content-Range header giving the
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2508 # allowable range.
4362
74476eaac38a more modernisation
Richard Jones <richard@users.sourceforge.net>
parents: 4344
diff changeset
2509 self.response_code = http_.client.REQUESTED_RANGE_NOT_SATISFIABLE
4064
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2510 self.setHeader("Content-Range", "bytes */%d" % length)
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2511 return None
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2512 # RFC 2616 10.2.7: 206 Partial Content
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2513 #
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2514 # Tell the client that we are honoring the Range request by
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2515 # indicating that we are providing partial content.
4362
74476eaac38a more modernisation
Richard Jones <richard@users.sourceforge.net>
parents: 4344
diff changeset
2516 self.response_code = http_.client.PARTIAL_CONTENT
4064
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2517 # RFC 2616 14.16: Content-Range
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2518 #
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2519 # Tell the client what data we are providing.
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2520 #
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2521 # content-range-spec = byte-content-range-spec
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2522 # byte-content-range-spec = bytes-unit SP
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2523 # byte-range-resp-spec "/"
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2524 # ( instance-length | "*" )
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2525 # byte-range-resp-spec = (first-byte-pos "-" last-byte-pos)
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2526 # | "*"
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2527 # instance-length = 1 * DIGIT
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2528 self.setHeader("Content-Range",
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2529 "bytes %d-%d/%d" % (first, last, length))
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2530 return (first, last - first + 1)
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2531
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2532 def write_file(self, filename):
6458
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2533 """Send the contents of 'filename' to the user.
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2534 Send an acceptable pre-compressed version of the
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2535 file if it is newer than the uncompressed version.
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2536 """
4064
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2537
6458
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2538 # Assume we will return the entire file.
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2539 offset = 0
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2540
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2541 # initalize length from uncompressed file
4064
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2542 stat_info = os.stat(filename)
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2543 length = stat_info[stat.ST_SIZE]
6458
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2544
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2545 # Determine if we are sending a range. If so, compress
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2546 # on the fly. Otherwise see if we have a suitable
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2547 # pre-compressed/encoded file we can send.
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2548 if not self.env.get("HTTP_RANGE"):
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2549 # no range, search for file in list ordered
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2550 # from best to worst alternative
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2551 encoding_list = self.determine_content_encoding(list_all=True,
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2552 precompressed=True)
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2553 if encoding_list and self.db.config.WEB_USE_PRECOMPRESSED_FILES:
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2554 # do we need to search through list? If best is not
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2555 # precompressed, on the fly compress with best?
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2556 # by searching list we will respond with precompressed
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2557 # 2nd best or worse.
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2558 for encoder in encoding_list:
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2559 try:
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2560 trial_filename = '%s.%s'%(filename,encoder)
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2561 trial_stat_info = os.stat(trial_filename)
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2562 if stat_info[stat.ST_MTIME] > \
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2563 trial_stat_info[stat.ST_MTIME]:
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2564 # compressed file is obsolete
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2565 # don't use it
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2566 logger.warning(self._("Cache failure: "
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2567 "compressed file %(compressed)s is "
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2568 "older than its source file "
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2569 "%(filename)s"%{'filename': filename,
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2570 'compressed': trial_filename}))
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2571
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2572 continue
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2573 filename = trial_filename
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2574 length = trial_stat_info[stat.ST_SIZE]
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2575 self.setHeader('Content-Encoding', encoder)
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2576 self.setVary('Accept-Encoding')
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2577 break
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2578 # except FileNotFoundError: py2/py3
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2579 # compatible version
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2580 except EnvironmentError as e:
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2581 if e.errno != errno.ENOENT:
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2582 raise
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2583
4648
e645820e8556 Clean up whitespace in client.py
Ezio Melotti <ezio.melotti@gmail.com>
parents: 4640
diff changeset
2584 # If the headers have not already been finalized,
4064
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2585 if not self.headers_done:
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2586 # RFC 2616 14.19: ETag
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2587 #
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2588 # Compute the entity tag, in a format similar to that
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2589 # used by Apache.
6458
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2590 #
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2591 # Tag does *not* change with Content-Encoding.
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2592 # Header 'Vary: Accept-Encoding' is returned with response.
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2593 # RFC2616 section 13.32 discusses etag and references
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2594 # section 14.44 (Vary header) as being applicable to etag.
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2595 # Hence the intermediate proxy should/must match
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2596 # Accept-Encoding and ETag to determine whether to return
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2597 # a 304 or report cache miss and fetch from origin server.
4064
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2598 etag = '"%x-%x-%x"' % (stat_info[stat.ST_INO],
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2599 length,
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2600 stat_info[stat.ST_MTIME])
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2601 self.setHeader("ETag", etag)
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2602 # RFC 2616 14.5: Accept-Ranges
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2603 #
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2604 # Let the client know that we will accept range requests.
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2605 self.setHeader("Accept-Ranges", "bytes")
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2606 # RFC 2616 14.35: Range
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2607 #
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2608 # If there is a Range header, we may be able to avoid
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2609 # sending the entire file.
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2610 content_range = self.handle_range_header(length, etag)
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2611 if content_range:
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2612 offset, length = content_range
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2613 # RFC 2616 14.13: Content-Length
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2614 #
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2615 # Tell the client how much data we are providing.
4145
c15fcee3d8a1 Fix issue2550552.
Stefan Seefeld <stefan@seefeld.name>
parents: 4114
diff changeset
2616 self.setHeader("Content-Length", str(length))
4064
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2617 # If the client doesn't actually want the body, or if we are
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2618 # indicating an invalid range.
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2619 if (self.env['REQUEST_METHOD'] == 'HEAD'
4362
74476eaac38a more modernisation
Richard Jones <richard@users.sourceforge.net>
parents: 4344
diff changeset
2620 or self.response_code == http_.client.REQUESTED_RANGE_NOT_SATISFIABLE):
6656
b83b90d57846 Fix header value. needs to be string not integer.
John Rouillard <rouilj@ieee.org>
parents: 6649
diff changeset
2621 self.setHeader("Content-Length", "0")
6649
33616bc80baf Fix hang in unsatisfyable range or HEAD request for static file
John Rouillard <rouilj@ieee.org>
parents: 6588
diff changeset
2622 self.header()
4064
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2623 return
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2624 # Use the optimized "sendfile" operation, if possible.
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2625 if hasattr(self.request, "sendfile"):
6458
8f1b91756457 issue2551147 - Enable compression of http responses in roundup.
John Rouillard <rouilj@ieee.org>
parents: 6447
diff changeset
2626 self.header()
4064
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2627 self._socket_op(self.request.sendfile, filename, offset, length)
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2628 return
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2629 # Fallback to the "write" operation.
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2630 f = open(filename, 'rb')
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2631 try:
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2632 if offset:
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2633 f.seek(offset)
4077
7d19ed05baa6 Fix issue2550517
Stefan Seefeld <stefan@seefeld.name>
parents: 4065
diff changeset
2634 content = f.read(length)
4064
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2635 finally:
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2636 f.close()
662cd78df973 Add support for resuming (file) downloads.
Stefan Seefeld <stefan@seefeld.name>
parents: 4047
diff changeset
2637 self.write(content)
4047
e70643990e9c Support the use of sendfile() for file transfer, if available.
Stefan Seefeld <stefan@seefeld.name>
parents: 4046
diff changeset
2638
2046
f913b6beac35 document and make easier the actions-returning-content idiom
Richard Jones <richard@users.sourceforge.net>
parents: 2045
diff changeset
2639 def setHeader(self, header, value):
6544
9aa8df0b4426 issue2551178 - fix Traceback in Apache WSGI
John Rouillard <rouilj@ieee.org>
parents: 6539
diff changeset
2640 """Override or delete a header to be returned to the user's browser.
4065
1e28d58c6d1c Uniformly use """...""" instead of '''...''' for comments.
Stefan Seefeld <stefan@seefeld.name>
parents: 4064
diff changeset
2641 """
6544
9aa8df0b4426 issue2551178 - fix Traceback in Apache WSGI
John Rouillard <rouilj@ieee.org>
parents: 6539
diff changeset
2642 if value is None:
9aa8df0b4426 issue2551178 - fix Traceback in Apache WSGI
John Rouillard <rouilj@ieee.org>
parents: 6539
diff changeset
2643 try:
9aa8df0b4426 issue2551178 - fix Traceback in Apache WSGI
John Rouillard <rouilj@ieee.org>
parents: 6539
diff changeset
2644 del(self.additional_headers[header])
9aa8df0b4426 issue2551178 - fix Traceback in Apache WSGI
John Rouillard <rouilj@ieee.org>
parents: 6539
diff changeset
2645 except KeyError:
9aa8df0b4426 issue2551178 - fix Traceback in Apache WSGI
John Rouillard <rouilj@ieee.org>
parents: 6539
diff changeset
2646 pass
9aa8df0b4426 issue2551178 - fix Traceback in Apache WSGI
John Rouillard <rouilj@ieee.org>
parents: 6539
diff changeset
2647 else:
9aa8df0b4426 issue2551178 - fix Traceback in Apache WSGI
John Rouillard <rouilj@ieee.org>
parents: 6539
diff changeset
2648 self.additional_headers[header] = value
2046
f913b6beac35 document and make easier the actions-returning-content idiom
Richard Jones <richard@users.sourceforge.net>
parents: 2045
diff changeset
2649
1120
c26471971d18 Exposed the Batch mechanism through the top-level "utils" variable.
Richard Jones <richard@users.sourceforge.net>
parents: 1103
diff changeset
2650 def header(self, headers=None, response=None):
4065
1e28d58c6d1c Uniformly use """...""" instead of '''...''' for comments.
Stefan Seefeld <stefan@seefeld.name>
parents: 4064
diff changeset
2651 """Put up the appropriate header.
1e28d58c6d1c Uniformly use """...""" instead of '''...''' for comments.
Stefan Seefeld <stefan@seefeld.name>
parents: 4064
diff changeset
2652 """
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
2653 if headers is None:
2279
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
2654 headers = {'Content-Type':'text/html; charset=utf-8'}
1120
c26471971d18 Exposed the Batch mechanism through the top-level "utils" variable.
Richard Jones <richard@users.sourceforge.net>
parents: 1103
diff changeset
2655 if response is None:
c26471971d18 Exposed the Batch mechanism through the top-level "utils" variable.
Richard Jones <richard@users.sourceforge.net>
parents: 1103
diff changeset
2656 response = self.response_code
1130
89bd02ffe4af tell clients/caches not to cache our dynamic bits
Richard Jones <richard@users.sourceforge.net>
parents: 1129
diff changeset
2657
89bd02ffe4af tell clients/caches not to cache our dynamic bits
Richard Jones <richard@users.sourceforge.net>
parents: 1129
diff changeset
2658 # update with additional info
1120
c26471971d18 Exposed the Batch mechanism through the top-level "utils" variable.
Richard Jones <richard@users.sourceforge.net>
parents: 1103
diff changeset
2659 headers.update(self.additional_headers)
1130
89bd02ffe4af tell clients/caches not to cache our dynamic bits
Richard Jones <richard@users.sourceforge.net>
parents: 1129
diff changeset
2660
2279
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
2661 if headers.get('Content-Type', 'text/html') == 'text/html':
297e46e22e04 implemented HTTP charset negotiation.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2248
diff changeset
2662 headers['Content-Type'] = 'text/html; charset=utf-8'
3736
a2d22d0de0bc WSGI support via roundup.cgi.wsgi_handler
Richard Jones <richard@users.sourceforge.net>
parents: 3687
diff changeset
2663
6548
de5f5f9c02f2 Fix spurious content-ty on 304; xfail css Cache-Control
John Rouillard <rouilj@ieee.org>
parents: 6546
diff changeset
2664 if response in [ 204, 304]: # has no body so no content-type
6509
1fc765ef6379 Fix 204 responses, hangs and crashes with REST.
John Rouillard <rouilj@ieee.org>
parents: 6504
diff changeset
2665 del(headers['Content-Type'])
1fc765ef6379 Fix 204 responses, hangs and crashes with REST.
John Rouillard <rouilj@ieee.org>
parents: 6504
diff changeset
2666
4362
74476eaac38a more modernisation
Richard Jones <richard@users.sourceforge.net>
parents: 4344
diff changeset
2667 headers = list(headers.items())
3736
a2d22d0de0bc WSGI support via roundup.cgi.wsgi_handler
Richard Jones <richard@users.sourceforge.net>
parents: 3687
diff changeset
2668
5395
23b8e6067f7c Python 3 preparation: update calls to dict methods.
Joseph Myers <jsm@polyomino.org.uk>
parents: 5378
diff changeset
2669 for ((path, name), (value, expire)) in self._cookies.items():
3548
61d48244e7a8 login may now be for a single session
Richard Jones <richard@users.sourceforge.net>
parents: 3494
diff changeset
2670 cookie = "%s=%s; Path=%s;"%(name, value, path)
61d48244e7a8 login may now be for a single session
Richard Jones <richard@users.sourceforge.net>
parents: 3494
diff changeset
2671 if expire is not None:
4362
74476eaac38a more modernisation
Richard Jones <richard@users.sourceforge.net>
parents: 4344
diff changeset
2672 cookie += " expires=%s;"%get_cookie_date(expire)
4586
b21bb66de6ff Mark cookies HttpOnly and -- if https is used -- secure.
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4578
diff changeset
2673 # mark as secure if https, see issue2550689
b21bb66de6ff Mark cookies HttpOnly and -- if https is used -- secure.
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4578
diff changeset
2674 if self.secure:
b21bb66de6ff Mark cookies HttpOnly and -- if https is used -- secure.
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4578
diff changeset
2675 cookie += " secure;"
5212
d4cc71beb102 Added support for SameSite cookie option for CSRF prevention
John Rouillard <rouilj@ieee.org>
parents: 5211
diff changeset
2676 ssc = self.db.config['WEB_SAMESITE_COOKIE_SETTING']
d4cc71beb102 Added support for SameSite cookie option for CSRF prevention
John Rouillard <rouilj@ieee.org>
parents: 5211
diff changeset
2677 if ssc != "None":
d4cc71beb102 Added support for SameSite cookie option for CSRF prevention
John Rouillard <rouilj@ieee.org>
parents: 5211
diff changeset
2678 cookie += " SameSite=%s;"%ssc
4586
b21bb66de6ff Mark cookies HttpOnly and -- if https is used -- secure.
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4578
diff changeset
2679 # prevent theft of session cookie, see issue2550689
b21bb66de6ff Mark cookies HttpOnly and -- if https is used -- secure.
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4578
diff changeset
2680 cookie += " HttpOnly;"
3736
a2d22d0de0bc WSGI support via roundup.cgi.wsgi_handler
Richard Jones <richard@users.sourceforge.net>
parents: 3687
diff changeset
2681 headers.append(('Set-Cookie', cookie))
a2d22d0de0bc WSGI support via roundup.cgi.wsgi_handler
Richard Jones <richard@users.sourceforge.net>
parents: 3687
diff changeset
2682
3760
b8f52d030f1a ignore common network errors, like "Connection reset by peer"
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 3736
diff changeset
2683 self._socket_op(self.request.start_response, headers, response)
3736
a2d22d0de0bc WSGI support via roundup.cgi.wsgi_handler
Richard Jones <richard@users.sourceforge.net>
parents: 3687
diff changeset
2684
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
2685 self.headers_done = 1
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
2686 if self.debug:
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
2687 self.headers_sent = headers
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
2688
2946
661028d24cd2 support for multiple cookie headers in single http response;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2942
diff changeset
2689 def add_cookie(self, name, value, expire=86400*365, path=None):
661028d24cd2 support for multiple cookie headers in single http response;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2942
diff changeset
2690 """Set a cookie value to be sent in HTTP headers
661028d24cd2 support for multiple cookie headers in single http response;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2942
diff changeset
2691
661028d24cd2 support for multiple cookie headers in single http response;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2942
diff changeset
2692 Parameters:
661028d24cd2 support for multiple cookie headers in single http response;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2942
diff changeset
2693 name:
661028d24cd2 support for multiple cookie headers in single http response;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2942
diff changeset
2694 cookie name
661028d24cd2 support for multiple cookie headers in single http response;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2942
diff changeset
2695 value:
661028d24cd2 support for multiple cookie headers in single http response;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2942
diff changeset
2696 cookie value
661028d24cd2 support for multiple cookie headers in single http response;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2942
diff changeset
2697 expire:
661028d24cd2 support for multiple cookie headers in single http response;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2942
diff changeset
2698 cookie expiration time (seconds).
661028d24cd2 support for multiple cookie headers in single http response;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2942
diff changeset
2699 If value is empty (meaning "delete cookie"),
661028d24cd2 support for multiple cookie headers in single http response;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2942
diff changeset
2700 expiration time is forced in the past
661028d24cd2 support for multiple cookie headers in single http response;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2942
diff changeset
2701 and this argument is ignored.
3548
61d48244e7a8 login may now be for a single session
Richard Jones <richard@users.sourceforge.net>
parents: 3494
diff changeset
2702 If None, the cookie will expire at end-of-session.
2946
661028d24cd2 support for multiple cookie headers in single http response;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2942
diff changeset
2703 If omitted, the cookie will be kept for a year.
661028d24cd2 support for multiple cookie headers in single http response;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2942
diff changeset
2704 path:
661028d24cd2 support for multiple cookie headers in single http response;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2942
diff changeset
2705 cookie path (optional)
661028d24cd2 support for multiple cookie headers in single http response;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2942
diff changeset
2706
661028d24cd2 support for multiple cookie headers in single http response;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2942
diff changeset
2707 """
661028d24cd2 support for multiple cookie headers in single http response;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2942
diff changeset
2708 if path is None:
661028d24cd2 support for multiple cookie headers in single http response;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2942
diff changeset
2709 path = self.cookie_path
661028d24cd2 support for multiple cookie headers in single http response;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2942
diff changeset
2710 if not value:
661028d24cd2 support for multiple cookie headers in single http response;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2942
diff changeset
2711 expire = -1
3989
0112e9e1d068 improvements to session management
Richard Jones <richard@users.sourceforge.net>
parents: 3916
diff changeset
2712 self._cookies[(path, name)] = (value, expire)
2946
661028d24cd2 support for multiple cookie headers in single http response;
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2942
diff changeset
2713
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
2714 def make_user_anonymous(self):
4065
1e28d58c6d1c Uniformly use """...""" instead of '''...''' for comments.
Stefan Seefeld <stefan@seefeld.name>
parents: 4064
diff changeset
2715 """ Make us anonymous
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
2716
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
2717 This method used to handle non-existence of the 'anonymous'
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
2718 user, but that user is mandatory now.
4065
1e28d58c6d1c Uniformly use """...""" instead of '''...''' for comments.
Stefan Seefeld <stefan@seefeld.name>
parents: 4064
diff changeset
2719 """
985
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
2720 self.userid = self.db.user.lookup('anonymous')
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
2721 self.user = 'anonymous'
55ab0c5b49f9 New CGI interface support
Richard Jones <richard@users.sourceforge.net>
parents:
diff changeset
2722
1801
9f9d35f3d8f7 Change the message asking for confirmation of registration...
Johannes Gijsbers <jlgijsbers@users.sourceforge.net>
parents: 1799
diff changeset
2723 def standard_message(self, to, subject, body, author=None):
4065
1e28d58c6d1c Uniformly use """...""" instead of '''...''' for comments.
Stefan Seefeld <stefan@seefeld.name>
parents: 4064
diff changeset
2724 """Send a standard email message from Roundup.
2248
cd7e6d6288c6 fixed rego from email address [SF#947414]
Richard Jones <richard@users.sourceforge.net>
parents: 2246
diff changeset
2725
cd7e6d6288c6 fixed rego from email address [SF#947414]
Richard Jones <richard@users.sourceforge.net>
parents: 2246
diff changeset
2726 "to" - recipients list
cd7e6d6288c6 fixed rego from email address [SF#947414]
Richard Jones <richard@users.sourceforge.net>
parents: 2246
diff changeset
2727 "subject" - Subject
cd7e6d6288c6 fixed rego from email address [SF#947414]
Richard Jones <richard@users.sourceforge.net>
parents: 2246
diff changeset
2728 "body" - Message
cd7e6d6288c6 fixed rego from email address [SF#947414]
Richard Jones <richard@users.sourceforge.net>
parents: 2246
diff changeset
2729 "author" - (name, address) tuple or None for admin email
cd7e6d6288c6 fixed rego from email address [SF#947414]
Richard Jones <richard@users.sourceforge.net>
parents: 2246
diff changeset
2730
cd7e6d6288c6 fixed rego from email address [SF#947414]
Richard Jones <richard@users.sourceforge.net>
parents: 2246
diff changeset
2731 Arguments are passed to the Mailer.standard_message code.
4065
1e28d58c6d1c Uniformly use """...""" instead of '''...''' for comments.
Stefan Seefeld <stefan@seefeld.name>
parents: 4064
diff changeset
2732 """
1799
071ea6fc803f Extracted duplicated mail-sending code...
Johannes Gijsbers <jlgijsbers@users.sourceforge.net>
parents: 1798
diff changeset
2733 try:
1801
9f9d35f3d8f7 Change the message asking for confirmation of registration...
Johannes Gijsbers <jlgijsbers@users.sourceforge.net>
parents: 1799
diff changeset
2734 self.mailer.standard_message(to, subject, body, author)
5248
198b6e810c67 Use Python-3-compatible 'as' syntax for except statements
Eric S. Raymond <esr@thyrsus.com>
parents: 5231
diff changeset
2735 except MessageSendError as e:
4880
ca692423e401 Different approach to fix XSS in issue2550817
Ralf Schlatterbeck <rsc@runtux.com>
parents: 4851
diff changeset
2736 self.add_error_message(str(e))
2248
cd7e6d6288c6 fixed rego from email address [SF#947414]
Richard Jones <richard@users.sourceforge.net>
parents: 2246
diff changeset
2737 return 0
cd7e6d6288c6 fixed rego from email address [SF#947414]
Richard Jones <richard@users.sourceforge.net>
parents: 2246
diff changeset
2738 return 1
1467
378081f066cc registration is now a two-step process with confirmation from the
Richard Jones <richard@users.sourceforge.net>
parents: 1456
diff changeset
2739
2107
b7404a96b58a minor pre-release / test fixes
Richard Jones <richard@users.sourceforge.net>
parents: 2082
diff changeset
2740 def parsePropsFromForm(self, create=0):
2010
1b11ffd8015e forward-porting of fixed edit action / parsePropsFromForm...
Richard Jones <richard@users.sourceforge.net>
parents: 2005
diff changeset
2741 return FormParser(self).parse(create=create)
1b11ffd8015e forward-porting of fixed edit action / parsePropsFromForm...
Richard Jones <richard@users.sourceforge.net>
parents: 2005
diff changeset
2742
2799
9605965569b0 disallow caching of pages with error and/or ok messages.
Alexander Smishlajev <a1s@users.sourceforge.net>
parents: 2724
diff changeset
2743 # vim: set et sts=4 sw=4 :

Roundup Issue Tracker: http://roundup-tracker.org/