##// END OF EJS Templates
ui: report_untrusted fixes...
Matt Mackall -
r8204:797586be default
parent child Browse files
Show More
@@ -1,350 +1,350 b''
1 1 # ui.py - user interface bits for mercurial
2 2 #
3 3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 4 #
5 5 # This software may be used and distributed according to the terms
6 6 # of the GNU General Public License, incorporated herein by reference.
7 7
8 8 from i18n import _
9 9 import errno, getpass, os, re, socket, sys, tempfile
10 10 import config, traceback, util, error
11 11
12 12 _booleans = {'1':True, 'yes':True, 'true':True, 'on':True,
13 13 '0':False, 'no':False, 'false':False, 'off':False}
14 14
15 15 class ui(object):
16 16 def __init__(self, src=None):
17 17 self._buffers = []
18 18 self.quiet = self.verbose = self.debugflag = self.traceback = False
19 self.interactive = self.report_untrusted = True
19 self.interactive = self._reportuntrusted = True
20 20 self._ocfg = config.config() # overlay
21 21 self._tcfg = config.config() # trusted
22 22 self._ucfg = config.config() # untrusted
23 23 self._trustusers = {}
24 24 self._trustgroups = {}
25 25
26 26 if src:
27 27 self._tcfg = src._tcfg.copy()
28 28 self._ucfg = src._ucfg.copy()
29 29 self._ocfg = src._ocfg.copy()
30 30 self._trustusers = src._trustusers.copy()
31 31 self._trustgroups = src._trustgroups.copy()
32 32 self.fixconfig()
33 33 else:
34 34 # we always trust global config files
35 35 for f in util.rcpath():
36 36 self.readconfig(f, trust=True)
37 37 def copy(self):
38 38 return ui(self)
39 39
40 40 _isatty = None
41 41 def isatty(self):
42 42 if ui._isatty is None:
43 43 try:
44 44 ui._isatty = sys.stdin.isatty()
45 45 except AttributeError: # not a real file object
46 46 ui._isatty = False
47 47 except IOError:
48 48 # access to stdin is unsafe in a WSGI environment
49 49 ui._isatty = False
50 50 return ui._isatty
51 51
52 52 def _is_trusted(self, fp, f):
53 53 st = util.fstat(fp)
54 54 if util.isowner(fp, st):
55 55 return True
56 56
57 57 tusers, tgroups = self._trustusers, self._trustgroups
58 58 if '*' in tusers or '*' in tgroups:
59 59 return True
60 60
61 61 user = util.username(st.st_uid)
62 62 group = util.groupname(st.st_gid)
63 63 if user in tusers or group in tgroups or user == util.username():
64 64 return True
65 65
66 if self.report_untrusted:
66 if self._reportuntrusted:
67 67 self.warn(_('Not trusting file %s from untrusted '
68 68 'user %s, group %s\n') % (f, user, group))
69 69 return False
70 70
71 71 def readconfig(self, filename, root=None, trust=False,
72 72 sections = None):
73 73 try:
74 74 fp = open(filename)
75 75 except IOError:
76 76 if not sections: # ignore unless we were looking for something
77 77 return
78 78 raise
79 79
80 80 cfg = config.config()
81 81 trusted = sections or trust or self._is_trusted(fp, filename)
82 82
83 83 try:
84 84 cfg.read(filename, fp, sections=sections)
85 85 except error.ConfigError, inst:
86 86 if trusted:
87 87 raise
88 88 self.warn(_("Ignored: %s\n") % str(inst))
89 89
90 90 if trusted:
91 91 self._tcfg.update(cfg)
92 92 self._tcfg.update(self._ocfg)
93 93 self._ucfg.update(cfg)
94 94 self._ucfg.update(self._ocfg)
95 95
96 96 if root is None:
97 97 root = os.path.expanduser('~')
98 98 self.fixconfig(root=root)
99 99
100 100 def fixconfig(self, root=None):
101 101 # translate paths relative to root (or home) into absolute paths
102 102 root = root or os.getcwd()
103 103 for c in self._tcfg, self._ucfg, self._ocfg:
104 104 for n, p in c.items('paths'):
105 105 if p and "://" not in p and not os.path.isabs(p):
106 106 c.set("paths", n, os.path.normpath(os.path.join(root, p)))
107 107
108 108 # update ui options
109 109 self.debugflag = self.configbool('ui', 'debug')
110 110 self.verbose = self.debugflag or self.configbool('ui', 'verbose')
111 111 self.quiet = not self.debugflag and self.configbool('ui', 'quiet')
112 112 if self.verbose and self.quiet:
113 113 self.quiet = self.verbose = False
114 self.report_untrusted = self.configbool("ui", "report_untrusted", True)
114 self._reportuntrusted = self.configbool("ui", "report_untrusted", True)
115 115 self.interactive = self.configbool("ui", "interactive", self.isatty())
116 116 self.traceback = self.configbool('ui', 'traceback', False)
117 117
118 118 # update trust information
119 119 for user in self.configlist('trusted', 'users'):
120 120 self._trustusers[user] = 1
121 121 for group in self.configlist('trusted', 'groups'):
122 122 self._trustgroups[group] = 1
123 123
124 124 def setconfig(self, section, name, value):
125 125 for cfg in (self._ocfg, self._tcfg, self._ucfg):
126 126 cfg.set(section, name, value)
127 127 self.fixconfig()
128 128
129 129 def _data(self, untrusted):
130 130 return untrusted and self._ucfg or self._tcfg
131 131
132 132 def configsource(self, section, name, untrusted=False):
133 133 return self._data(untrusted).source(section, name) or 'none'
134 134
135 135 def config(self, section, name, default=None, untrusted=False):
136 136 value = self._data(untrusted).get(section, name, default)
137 if self.debugflag and not untrusted:
137 if self.debugflag and not untrusted and self._reportuntrusted:
138 138 uvalue = self._ucfg.get(section, name)
139 139 if uvalue is not None and uvalue != value:
140 self.warn(_("Ignoring untrusted configuration option "
140 self.debug(_("ignoring untrusted configuration option "
141 141 "%s.%s = %s\n") % (section, name, uvalue))
142 142 return value
143 143
144 144 def configbool(self, section, name, default=False, untrusted=False):
145 145 v = self.config(section, name, None, untrusted)
146 146 if v == None:
147 147 return default
148 148 if v.lower() not in _booleans:
149 149 raise error.ConfigError(_("%s.%s not a boolean ('%s')")
150 150 % (section, name, v))
151 151 return _booleans[v.lower()]
152 152
153 153 def configlist(self, section, name, default=None, untrusted=False):
154 154 """Return a list of comma/space separated strings"""
155 155 result = self.config(section, name, untrusted=untrusted)
156 156 if result is None:
157 157 result = default or []
158 158 if isinstance(result, basestring):
159 159 result = result.replace(",", " ").split()
160 160 return result
161 161
162 162 def has_section(self, section, untrusted=False):
163 163 '''tell whether section exists in config.'''
164 164 return section in self._data(untrusted)
165 165
166 166 def configitems(self, section, untrusted=False):
167 167 items = self._data(untrusted).items(section)
168 if self.debugflag and not untrusted:
168 if self.debugflag and not untrusted and self._reportuntrusted:
169 169 for k,v in self._ucfg.items(section):
170 170 if self._tcfg.get(section, k) != v:
171 self.warn(_("Ignoring untrusted configuration option "
171 self.debug(_("ignoring untrusted configuration option "
172 172 "%s.%s = %s\n") % (section, k, v))
173 173 return items
174 174
175 175 def walkconfig(self, untrusted=False):
176 176 cfg = self._data(untrusted)
177 177 for section in cfg.sections():
178 178 for name, value in self.configitems(section, untrusted):
179 179 yield section, name, str(value).replace('\n', '\\n')
180 180
181 181 def username(self):
182 182 """Return default username to be used in commits.
183 183
184 184 Searched in this order: $HGUSER, [ui] section of hgrcs, $EMAIL
185 185 and stop searching if one of these is set.
186 186 If not found and ui.askusername is True, ask the user, else use
187 187 ($LOGNAME or $USER or $LNAME or $USERNAME) + "@full.hostname".
188 188 """
189 189 user = os.environ.get("HGUSER")
190 190 if user is None:
191 191 user = self.config("ui", "username")
192 192 if user is None:
193 193 user = os.environ.get("EMAIL")
194 194 if user is None and self.configbool("ui", "askusername"):
195 195 user = self.prompt(_("enter a commit username:"), default=None)
196 196 if user is None:
197 197 try:
198 198 user = '%s@%s' % (util.getuser(), socket.getfqdn())
199 199 self.warn(_("No username found, using '%s' instead\n") % user)
200 200 except KeyError:
201 201 pass
202 202 if not user:
203 203 raise util.Abort(_("Please specify a username."))
204 204 if "\n" in user:
205 205 raise util.Abort(_("username %s contains a newline\n") % repr(user))
206 206 return user
207 207
208 208 def shortuser(self, user):
209 209 """Return a short representation of a user name or email address."""
210 210 if not self.verbose: user = util.shortuser(user)
211 211 return user
212 212
213 213 def _path(self, loc):
214 214 p = self.config('paths', loc)
215 215 if p and '%%' in p:
216 216 ui.warn('(deprecated \'\%\%\' in path %s=%s from %s)\n' %
217 217 (loc, p, self.configsource('paths', loc)))
218 218 p = p.replace('%%', '%')
219 219 return p
220 220
221 221 def expandpath(self, loc, default=None):
222 222 """Return repository location relative to cwd or from [paths]"""
223 223 if "://" in loc or os.path.isdir(os.path.join(loc, '.hg')):
224 224 return loc
225 225
226 226 path = self._path(loc)
227 227 if not path and default is not None:
228 228 path = self._path(default)
229 229 return path or loc
230 230
231 231 def pushbuffer(self):
232 232 self._buffers.append([])
233 233
234 234 def popbuffer(self):
235 235 return "".join(self._buffers.pop())
236 236
237 237 def write(self, *args):
238 238 if self._buffers:
239 239 self._buffers[-1].extend([str(a) for a in args])
240 240 else:
241 241 for a in args:
242 242 sys.stdout.write(str(a))
243 243
244 244 def write_err(self, *args):
245 245 try:
246 246 if not sys.stdout.closed: sys.stdout.flush()
247 247 for a in args:
248 248 sys.stderr.write(str(a))
249 249 # stderr may be buffered under win32 when redirected to files,
250 250 # including stdout.
251 251 if not sys.stderr.closed: sys.stderr.flush()
252 252 except IOError, inst:
253 253 if inst.errno != errno.EPIPE:
254 254 raise
255 255
256 256 def flush(self):
257 257 try: sys.stdout.flush()
258 258 except: pass
259 259 try: sys.stderr.flush()
260 260 except: pass
261 261
262 262 def _readline(self, prompt=''):
263 263 if self.isatty():
264 264 try:
265 265 # magically add command line editing support, where
266 266 # available
267 267 import readline
268 268 # force demandimport to really load the module
269 269 readline.read_history_file
270 270 # windows sometimes raises something other than ImportError
271 271 except Exception:
272 272 pass
273 273 line = raw_input(prompt)
274 274 # When stdin is in binary mode on Windows, it can cause
275 275 # raw_input() to emit an extra trailing carriage return
276 276 if os.linesep == '\r\n' and line and line[-1] == '\r':
277 277 line = line[:-1]
278 278 return line
279 279
280 280 def prompt(self, msg, pat=None, default="y"):
281 281 """Prompt user with msg, read response, and ensure it matches pat
282 282
283 283 If not interactive -- the default is returned
284 284 """
285 285 if not self.interactive:
286 286 self.note(msg, ' ', default, "\n")
287 287 return default
288 288 while True:
289 289 try:
290 290 r = self._readline(msg + ' ')
291 291 if not r:
292 292 return default
293 293 if not pat or re.match(pat, r):
294 294 return r
295 295 else:
296 296 self.write(_("unrecognized response\n"))
297 297 except EOFError:
298 298 raise util.Abort(_('response expected'))
299 299
300 300 def getpass(self, prompt=None, default=None):
301 301 if not self.interactive: return default
302 302 try:
303 303 return getpass.getpass(prompt or _('password: '))
304 304 except EOFError:
305 305 raise util.Abort(_('response expected'))
306 306 def status(self, *msg):
307 307 if not self.quiet: self.write(*msg)
308 308 def warn(self, *msg):
309 309 self.write_err(*msg)
310 310 def note(self, *msg):
311 311 if self.verbose: self.write(*msg)
312 312 def debug(self, *msg):
313 313 if self.debugflag: self.write(*msg)
314 314 def edit(self, text, user):
315 315 (fd, name) = tempfile.mkstemp(prefix="hg-editor-", suffix=".txt",
316 316 text=True)
317 317 try:
318 318 f = os.fdopen(fd, "w")
319 319 f.write(text)
320 320 f.close()
321 321
322 322 editor = self.geteditor()
323 323
324 324 util.system("%s \"%s\"" % (editor, name),
325 325 environ={'HGUSER': user},
326 326 onerr=util.Abort, errprefix=_("edit failed"))
327 327
328 328 f = open(name)
329 329 t = f.read()
330 330 f.close()
331 331 t = re.sub("(?m)^HG:.*\n", "", t)
332 332 finally:
333 333 os.unlink(name)
334 334
335 335 return t
336 336
337 337 def print_exc(self):
338 338 '''print exception traceback if traceback printing enabled.
339 339 only to call in exception handler. returns true if traceback
340 340 printed.'''
341 341 if self.traceback:
342 342 traceback.print_exc()
343 343 return self.traceback
344 344
345 345 def geteditor(self):
346 346 '''return editor to use'''
347 347 return (os.environ.get("HGEDITOR") or
348 348 self.config("ui", "editor") or
349 349 os.environ.get("VISUAL") or
350 350 os.environ.get("EDITOR", "vi"))
@@ -1,160 +1,160 b''
1 1 # same user, same group
2 2 trusted
3 3 global = /some/path
4 4 local = /another/path
5 5 untrusted
6 6 . . global = /some/path
7 7 . . local = /another/path
8 8
9 9 # same user, different group
10 10 trusted
11 11 global = /some/path
12 12 local = /another/path
13 13 untrusted
14 14 . . global = /some/path
15 15 . . local = /another/path
16 16
17 17 # different user, same group
18 18 Not trusting file .hg/hgrc from untrusted user abc, group bar
19 19 trusted
20 20 global = /some/path
21 21 untrusted
22 22 . . global = /some/path
23 23 . . local = /another/path
24 24
25 25 # different user, same group, but we trust the group
26 26 trusted
27 27 global = /some/path
28 28 local = /another/path
29 29 untrusted
30 30 . . global = /some/path
31 31 . . local = /another/path
32 32
33 33 # different user, different group
34 34 Not trusting file .hg/hgrc from untrusted user abc, group def
35 35 trusted
36 36 global = /some/path
37 37 untrusted
38 38 . . global = /some/path
39 39 . . local = /another/path
40 40
41 41 # different user, different group, but we trust the user
42 42 trusted
43 43 global = /some/path
44 44 local = /another/path
45 45 untrusted
46 46 . . global = /some/path
47 47 . . local = /another/path
48 48
49 49 # different user, different group, but we trust the group
50 50 trusted
51 51 global = /some/path
52 52 local = /another/path
53 53 untrusted
54 54 . . global = /some/path
55 55 . . local = /another/path
56 56
57 57 # different user, different group, but we trust the user and the group
58 58 trusted
59 59 global = /some/path
60 60 local = /another/path
61 61 untrusted
62 62 . . global = /some/path
63 63 . . local = /another/path
64 64
65 65 # we trust all users
66 66 # different user, different group
67 67 trusted
68 68 global = /some/path
69 69 local = /another/path
70 70 untrusted
71 71 . . global = /some/path
72 72 . . local = /another/path
73 73
74 74 # we trust all groups
75 75 # different user, different group
76 76 trusted
77 77 global = /some/path
78 78 local = /another/path
79 79 untrusted
80 80 . . global = /some/path
81 81 . . local = /another/path
82 82
83 83 # we trust all users and groups
84 84 # different user, different group
85 85 trusted
86 86 global = /some/path
87 87 local = /another/path
88 88 untrusted
89 89 . . global = /some/path
90 90 . . local = /another/path
91 91
92 92 # we don't get confused by users and groups with the same name
93 93 # different user, different group
94 94 Not trusting file .hg/hgrc from untrusted user abc, group def
95 95 trusted
96 96 global = /some/path
97 97 untrusted
98 98 . . global = /some/path
99 99 . . local = /another/path
100 100
101 101 # list of user names
102 102 # different user, different group, but we trust the user
103 103 trusted
104 104 global = /some/path
105 105 local = /another/path
106 106 untrusted
107 107 . . global = /some/path
108 108 . . local = /another/path
109 109
110 110 # list of group names
111 111 # different user, different group, but we trust the group
112 112 trusted
113 113 global = /some/path
114 114 local = /another/path
115 115 untrusted
116 116 . . global = /some/path
117 117 . . local = /another/path
118 118
119 119 # Can't figure out the name of the user running this process
120 120 # different user, different group
121 121 Not trusting file .hg/hgrc from untrusted user abc, group def
122 122 trusted
123 123 global = /some/path
124 124 untrusted
125 125 . . global = /some/path
126 126 . . local = /another/path
127 127
128 128 # prints debug warnings
129 129 # different user, different group
130 130 Not trusting file .hg/hgrc from untrusted user abc, group def
131 131 trusted
132 Ignoring untrusted configuration option paths.local = /another/path
132 ignoring untrusted configuration option paths.local = /another/path
133 133 global = /some/path
134 134 untrusted
135 135 . . global = /some/path
136 .Ignoring untrusted configuration option paths.local = /another/path
137 . local = /another/path
136 .ignoring untrusted configuration option paths.local = /another/path
137 . local = /another/path
138 138
139 139 # ui.readconfig sections
140 140 quux
141 141
142 142 # read trusted, untrusted, new ui, trusted
143 143 Not trusting file foobar from untrusted user abc, group def
144 144 trusted:
145 Ignoring untrusted configuration option foobar.baz = quux
145 ignoring untrusted configuration option foobar.baz = quux
146 146 None
147 147 untrusted:
148 148 quux
149 149
150 150 # error handling
151 151 # file doesn't exist
152 152 # same user, same group
153 153 # different user, different group
154 154
155 155 # parse error
156 156 # different user, different group
157 157 Not trusting file .hg/hgrc from untrusted user abc, group def
158 158 Ignored: config error at .hg/hgrc:1: 'foo'
159 159 # same user, same group
160 160 config error at .hg/hgrc:1: 'foo'
General Comments 0
You need to be logged in to leave comments. Login now