##// END OF EJS Templates
Also export config filename via extras.config in simplegit middleware (juste like for the simplehg one)
Vincent Caron -
r2858:dd2d5b65 beta
parent child Browse files
Show More
@@ -1,335 +1,337 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 rhodecode.lib.middleware.simplegit
4 4 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
5 5
6 6 SimpleGit middleware for handling git protocol request (push/clone etc.)
7 7 It's implemented with basic auth function
8 8
9 9 :created_on: Apr 28, 2010
10 10 :author: marcink
11 11 :copyright: (C) 2010-2012 Marcin Kuzminski <marcin@python-works.com>
12 12 :license: GPLv3, see COPYING for more details.
13 13 """
14 14 # This program is free software: you can redistribute it and/or modify
15 15 # it under the terms of the GNU General Public License as published by
16 16 # the Free Software Foundation, either version 3 of the License, or
17 17 # (at your option) any later version.
18 18 #
19 19 # This program is distributed in the hope that it will be useful,
20 20 # but WITHOUT ANY WARRANTY; without even the implied warranty of
21 21 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 22 # GNU General Public License for more details.
23 23 #
24 24 # You should have received a copy of the GNU General Public License
25 25 # along with this program. If not, see <http://www.gnu.org/licenses/>.
26 26
27 27 import os
28 28 import re
29 29 import logging
30 30 import traceback
31 31
32 32 from dulwich import server as dulserver
33 33 from dulwich.web import LimitedInputFilter, GunzipFilter
34 34 from rhodecode.lib.exceptions import HTTPLockedRC
35 35 from rhodecode.lib.hooks import pre_pull
36 36
37 37
38 38 class SimpleGitUploadPackHandler(dulserver.UploadPackHandler):
39 39
40 40 def handle(self):
41 41 write = lambda x: self.proto.write_sideband(1, x)
42 42
43 43 graph_walker = dulserver.ProtocolGraphWalker(self,
44 44 self.repo.object_store,
45 45 self.repo.get_peeled)
46 46 objects_iter = self.repo.fetch_objects(
47 47 graph_walker.determine_wants, graph_walker, self.progress,
48 48 get_tagged=self.get_tagged)
49 49
50 50 # Did the process short-circuit (e.g. in a stateless RPC call)? Note
51 51 # that the client still expects a 0-object pack in most cases.
52 52 if objects_iter is None:
53 53 return
54 54
55 55 self.progress("counting objects: %d, done.\n" % len(objects_iter))
56 56 dulserver.write_pack_objects(dulserver.ProtocolFile(None, write),
57 57 objects_iter)
58 58 messages = []
59 59 messages.append('thank you for using rhodecode')
60 60
61 61 for msg in messages:
62 62 self.progress(msg + "\n")
63 63 # we are done
64 64 self.proto.write("0000")
65 65
66 66
67 67 dulserver.DEFAULT_HANDLERS = {
68 68 #git-ls-remote, git-clone, git-fetch and git-pull
69 69 'git-upload-pack': SimpleGitUploadPackHandler,
70 70 #git-push
71 71 'git-receive-pack': dulserver.ReceivePackHandler,
72 72 }
73 73
74 74 # not used for now until dulwich get's fixed
75 75 #from dulwich.repo import Repo
76 76 #from dulwich.web import make_wsgi_chain
77 77
78 78 from paste.httpheaders import REMOTE_USER, AUTH_TYPE
79 79 from webob.exc import HTTPNotFound, HTTPForbidden, HTTPInternalServerError, \
80 80 HTTPBadRequest, HTTPNotAcceptable
81 81
82 82 from rhodecode.lib.utils2 import safe_str
83 83 from rhodecode.lib.base import BaseVCSController
84 84 from rhodecode.lib.auth import get_container_username
85 85 from rhodecode.lib.utils import is_valid_repo, make_ui
86 86 from rhodecode.lib.compat import json
87 87 from rhodecode.model.db import User, RhodeCodeUi
88 88
89 89 log = logging.getLogger(__name__)
90 90
91 91
92 92 GIT_PROTO_PAT = re.compile(r'^/(.+)/(info/refs|git-upload-pack|git-receive-pack)')
93 93
94 94
95 95 def is_git(environ):
96 96 path_info = environ['PATH_INFO']
97 97 isgit_path = GIT_PROTO_PAT.match(path_info)
98 98 log.debug('pathinfo: %s detected as GIT %s' % (
99 99 path_info, isgit_path != None)
100 100 )
101 101 return isgit_path
102 102
103 103
104 104 class SimpleGit(BaseVCSController):
105 105
106 106 def _handle_request(self, environ, start_response):
107 107 if not is_git(environ):
108 108 return self.application(environ, start_response)
109 109 if not self._check_ssl(environ, start_response):
110 110 return HTTPNotAcceptable('SSL REQUIRED !')(environ, start_response)
111 111
112 112 ipaddr = self._get_ip_addr(environ)
113 113 username = None
114 114 self._git_first_op = False
115 115 # skip passing error to error controller
116 116 environ['pylons.status_code_redirect'] = True
117 117
118 118 #======================================================================
119 119 # EXTRACT REPOSITORY NAME FROM ENV
120 120 #======================================================================
121 121 try:
122 122 repo_name = self.__get_repository(environ)
123 123 log.debug('Extracted repo name is %s' % repo_name)
124 124 except:
125 125 return HTTPInternalServerError()(environ, start_response)
126 126
127 127 # quick check if that dir exists...
128 128 if is_valid_repo(repo_name, self.basepath, 'git') is False:
129 129 return HTTPNotFound()(environ, start_response)
130 130
131 131 #======================================================================
132 132 # GET ACTION PULL or PUSH
133 133 #======================================================================
134 134 action = self.__get_action(environ)
135 135
136 136 #======================================================================
137 137 # CHECK ANONYMOUS PERMISSION
138 138 #======================================================================
139 139 if action in ['pull', 'push']:
140 140 anonymous_user = self.__get_user('default')
141 141 username = anonymous_user.username
142 142 anonymous_perm = self._check_permission(action, anonymous_user,
143 143 repo_name)
144 144
145 145 if anonymous_perm is not True or anonymous_user.active is False:
146 146 if anonymous_perm is not True:
147 147 log.debug('Not enough credentials to access this '
148 148 'repository as anonymous user')
149 149 if anonymous_user.active is False:
150 150 log.debug('Anonymous access is disabled, running '
151 151 'authentication')
152 152 #==============================================================
153 153 # DEFAULT PERM FAILED OR ANONYMOUS ACCESS IS DISABLED SO WE
154 154 # NEED TO AUTHENTICATE AND ASK FOR AUTH USER PERMISSIONS
155 155 #==============================================================
156 156
157 157 # Attempting to retrieve username from the container
158 158 username = get_container_username(environ, self.config)
159 159
160 160 # If not authenticated by the container, running basic auth
161 161 if not username:
162 162 self.authenticate.realm = \
163 163 safe_str(self.config['rhodecode_realm'])
164 164 result = self.authenticate(environ)
165 165 if isinstance(result, str):
166 166 AUTH_TYPE.update(environ, 'basic')
167 167 REMOTE_USER.update(environ, result)
168 168 username = result
169 169 else:
170 170 return result.wsgi_application(environ, start_response)
171 171
172 172 #==============================================================
173 173 # CHECK PERMISSIONS FOR THIS REQUEST USING GIVEN USERNAME
174 174 #==============================================================
175 175 try:
176 176 user = self.__get_user(username)
177 177 if user is None or not user.active:
178 178 return HTTPForbidden()(environ, start_response)
179 179 username = user.username
180 180 except:
181 181 log.error(traceback.format_exc())
182 182 return HTTPInternalServerError()(environ, start_response)
183 183
184 184 #check permissions for this repository
185 185 perm = self._check_permission(action, user, repo_name)
186 186 if perm is not True:
187 187 return HTTPForbidden()(environ, start_response)
188 188
189 189 # extras are injected into UI object and later available
190 190 # in hooks executed by rhodecode
191 from rhodecode import CONFIG
191 192 extras = {
192 193 'ip': ipaddr,
193 194 'username': username,
194 195 'action': action,
195 196 'repository': repo_name,
196 197 'scm': 'git',
198 'config': CONFIG['__file__'],
197 199 'make_lock': None,
198 200 'locked_by': [None, None]
199 201 }
200 202
201 203 #===================================================================
202 204 # GIT REQUEST HANDLING
203 205 #===================================================================
204 206 repo_path = os.path.join(safe_str(self.basepath), safe_str(repo_name))
205 207 log.debug('Repository path is %s' % repo_path)
206 208
207 209 # CHECK LOCKING only if it's not ANONYMOUS USER
208 210 if username != User.DEFAULT_USER:
209 211 log.debug('Checking locking on repository')
210 212 (make_lock,
211 213 locked,
212 214 locked_by) = self._check_locking_state(
213 215 environ=environ, action=action,
214 216 repo=repo_name, user_id=user.user_id
215 217 )
216 218 # store the make_lock for later evaluation in hooks
217 219 extras.update({'make_lock': make_lock,
218 220 'locked_by': locked_by})
219 221 # set the environ variables for this request
220 222 os.environ['RC_SCM_DATA'] = json.dumps(extras)
221 223 log.debug('HOOKS extras is %s' % extras)
222 224 baseui = make_ui('db')
223 225 self.__inject_extras(repo_path, baseui, extras)
224 226
225 227 try:
226 228 # invalidate cache on push
227 229 if action == 'push':
228 230 self._invalidate_cache(repo_name)
229 231 self._handle_githooks(repo_name, action, baseui, environ)
230 232
231 233 log.info('%s action on GIT repo "%s"' % (action, repo_name))
232 234 app = self.__make_app(repo_name, repo_path, extras)
233 235 return app(environ, start_response)
234 236 except HTTPLockedRC, e:
235 237 log.debug('Repositry LOCKED ret code 423!')
236 238 return e(environ, start_response)
237 239 except Exception:
238 240 log.error(traceback.format_exc())
239 241 return HTTPInternalServerError()(environ, start_response)
240 242
241 243 def __make_app(self, repo_name, repo_path, extras):
242 244 """
243 245 Make an wsgi application using dulserver
244 246
245 247 :param repo_name: name of the repository
246 248 :param repo_path: full path to the repository
247 249 """
248 250
249 251 from rhodecode.lib.middleware.pygrack import make_wsgi_app
250 252 app = make_wsgi_app(
251 253 repo_root=safe_str(self.basepath),
252 254 repo_name=repo_name,
253 255 extras=extras,
254 256 )
255 257 app = GunzipFilter(LimitedInputFilter(app))
256 258 return app
257 259
258 260 def __get_repository(self, environ):
259 261 """
260 262 Get's repository name out of PATH_INFO header
261 263
262 264 :param environ: environ where PATH_INFO is stored
263 265 """
264 266 try:
265 267 environ['PATH_INFO'] = self._get_by_id(environ['PATH_INFO'])
266 268 repo_name = GIT_PROTO_PAT.match(environ['PATH_INFO']).group(1)
267 269 except:
268 270 log.error(traceback.format_exc())
269 271 raise
270 272
271 273 return repo_name
272 274
273 275 def __get_user(self, username):
274 276 return User.get_by_username(username)
275 277
276 278 def __get_action(self, environ):
277 279 """
278 280 Maps git request commands into a pull or push command.
279 281
280 282 :param environ:
281 283 """
282 284 service = environ['QUERY_STRING'].split('=')
283 285
284 286 if len(service) > 1:
285 287 service_cmd = service[1]
286 288 mapping = {
287 289 'git-receive-pack': 'push',
288 290 'git-upload-pack': 'pull',
289 291 }
290 292 op = mapping[service_cmd]
291 293 self._git_stored_op = op
292 294 return op
293 295 else:
294 296 # try to fallback to stored variable as we don't know if the last
295 297 # operation is pull/push
296 298 op = getattr(self, '_git_stored_op', 'pull')
297 299 return op
298 300
299 301 def _handle_githooks(self, repo_name, action, baseui, environ):
300 302 """
301 303 Handles pull action, push is handled by post-receive hook
302 304 """
303 305 from rhodecode.lib.hooks import log_pull_action
304 306 service = environ['QUERY_STRING'].split('=')
305 307
306 308 if len(service) < 2:
307 309 return
308 310
309 311 from rhodecode.model.db import Repository
310 312 _repo = Repository.get_by_repo_name(repo_name)
311 313 _repo = _repo.scm_instance
312 314 _repo._repo.ui = baseui
313 315
314 316 _hooks = dict(baseui.configitems('hooks')) or {}
315 317 if action == 'pull':
316 318 # stupid git, emulate pre-pull hook !
317 319 pre_pull(ui=baseui, repo=_repo._repo)
318 320 if action == 'pull' and _hooks.get(RhodeCodeUi.HOOK_PULL):
319 321 log_pull_action(ui=baseui, repo=_repo._repo)
320 322
321 323 def __inject_extras(self, repo_path, baseui, extras={}):
322 324 """
323 325 Injects some extra params into baseui instance
324 326
325 327 :param baseui: baseui instance
326 328 :param extras: dict with extra params to put into baseui
327 329 """
328 330
329 331 # make our hgweb quiet so it doesn't print output
330 332 baseui.setconfig('ui', 'quiet', 'true')
331 333
332 334 #inject some additional parameters that will be available in ui
333 335 #for hooks
334 336 for k, v in extras.items():
335 337 baseui.setconfig('rhodecode_extras', k, v)
General Comments 0
You need to be logged in to leave comments. Login now