953
821
except ImportError:
956
user_encoding = osutils.get_user_encoding()
957
realname = username = getpass.getuser().decode(user_encoding)
824
realname = username = getpass.getuser().decode(bzrlib.user_encoding)
958
825
except UnicodeDecodeError:
959
826
raise errors.BzrError("Can't decode username as %s." % \
827
bzrlib.user_encoding)
962
829
return realname, (username + '@' + socket.gethostname())
965
def parse_username(username):
966
"""Parse e-mail username and return a (name, address) tuple."""
967
match = re.match(r'(.*?)\s*<?([\w+.-]+@[\w+.-]+)>?', username)
969
return (username, '')
971
return (match.group(1), match.group(2))
974
832
def extract_email_address(e):
975
833
"""Return just the address part of an email string.
977
That is just the user@domain part, nothing else.
835
That is just the user@domain part, nothing else.
978
836
This part is required to contain only ascii characters.
979
837
If it can't be extracted, raises an error.
981
839
>>> extract_email_address('Jane Tester <jane@test.com>')
984
name, email = parse_username(e)
842
m = re.search(r'[\w+.-]+@[\w+.-]+', e)
986
844
raise errors.NoEmailInUsername(e)
990
848
class TreeConfig(IniBasedConfig):
991
849
"""Branch configuration data associated with its contents, not location"""
993
# XXX: Really needs a better name, as this is not part of the tree! -- mbp 20080507
995
850
def __init__(self, branch):
996
self._config = branch._get_config()
997
851
self.branch = branch
999
853
def _get_parser(self, file=None):
1000
854
if file is not None:
1001
855
return IniBasedConfig._get_parser(file)
1002
return self._config._get_configobj()
856
return self._get_config()
858
def _get_config(self):
860
obj = ConfigObj(self.branch.control_files.get('branch.conf'),
862
except errors.NoSuchFile:
863
obj = ConfigObj(encoding='utf=8')
1004
866
def get_option(self, name, section=None, default=None):
1005
867
self.branch.lock_read()
1007
return self._config.get_option(name, section, default)
869
obj = self._get_config()
871
if section is not None:
1009
877
self.branch.unlock()
1011
880
def set_option(self, value, name, section=None):
1012
881
"""Set a per-branch configuration option"""
1013
882
self.branch.lock_write()
1015
self._config.set_option(value, name, section)
884
cfg_obj = self._get_config()
889
obj = cfg_obj[section]
891
cfg_obj[section] = {}
892
obj = cfg_obj[section]
894
out_file = StringIO()
895
cfg_obj.write(out_file)
897
self.branch.control_files.put('branch.conf', out_file)
1017
899
self.branch.unlock()
1020
class AuthenticationConfig(object):
1021
"""The authentication configuration file based on a ini file.
1023
Implements the authentication.conf file described in
1024
doc/developers/authentication-ring.txt.
1027
def __init__(self, _file=None):
1028
self._config = None # The ConfigObj
1030
self._filename = authentication_config_filename()
1031
self._input = self._filename = authentication_config_filename()
1033
# Tests can provide a string as _file
1034
self._filename = None
1037
def _get_config(self):
1038
if self._config is not None:
1041
# FIXME: Should we validate something here ? Includes: empty
1042
# sections are useless, at least one of
1043
# user/password/password_encoding should be defined, etc.
1045
# Note: the encoding below declares that the file itself is utf-8
1046
# encoded, but the values in the ConfigObj are always Unicode.
1047
self._config = ConfigObj(self._input, encoding='utf-8')
1048
except configobj.ConfigObjError, e:
1049
raise errors.ParseConfigError(e.errors, e.config.filename)
1053
"""Save the config file, only tests should use it for now."""
1054
conf_dir = os.path.dirname(self._filename)
1055
ensure_config_dir_exists(conf_dir)
1056
self._get_config().write(file(self._filename, 'wb'))
1058
def _set_option(self, section_name, option_name, value):
1059
"""Set an authentication configuration option"""
1060
conf = self._get_config()
1061
section = conf.get(section_name)
1064
section = conf[section]
1065
section[option_name] = value
1068
def get_credentials(self, scheme, host, port=None, user=None, path=None,
1070
"""Returns the matching credentials from authentication.conf file.
1072
:param scheme: protocol
1074
:param host: the server address
1076
:param port: the associated port (optional)
1078
:param user: login (optional)
1080
:param path: the absolute path on the server (optional)
1082
:param realm: the http authentication realm (optional)
1084
:return: A dict containing the matching credentials or None.
1086
- name: the section name of the credentials in the
1087
authentication.conf file,
1088
- user: can't be different from the provided user if any,
1089
- scheme: the server protocol,
1090
- host: the server address,
1091
- port: the server port (can be None),
1092
- path: the absolute server path (can be None),
1093
- realm: the http specific authentication realm (can be None),
1094
- password: the decoded password, could be None if the credential
1095
defines only the user
1096
- verify_certificates: https specific, True if the server
1097
certificate should be verified, False otherwise.
1100
for auth_def_name, auth_def in self._get_config().items():
1101
if type(auth_def) is not configobj.Section:
1102
raise ValueError("%s defined outside a section" % auth_def_name)
1104
a_scheme, a_host, a_user, a_path = map(
1105
auth_def.get, ['scheme', 'host', 'user', 'path'])
1108
a_port = auth_def.as_int('port')
1112
raise ValueError("'port' not numeric in %s" % auth_def_name)
1114
a_verify_certificates = auth_def.as_bool('verify_certificates')
1116
a_verify_certificates = True
1119
"'verify_certificates' not boolean in %s" % auth_def_name)
1122
if a_scheme is not None and scheme != a_scheme:
1124
if a_host is not None:
1125
if not (host == a_host
1126
or (a_host.startswith('.') and host.endswith(a_host))):
1128
if a_port is not None and port != a_port:
1130
if (a_path is not None and path is not None
1131
and not path.startswith(a_path)):
1133
if (a_user is not None and user is not None
1134
and a_user != user):
1135
# Never contradict the caller about the user to be used
1140
# Prepare a credentials dictionary with additional keys
1141
# for the credential providers
1142
credentials = dict(name=auth_def_name,
1149
password=auth_def.get('password', None),
1150
verify_certificates=a_verify_certificates)
1151
# Decode the password in the credentials (or get one)
1152
self.decode_password(credentials,
1153
auth_def.get('password_encoding', None))
1154
if 'auth' in debug.debug_flags:
1155
trace.mutter("Using authentication section: %r", auth_def_name)
1158
if credentials is None:
1159
# No credentials were found in authentication.conf, try the fallback
1160
# credentials stores.
1161
credentials = credential_store_registry.get_fallback_credentials(
1162
scheme, host, port, user, path, realm)
1166
def set_credentials(self, name, host, user, scheme=None, password=None,
1167
port=None, path=None, verify_certificates=None,
1169
"""Set authentication credentials for a host.
1171
Any existing credentials with matching scheme, host, port and path
1172
will be deleted, regardless of name.
1174
:param name: An arbitrary name to describe this set of credentials.
1175
:param host: Name of the host that accepts these credentials.
1176
:param user: The username portion of these credentials.
1177
:param scheme: The URL scheme (e.g. ssh, http) the credentials apply
1179
:param password: Password portion of these credentials.
1180
:param port: The IP port on the host that these credentials apply to.
1181
:param path: A filesystem path on the host that these credentials
1183
:param verify_certificates: On https, verify server certificates if
1185
:param realm: The http authentication realm (optional).
1187
values = {'host': host, 'user': user}
1188
if password is not None:
1189
values['password'] = password
1190
if scheme is not None:
1191
values['scheme'] = scheme
1192
if port is not None:
1193
values['port'] = '%d' % port
1194
if path is not None:
1195
values['path'] = path
1196
if verify_certificates is not None:
1197
values['verify_certificates'] = str(verify_certificates)
1198
if realm is not None:
1199
values['realm'] = realm
1200
config = self._get_config()
1202
for section, existing_values in config.items():
1203
for key in ('scheme', 'host', 'port', 'path', 'realm'):
1204
if existing_values.get(key) != values.get(key):
1208
config.update({name: values})
1211
def get_user(self, scheme, host, port=None, realm=None, path=None,
1212
prompt=None, ask=False, default=None):
1213
"""Get a user from authentication file.
1215
:param scheme: protocol
1217
:param host: the server address
1219
:param port: the associated port (optional)
1221
:param realm: the realm sent by the server (optional)
1223
:param path: the absolute path on the server (optional)
1225
:param ask: Ask the user if there is no explicitly configured username
1228
:param default: The username returned if none is defined (optional).
1230
:return: The found user.
1232
credentials = self.get_credentials(scheme, host, port, user=None,
1233
path=path, realm=realm)
1234
if credentials is not None:
1235
user = credentials['user']
1241
# Create a default prompt suitable for most cases
1242
prompt = scheme.upper() + ' %(host)s username'
1243
# Special handling for optional fields in the prompt
1244
if port is not None:
1245
prompt_host = '%s:%d' % (host, port)
1248
user = ui.ui_factory.get_username(prompt, host=prompt_host)
1253
def get_password(self, scheme, host, user, port=None,
1254
realm=None, path=None, prompt=None):
1255
"""Get a password from authentication file or prompt the user for one.
1257
:param scheme: protocol
1259
:param host: the server address
1261
:param port: the associated port (optional)
1265
:param realm: the realm sent by the server (optional)
1267
:param path: the absolute path on the server (optional)
1269
:return: The found password or the one entered by the user.
1271
credentials = self.get_credentials(scheme, host, port, user, path,
1273
if credentials is not None:
1274
password = credentials['password']
1275
if password is not None and scheme is 'ssh':
1276
trace.warning('password ignored in section [%s],'
1277
' use an ssh agent instead'
1278
% credentials['name'])
1282
# Prompt user only if we could't find a password
1283
if password is None:
1285
# Create a default prompt suitable for most cases
1286
prompt = '%s' % scheme.upper() + ' %(user)s@%(host)s password'
1287
# Special handling for optional fields in the prompt
1288
if port is not None:
1289
prompt_host = '%s:%d' % (host, port)
1292
password = ui.ui_factory.get_password(prompt,
1293
host=prompt_host, user=user)
1296
def decode_password(self, credentials, encoding):
1298
cs = credential_store_registry.get_credential_store(encoding)
1300
raise ValueError('%r is not a known password_encoding' % encoding)
1301
credentials['password'] = cs.decode_password(credentials)
1305
class CredentialStoreRegistry(registry.Registry):
1306
"""A class that registers credential stores.
1308
A credential store provides access to credentials via the password_encoding
1309
field in authentication.conf sections.
1311
Except for stores provided by bzr itself, most stores are expected to be
1312
provided by plugins that will therefore use
1313
register_lazy(password_encoding, module_name, member_name, help=help,
1314
fallback=fallback) to install themselves.
1316
A fallback credential store is one that is queried if no credentials can be
1317
found via authentication.conf.
1320
def get_credential_store(self, encoding=None):
1321
cs = self.get(encoding)
1326
def is_fallback(self, name):
1327
"""Check if the named credentials store should be used as fallback."""
1328
return self.get_info(name)
1330
def get_fallback_credentials(self, scheme, host, port=None, user=None,
1331
path=None, realm=None):
1332
"""Request credentials from all fallback credentials stores.
1334
The first credentials store that can provide credentials wins.
1337
for name in self.keys():
1338
if not self.is_fallback(name):
1340
cs = self.get_credential_store(name)
1341
credentials = cs.get_credentials(scheme, host, port, user,
1343
if credentials is not None:
1344
# We found some credentials
1348
def register(self, key, obj, help=None, override_existing=False,
1350
"""Register a new object to a name.
1352
:param key: This is the key to use to request the object later.
1353
:param obj: The object to register.
1354
:param help: Help text for this entry. This may be a string or
1355
a callable. If it is a callable, it should take two
1356
parameters (registry, key): this registry and the key that
1357
the help was registered under.
1358
:param override_existing: Raise KeyErorr if False and something has
1359
already been registered for that key. If True, ignore if there
1360
is an existing key (always register the new value).
1361
:param fallback: Whether this credential store should be
1364
return super(CredentialStoreRegistry,
1365
self).register(key, obj, help, info=fallback,
1366
override_existing=override_existing)
1368
def register_lazy(self, key, module_name, member_name,
1369
help=None, override_existing=False,
1371
"""Register a new credential store to be loaded on request.
1373
:param module_name: The python path to the module. Such as 'os.path'.
1374
:param member_name: The member of the module to return. If empty or
1375
None, get() will return the module itself.
1376
:param help: Help text for this entry. This may be a string or
1378
:param override_existing: If True, replace the existing object
1379
with the new one. If False, if there is already something
1380
registered with the same key, raise a KeyError
1381
:param fallback: Whether this credential store should be
1384
return super(CredentialStoreRegistry, self).register_lazy(
1385
key, module_name, member_name, help,
1386
info=fallback, override_existing=override_existing)
1389
credential_store_registry = CredentialStoreRegistry()
1392
class CredentialStore(object):
1393
"""An abstract class to implement storage for credentials"""
1395
def decode_password(self, credentials):
1396
"""Returns a clear text password for the provided credentials."""
1397
raise NotImplementedError(self.decode_password)
1399
def get_credentials(self, scheme, host, port=None, user=None, path=None,
1401
"""Return the matching credentials from this credential store.
1403
This method is only called on fallback credential stores.
1405
raise NotImplementedError(self.get_credentials)
1409
class PlainTextCredentialStore(CredentialStore):
1410
"""Plain text credential store for the authentication.conf file."""
1412
def decode_password(self, credentials):
1413
"""See CredentialStore.decode_password."""
1414
return credentials['password']
1417
credential_store_registry.register('plain', PlainTextCredentialStore,
1418
help=PlainTextCredentialStore.__doc__)
1419
credential_store_registry.default_key = 'plain'
1422
class BzrDirConfig(object):
1424
def __init__(self, bzrdir):
1425
self._bzrdir = bzrdir
1426
self._config = bzrdir._get_config()
1428
def set_default_stack_on(self, value):
1429
"""Set the default stacking location.
1431
It may be set to a location, or None.
1433
This policy affects all branches contained by this bzrdir, except for
1434
those under repositories.
1436
if self._config is None:
1437
raise errors.BzrError("Cannot set configuration in %s" % self._bzrdir)
1439
self._config.set_option('', 'default_stack_on')
1441
self._config.set_option(value, 'default_stack_on')
1443
def get_default_stack_on(self):
1444
"""Return the default stacking location.
1446
This will either be a location, or None.
1448
This policy affects all branches contained by this bzrdir, except for
1449
those under repositories.
1451
if self._config is None:
1453
value = self._config.get_option('default_stack_on')
1459
class TransportConfig(object):
1460
"""A Config that reads/writes a config file on a Transport.
1462
It is a low-level object that considers config data to be name/value pairs
1463
that may be associated with a section. Assigning meaning to the these
1464
values is done at higher levels like TreeConfig.
1467
def __init__(self, transport, filename):
1468
self._transport = transport
1469
self._filename = filename
1471
def get_option(self, name, section=None, default=None):
1472
"""Return the value associated with a named option.
1474
:param name: The name of the value
1475
:param section: The section the option is in (if any)
1476
:param default: The value to return if the value is not set
1477
:return: The value or default value
1479
configobj = self._get_configobj()
1481
section_obj = configobj
1484
section_obj = configobj[section]
1487
return section_obj.get(name, default)
1489
def set_option(self, value, name, section=None):
1490
"""Set the value associated with a named option.
1492
:param value: The value to set
1493
:param name: The name of the value to set
1494
:param section: The section the option is in (if any)
1496
configobj = self._get_configobj()
1498
configobj[name] = value
1500
configobj.setdefault(section, {})[name] = value
1501
self._set_configobj(configobj)
1503
def _get_config_file(self):
1505
return StringIO(self._transport.get_bytes(self._filename))
1506
except errors.NoSuchFile:
1509
def _get_configobj(self):
1510
return ConfigObj(self._get_config_file(), encoding='utf-8')
1512
def _set_configobj(self, configobj):
1513
out_file = StringIO()
1514
configobj.write(out_file)
1516
self._transport.put_file(self._filename, out_file)