948
655
except ImportError:
951
user_encoding = osutils.get_user_encoding()
952
realname = username = getpass.getuser().decode(user_encoding)
658
realname = username = getpass.getuser().decode(bzrlib.user_encoding)
953
659
except UnicodeDecodeError:
954
660
raise errors.BzrError("Can't decode username as %s." % \
661
bzrlib.user_encoding)
957
663
return realname, (username + '@' + socket.gethostname())
960
def parse_username(username):
961
"""Parse e-mail username and return a (name, address) tuple."""
962
match = re.match(r'(.*?)\s*<?([\w+.-]+@[\w+.-]+)>?', username)
964
return (username, '')
966
return (match.group(1), match.group(2))
969
666
def extract_email_address(e):
970
667
"""Return just the address part of an email string.
972
That is just the user@domain part, nothing else.
669
That is just the user@domain part, nothing else.
973
670
This part is required to contain only ascii characters.
974
671
If it can't be extracted, raises an error.
976
673
>>> extract_email_address('Jane Tester <jane@test.com>')
979
name, email = parse_username(e)
981
raise errors.NoEmailInUsername(e)
676
m = re.search(r'[\w+.-]+@[\w+.-]+', e)
678
raise errors.BzrError("%r doesn't seem to contain "
679
"a reasonable email address" % e)
985
683
class TreeConfig(IniBasedConfig):
986
684
"""Branch configuration data associated with its contents, not location"""
988
# XXX: Really needs a better name, as this is not part of the tree! -- mbp 20080507
990
685
def __init__(self, branch):
991
self._config = branch._get_config()
992
686
self.branch = branch
994
688
def _get_parser(self, file=None):
995
689
if file is not None:
996
690
return IniBasedConfig._get_parser(file)
997
return self._config._get_configobj()
691
return self._get_config()
693
def _get_config(self):
695
obj = ConfigObj(self.branch.control_files.get('branch.conf'),
697
except errors.NoSuchFile:
698
obj = ConfigObj(encoding='utf=8')
999
701
def get_option(self, name, section=None, default=None):
1000
702
self.branch.lock_read()
1002
return self._config.get_option(name, section, default)
704
obj = self._get_config()
706
if section is not None:
1004
712
self.branch.unlock()
1006
715
def set_option(self, value, name, section=None):
1007
716
"""Set a per-branch configuration option"""
1008
717
self.branch.lock_write()
1010
self._config.set_option(value, name, section)
719
cfg_obj = self._get_config()
724
obj = cfg_obj[section]
726
cfg_obj[section] = {}
727
obj = cfg_obj[section]
729
out_file = StringIO()
730
cfg_obj.write(out_file)
732
self.branch.control_files.put('branch.conf', out_file)
1012
734
self.branch.unlock()
1015
class AuthenticationConfig(object):
1016
"""The authentication configuration file based on a ini file.
1018
Implements the authentication.conf file described in
1019
doc/developers/authentication-ring.txt.
1022
def __init__(self, _file=None):
1023
self._config = None # The ConfigObj
1025
self._filename = authentication_config_filename()
1026
self._input = self._filename = authentication_config_filename()
1028
# Tests can provide a string as _file
1029
self._filename = None
1032
def _get_config(self):
1033
if self._config is not None:
1036
# FIXME: Should we validate something here ? Includes: empty
1037
# sections are useless, at least one of
1038
# user/password/password_encoding should be defined, etc.
1040
# Note: the encoding below declares that the file itself is utf-8
1041
# encoded, but the values in the ConfigObj are always Unicode.
1042
self._config = ConfigObj(self._input, encoding='utf-8')
1043
except configobj.ConfigObjError, e:
1044
raise errors.ParseConfigError(e.errors, e.config.filename)
1048
"""Save the config file, only tests should use it for now."""
1049
conf_dir = os.path.dirname(self._filename)
1050
ensure_config_dir_exists(conf_dir)
1051
self._get_config().write(file(self._filename, 'wb'))
1053
def _set_option(self, section_name, option_name, value):
1054
"""Set an authentication configuration option"""
1055
conf = self._get_config()
1056
section = conf.get(section_name)
1059
section = conf[section]
1060
section[option_name] = value
1063
def get_credentials(self, scheme, host, port=None, user=None, path=None,
1065
"""Returns the matching credentials from authentication.conf file.
1067
:param scheme: protocol
1069
:param host: the server address
1071
:param port: the associated port (optional)
1073
:param user: login (optional)
1075
:param path: the absolute path on the server (optional)
1077
:param realm: the http authentication realm (optional)
1079
:return: A dict containing the matching credentials or None.
1081
- name: the section name of the credentials in the
1082
authentication.conf file,
1083
- user: can't be different from the provided user if any,
1084
- scheme: the server protocol,
1085
- host: the server address,
1086
- port: the server port (can be None),
1087
- path: the absolute server path (can be None),
1088
- realm: the http specific authentication realm (can be None),
1089
- password: the decoded password, could be None if the credential
1090
defines only the user
1091
- verify_certificates: https specific, True if the server
1092
certificate should be verified, False otherwise.
1095
for auth_def_name, auth_def in self._get_config().items():
1096
if type(auth_def) is not configobj.Section:
1097
raise ValueError("%s defined outside a section" % auth_def_name)
1099
a_scheme, a_host, a_user, a_path = map(
1100
auth_def.get, ['scheme', 'host', 'user', 'path'])
1103
a_port = auth_def.as_int('port')
1107
raise ValueError("'port' not numeric in %s" % auth_def_name)
1109
a_verify_certificates = auth_def.as_bool('verify_certificates')
1111
a_verify_certificates = True
1114
"'verify_certificates' not boolean in %s" % auth_def_name)
1117
if a_scheme is not None and scheme != a_scheme:
1119
if a_host is not None:
1120
if not (host == a_host
1121
or (a_host.startswith('.') and host.endswith(a_host))):
1123
if a_port is not None and port != a_port:
1125
if (a_path is not None and path is not None
1126
and not path.startswith(a_path)):
1128
if (a_user is not None and user is not None
1129
and a_user != user):
1130
# Never contradict the caller about the user to be used
1135
# Prepare a credentials dictionary with additional keys
1136
# for the credential providers
1137
credentials = dict(name=auth_def_name,
1144
password=auth_def.get('password', None),
1145
verify_certificates=a_verify_certificates)
1146
# Decode the password in the credentials (or get one)
1147
self.decode_password(credentials,
1148
auth_def.get('password_encoding', None))
1149
if 'auth' in debug.debug_flags:
1150
trace.mutter("Using authentication section: %r", auth_def_name)
1153
if credentials is None:
1154
# No credentials were found in authentication.conf, try the fallback
1155
# credentials stores.
1156
credentials = credential_store_registry.get_fallback_credentials(
1157
scheme, host, port, user, path, realm)
1161
def set_credentials(self, name, host, user, scheme=None, password=None,
1162
port=None, path=None, verify_certificates=None,
1164
"""Set authentication credentials for a host.
1166
Any existing credentials with matching scheme, host, port and path
1167
will be deleted, regardless of name.
1169
:param name: An arbitrary name to describe this set of credentials.
1170
:param host: Name of the host that accepts these credentials.
1171
:param user: The username portion of these credentials.
1172
:param scheme: The URL scheme (e.g. ssh, http) the credentials apply
1174
:param password: Password portion of these credentials.
1175
:param port: The IP port on the host that these credentials apply to.
1176
:param path: A filesystem path on the host that these credentials
1178
:param verify_certificates: On https, verify server certificates if
1180
:param realm: The http authentication realm (optional).
1182
values = {'host': host, 'user': user}
1183
if password is not None:
1184
values['password'] = password
1185
if scheme is not None:
1186
values['scheme'] = scheme
1187
if port is not None:
1188
values['port'] = '%d' % port
1189
if path is not None:
1190
values['path'] = path
1191
if verify_certificates is not None:
1192
values['verify_certificates'] = str(verify_certificates)
1193
if realm is not None:
1194
values['realm'] = realm
1195
config = self._get_config()
1197
for section, existing_values in config.items():
1198
for key in ('scheme', 'host', 'port', 'path', 'realm'):
1199
if existing_values.get(key) != values.get(key):
1203
config.update({name: values})
1206
def get_user(self, scheme, host, port=None, realm=None, path=None,
1207
prompt=None, ask=False, default=None):
1208
"""Get a user from authentication file.
1210
:param scheme: protocol
1212
:param host: the server address
1214
:param port: the associated port (optional)
1216
:param realm: the realm sent by the server (optional)
1218
:param path: the absolute path on the server (optional)
1220
:param ask: Ask the user if there is no explicitly configured username
1223
:param default: The username returned if none is defined (optional).
1225
:return: The found user.
1227
credentials = self.get_credentials(scheme, host, port, user=None,
1228
path=path, realm=realm)
1229
if credentials is not None:
1230
user = credentials['user']
1236
# Create a default prompt suitable for most cases
1237
prompt = scheme.upper() + ' %(host)s username'
1238
# Special handling for optional fields in the prompt
1239
if port is not None:
1240
prompt_host = '%s:%d' % (host, port)
1243
user = ui.ui_factory.get_username(prompt, host=prompt_host)
1248
def get_password(self, scheme, host, user, port=None,
1249
realm=None, path=None, prompt=None):
1250
"""Get a password from authentication file or prompt the user for one.
1252
:param scheme: protocol
1254
:param host: the server address
1256
:param port: the associated port (optional)
1260
:param realm: the realm sent by the server (optional)
1262
:param path: the absolute path on the server (optional)
1264
:return: The found password or the one entered by the user.
1266
credentials = self.get_credentials(scheme, host, port, user, path,
1268
if credentials is not None:
1269
password = credentials['password']
1270
if password is not None and scheme is 'ssh':
1271
trace.warning('password ignored in section [%s],'
1272
' use an ssh agent instead'
1273
% credentials['name'])
1277
# Prompt user only if we could't find a password
1278
if password is None:
1280
# Create a default prompt suitable for most cases
1281
prompt = '%s' % scheme.upper() + ' %(user)s@%(host)s password'
1282
# Special handling for optional fields in the prompt
1283
if port is not None:
1284
prompt_host = '%s:%d' % (host, port)
1287
password = ui.ui_factory.get_password(prompt,
1288
host=prompt_host, user=user)
1291
def decode_password(self, credentials, encoding):
1293
cs = credential_store_registry.get_credential_store(encoding)
1295
raise ValueError('%r is not a known password_encoding' % encoding)
1296
credentials['password'] = cs.decode_password(credentials)
1300
class CredentialStoreRegistry(registry.Registry):
1301
"""A class that registers credential stores.
1303
A credential store provides access to credentials via the password_encoding
1304
field in authentication.conf sections.
1306
Except for stores provided by bzr itself, most stores are expected to be
1307
provided by plugins that will therefore use
1308
register_lazy(password_encoding, module_name, member_name, help=help,
1309
fallback=fallback) to install themselves.
1311
A fallback credential store is one that is queried if no credentials can be
1312
found via authentication.conf.
1315
def get_credential_store(self, encoding=None):
1316
cs = self.get(encoding)
1321
def is_fallback(self, name):
1322
"""Check if the named credentials store should be used as fallback."""
1323
return self.get_info(name)
1325
def get_fallback_credentials(self, scheme, host, port=None, user=None,
1326
path=None, realm=None):
1327
"""Request credentials from all fallback credentials stores.
1329
The first credentials store that can provide credentials wins.
1332
for name in self.keys():
1333
if not self.is_fallback(name):
1335
cs = self.get_credential_store(name)
1336
credentials = cs.get_credentials(scheme, host, port, user,
1338
if credentials is not None:
1339
# We found some credentials
1343
def register(self, key, obj, help=None, override_existing=False,
1345
"""Register a new object to a name.
1347
:param key: This is the key to use to request the object later.
1348
:param obj: The object to register.
1349
:param help: Help text for this entry. This may be a string or
1350
a callable. If it is a callable, it should take two
1351
parameters (registry, key): this registry and the key that
1352
the help was registered under.
1353
:param override_existing: Raise KeyErorr if False and something has
1354
already been registered for that key. If True, ignore if there
1355
is an existing key (always register the new value).
1356
:param fallback: Whether this credential store should be
1359
return super(CredentialStoreRegistry,
1360
self).register(key, obj, help, info=fallback,
1361
override_existing=override_existing)
1363
def register_lazy(self, key, module_name, member_name,
1364
help=None, override_existing=False,
1366
"""Register a new credential store to be loaded on request.
1368
:param module_name: The python path to the module. Such as 'os.path'.
1369
:param member_name: The member of the module to return. If empty or
1370
None, get() will return the module itself.
1371
:param help: Help text for this entry. This may be a string or
1373
:param override_existing: If True, replace the existing object
1374
with the new one. If False, if there is already something
1375
registered with the same key, raise a KeyError
1376
:param fallback: Whether this credential store should be
1379
return super(CredentialStoreRegistry, self).register_lazy(
1380
key, module_name, member_name, help,
1381
info=fallback, override_existing=override_existing)
1384
credential_store_registry = CredentialStoreRegistry()
1387
class CredentialStore(object):
1388
"""An abstract class to implement storage for credentials"""
1390
def decode_password(self, credentials):
1391
"""Returns a clear text password for the provided credentials."""
1392
raise NotImplementedError(self.decode_password)
1394
def get_credentials(self, scheme, host, port=None, user=None, path=None,
1396
"""Return the matching credentials from this credential store.
1398
This method is only called on fallback credential stores.
1400
raise NotImplementedError(self.get_credentials)
1404
class PlainTextCredentialStore(CredentialStore):
1405
"""Plain text credential store for the authentication.conf file."""
1407
def decode_password(self, credentials):
1408
"""See CredentialStore.decode_password."""
1409
return credentials['password']
1412
credential_store_registry.register('plain', PlainTextCredentialStore,
1413
help=PlainTextCredentialStore.__doc__)
1414
credential_store_registry.default_key = 'plain'
1417
class BzrDirConfig(object):
1419
def __init__(self, bzrdir):
1420
self._bzrdir = bzrdir
1421
self._config = bzrdir._get_config()
1423
def set_default_stack_on(self, value):
1424
"""Set the default stacking location.
1426
It may be set to a location, or None.
1428
This policy affects all branches contained by this bzrdir, except for
1429
those under repositories.
1431
if self._config is None:
1432
raise errors.BzrError("Cannot set configuration in %s" % self._bzrdir)
1434
self._config.set_option('', 'default_stack_on')
1436
self._config.set_option(value, 'default_stack_on')
1438
def get_default_stack_on(self):
1439
"""Return the default stacking location.
1441
This will either be a location, or None.
1443
This policy affects all branches contained by this bzrdir, except for
1444
those under repositories.
1446
if self._config is None:
1448
value = self._config.get_option('default_stack_on')
1454
class TransportConfig(object):
1455
"""A Config that reads/writes a config file on a Transport.
1457
It is a low-level object that considers config data to be name/value pairs
1458
that may be associated with a section. Assigning meaning to the these
1459
values is done at higher levels like TreeConfig.
1462
def __init__(self, transport, filename):
1463
self._transport = transport
1464
self._filename = filename
1466
def get_option(self, name, section=None, default=None):
1467
"""Return the value associated with a named option.
1469
:param name: The name of the value
1470
:param section: The section the option is in (if any)
1471
:param default: The value to return if the value is not set
1472
:return: The value or default value
1474
configobj = self._get_configobj()
1476
section_obj = configobj
1479
section_obj = configobj[section]
1482
return section_obj.get(name, default)
1484
def set_option(self, value, name, section=None):
1485
"""Set the value associated with a named option.
1487
:param value: The value to set
1488
:param name: The name of the value to set
1489
:param section: The section the option is in (if any)
1491
configobj = self._get_configobj()
1493
configobj[name] = value
1495
configobj.setdefault(section, {})[name] = value
1496
self._set_configobj(configobj)
1498
def _get_config_file(self):
1500
return StringIO(self._transport.get_bytes(self._filename))
1501
except errors.NoSuchFile:
1504
def _get_configobj(self):
1505
return ConfigObj(self._get_config_file(), encoding='utf-8')
1507
def _set_configobj(self, configobj):
1508
out_file = StringIO()
1509
configobj.write(out_file)
1511
self._transport.put_file(self._filename, out_file)