annotate easyhg.py @ 737:4f3a8aa8d384 tip

Markdown
author Chris Cannam
date Wed, 28 Aug 2019 17:40:54 +0100
parents c59c17665162
children
rev   line source
Chris@427 1 # -*- coding: utf-8 -*-
Chris@427 2 #
Chris@427 3 # EasyMercurial
Chris@427 4 #
Chris@427 5 # Based on hgExplorer by Jari Korhonen
Chris@427 6 # Copyright (c) 2010 Jari Korhonen
Chris@560 7 # Copyright (c) 2010-2012 Chris Cannam
Chris@560 8 # Copyright (c) 2010-2012 Queen Mary, University of London
Chris@427 9 #
Chris@427 10 # This program is free software; you can redistribute it and/or
Chris@427 11 # modify it under the terms of the GNU General Public License as
Chris@427 12 # published by the Free Software Foundation; either version 2 of the
Chris@427 13 # License, or (at your option) any later version. See the file
Chris@427 14 # COPYING included with this distribution for more information.
Chris@427 15
Chris@503 16 import sys, os, stat, urllib, urllib2, urlparse, hashlib
Chris@427 17
Chris@438 18 from mercurial.i18n import _
Chris@433 19 from mercurial import ui, util, error
Chris@427 20 try:
Chris@427 21 from mercurial.url import passwordmgr
Chris@427 22 except:
Chris@427 23 from mercurial.httprepo import passwordmgr
Chris@427 24
Chris@427 25 # The value assigned here may be modified during installation, by
Chris@427 26 # replacing its default value with another one. We can't compare
Chris@427 27 # against its default value, because then the comparison text would
Chris@427 28 # get modified as well. So, compare using prefix only.
Chris@427 29 #
Chris@427 30 easyhg_import_path = 'NO_EASYHG_IMPORT_PATH'
Chris@427 31 if not easyhg_import_path.startswith('NO_'):
Chris@427 32 # We have an installation path: append it twice, once with
Chris@427 33 # the Python version suffixed
cannam@724 34 version_suffix = 'Py%d%d' % (sys.version_info[0], sys.version_info[1])
Chris@427 35 sys.path.append(easyhg_import_path + "/" + version_suffix)
Chris@427 36 sys.path.append(easyhg_import_path)
Chris@427 37
Chris@673 38 # Try to load the PyQt5 module that we need. If this fails, we should
Chris@427 39 # bail out later (in uisetup), because if we bail out now, Mercurial
Chris@427 40 # will just continue without us and report success. The invoking
Chris@427 41 # application needs to be able to discover whether the module load
Chris@427 42 # succeeded or not, so we need to ensure that Mercurial itself returns
Chris@427 43 # failure if it didn't.
Chris@427 44 #
Chris@427 45 easyhg_pyqt_ok = True
Chris@427 46 try:
Chris@673 47 from PyQt5 import QtCore, QtGui, QtWidgets
Chris@427 48 except ImportError:
Chris@427 49 easyhg_pyqt_ok = False
Chris@427 50 easyhg_qtapp = None
Chris@427 51
Chris@440 52 # These imports are optional, we just can't use the authfile (i.e.
Chris@438 53 # "remember this password") feature without them
Chris@438 54 #
Chris@437 55 easyhg_authfile_imports_ok = True
Chris@602 56
Chris@437 57 try:
Chris@437 58 from Crypto.Cipher import AES
Chris@602 59 except ImportError:
Chris@602 60 print "EasyHg: Failed to import Crypto.Cipher module required for authfile support (try installing PyCrypto?)"
Chris@602 61 easyhg_authfile_imports_ok = False
Chris@602 62
Chris@602 63 try:
Chris@437 64 import ConfigParser # Mercurial version won't write files
Chris@437 65 import base64
Chris@437 66 except ImportError:
Chris@602 67 print "EasyHg: Failed to import modules (ConfigParser, base64) required for authfile support"
Chris@437 68 easyhg_authfile_imports_ok = False
Chris@433 69
Chris@431 70
Chris@452 71 class EasyHgAuthStore(object):
Chris@431 72
Chris@452 73 def __init__(self, ui, url, user, passwd):
Chris@452 74
Chris@452 75 self.ui = ui
Chris@452 76 self.remote_url = url
Chris@452 77
Chris@452 78 self.user = user
Chris@452 79 self.passwd = passwd
Chris@452 80
Chris@452 81 self.auth_key = self.ui.config('easyhg', 'authkey')
Chris@452 82 self.auth_file = self.ui.config('easyhg', 'authfile')
Chris@452 83
Chris@452 84 self.use_auth_file = (easyhg_authfile_imports_ok and
Chris@673 85 self.auth_key and self.auth_file)
Chris@452 86
Chris@458 87 self.auth_config = None
Chris@458 88 self.auth_cipher = None
Chris@458 89 self.remember = False
Chris@458 90
Chris@452 91 if self.use_auth_file:
Chris@452 92 self.auth_file = os.path.expanduser(self.auth_file)
Chris@452 93 self.load_auth_data()
Chris@452 94
Chris@452 95 def save(self):
Chris@452 96 if self.use_auth_file:
Chris@452 97 self.save_auth_data()
Chris@452 98
Chris@673 99 def encrypt(self, utext):
Chris@452 100 iv = os.urandom(12)
Chris@673 101 text = utext.encode('utf-8')
Chris@452 102 text = '%s.%d.%s.easyhg' % (base64.b64encode(iv), len(text), text)
Chris@452 103 text += (16 - (len(text) % 16)) * ' '
Chris@673 104 cipher = AES.new(self.auth_key, AES.MODE_CBC, os.urandom(16))
Chris@673 105 ctext = base64.b64encode(cipher.encrypt(text))
Chris@452 106 return ctext
Chris@452 107
Chris@452 108 def decrypt(self, ctext):
Chris@448 109 try:
Chris@673 110 cipher = AES.new(self.auth_key, AES.MODE_CBC, os.urandom(16))
Chris@673 111 text = cipher.decrypt(base64.b64decode(ctext))
Chris@456 112 (iv, d, text) = text.partition('.')
Chris@456 113 (tlen, d, text) = text.partition('.')
Chris@673 114 return text[0:int(tlen)].decode('utf-8')
Chris@448 115 except:
Chris@452 116 self.ui.write("failed to decrypt/convert cached data!")
Chris@452 117 return ''
Chris@452 118
Chris@452 119 def argless_url(self):
Chris@452 120 parsed = urlparse.urlparse(self.remote_url)
Chris@452 121 return "%s://%s%s" % (parsed.scheme, parsed.netloc, parsed.path)
Chris@452 122
Chris@452 123 def pathless_url(self):
Chris@452 124 parsed = urlparse.urlparse(self.remote_url)
Chris@452 125 return "%s://%s" % (parsed.scheme, parsed.netloc)
Chris@452 126
Chris@452 127 def load_config(self):
Chris@453 128 if not self.auth_config:
Chris@453 129 self.auth_config = ConfigParser.RawConfigParser()
Chris@452 130 fp = None
Chris@452 131 try:
Chris@452 132 fp = open(self.auth_file)
Chris@452 133 except:
Chris@452 134 self.ui.write("unable to read authfile %s, ignoring\n" % self.auth_file)
Chris@452 135 return
Chris@452 136 self.auth_config.readfp(fp)
Chris@452 137 fp.close()
Chris@452 138
Chris@452 139 def save_config(self):
Chris@452 140 ofp = None
Chris@452 141 try:
Chris@452 142 ofp = open(self.auth_file, 'w')
Chris@452 143 except:
Chris@452 144 self.ui.write("failed to open authfile %s for writing\n" % self.auth_file)
Chris@448 145 raise
Chris@503 146 if os.name == 'posix':
Chris@452 147 try:
Chris@452 148 os.fchmod(ofp.fileno(), stat.S_IRUSR | stat.S_IWUSR)
Chris@452 149 except:
Chris@452 150 ofp.close()
Chris@452 151 self.ui.write("failed to set permissions on authfile %s\n" % self.auth_file)
Chris@452 152 raise
Chris@452 153 self.auth_config.write(ofp)
Chris@452 154 ofp.close()
Chris@434 155
Chris@452 156 def get_from_config(self, sect, key):
Chris@452 157 data = None
Chris@452 158 try:
Chris@452 159 data = self.auth_config.get(sect, key)
Chris@452 160 except (ConfigParser.NoOptionError, ConfigParser.NoSectionError):
Chris@452 161 pass
Chris@452 162 return data
Chris@436 163
Chris@452 164 def get_boolean_from_config(self, sect, key, deflt):
Chris@452 165 data = deflt
Chris@452 166 try:
Chris@452 167 data = self.auth_config.getboolean(sect, key)
Chris@452 168 except (ConfigParser.NoOptionError, ConfigParser.NoSectionError):
Chris@452 169 pass
Chris@452 170 return data
Chris@436 171
Chris@452 172 def set_to_config(self, sect, key, data):
Chris@452 173 if not self.auth_config.has_section(sect):
Chris@452 174 self.auth_config.add_section(sect)
Chris@452 175 self.auth_config.set(sect, key, data)
Chris@436 176
Chris@452 177 def remote_key(self, url, user):
Chris@452 178 # generate a "safe-for-config-file" key representing uri+user
Chris@459 179 # self.ui.write('generating remote_key for url %s and user %s\n' % (url, user))
Chris@452 180 s = '%s@@%s' % (url, user)
Chris@452 181 h = hashlib.sha1()
Chris@452 182 h.update(self.auth_key)
Chris@452 183 h.update(s)
Chris@452 184 hx = h.hexdigest()
Chris@452 185 return hx
Chris@452 186
Chris@452 187 def remote_user_key(self):
Chris@453 188 return self.remote_key(self.pathless_url(), '')
Chris@452 189
Chris@452 190 def remote_passwd_key(self):
Chris@452 191 return self.remote_key(self.pathless_url(), self.user)
Chris@452 192
Chris@452 193 def load_auth_data(self):
Chris@452 194
Chris@452 195 self.load_config()
Chris@452 196 if not self.auth_config: return
Chris@452 197
Chris@452 198 self.remember = self.get_boolean_from_config(
Chris@452 199 'preferences', 'remember', False)
Chris@452 200
Chris@452 201 if not self.user:
Chris@452 202 d = self.get_from_config('user', self.remote_user_key())
Chris@452 203 if d:
Chris@452 204 self.user = self.decrypt(d)
Chris@452 205
Chris@452 206 if self.user:
Chris@452 207 d = self.get_from_config('auth', self.remote_passwd_key())
Chris@452 208 if d:
Chris@452 209 self.passwd = self.decrypt(d)
Chris@452 210
Chris@452 211 def save_auth_data(self):
Chris@452 212
Chris@453 213 self.load_config()
Chris@452 214 if not self.auth_config: return
Chris@453 215
Chris@452 216 self.set_to_config('preferences', 'remember', self.remember)
Chris@452 217
Chris@459 218 # self.ui.write('aiming to store details for user %s\n' % self.user)
Chris@452 219
Chris@452 220 if self.remember and self.user:
Chris@452 221 d = self.encrypt(self.user)
Chris@452 222 self.set_to_config('user', self.remote_user_key(), d)
Chris@452 223 else:
Chris@452 224 self.set_to_config('user', self.remote_user_key(), '')
Chris@452 225
Chris@452 226 if self.remember and self.user and self.passwd:
Chris@452 227 d = self.encrypt(self.passwd)
Chris@452 228 self.set_to_config('auth', self.remote_passwd_key(), d)
Chris@452 229 elif self.user:
Chris@452 230 self.set_to_config('auth', self.remote_passwd_key(), '')
Chris@452 231
Chris@452 232 self.save_config()
Chris@452 233
Chris@452 234 class EasyHgAuthDialog(object):
Chris@452 235
Chris@452 236 auth_store = None
Chris@452 237
Chris@452 238 def __init__(self, ui, url, user, passwd):
Chris@452 239 self.auth_store = EasyHgAuthStore(ui, url, user, passwd)
Chris@452 240
Chris@470 241 def ask(self, repeat):
Chris@459 242
Chris@460 243 if self.auth_store.user and self.auth_store.passwd and self.auth_store.remember:
Chris@470 244 if not repeat:
Chris@459 245 return (self.auth_store.user, self.auth_store.passwd)
Chris@459 246
Chris@673 247 dialog = QtWidgets.QDialog()
Chris@673 248 layout = QtWidgets.QGridLayout()
Chris@452 249 dialog.setLayout(layout)
Chris@452 250
Chris@470 251 heading = _('Login required')
Chris@470 252 if repeat:
Chris@470 253 heading = _('Login failed: please try again')
Chris@470 254 label_text = _(('<h3>%s</h3><p>Please provide your login details for the repository at<br><code>%s</code>:') % (heading, self.auth_store.argless_url()))
Chris@673 255 layout.addWidget(QtWidgets.QLabel(label_text), 0, 0, 1, 2)
Chris@452 256
Chris@673 257 user_field = QtWidgets.QLineEdit()
Chris@452 258 if self.auth_store.user: user_field.setText(self.auth_store.user)
Chris@673 259 layout.addWidget(QtWidgets.QLabel(_('User:')), 1, 0)
Chris@452 260 layout.addWidget(user_field, 1, 1)
Chris@452 261
Chris@673 262 passwd_field = QtWidgets.QLineEdit()
Chris@673 263 passwd_field.setEchoMode(QtWidgets.QLineEdit.Password)
Chris@452 264 if self.auth_store.passwd: passwd_field.setText(self.auth_store.passwd)
Chris@673 265 layout.addWidget(QtWidgets.QLabel(_('Password:')), 2, 0)
Chris@452 266 layout.addWidget(passwd_field, 2, 1)
chris@656 267 user_field.textChanged.connect(passwd_field.clear)
Chris@452 268
Chris@452 269 remember_field = None
Chris@452 270 if self.auth_store.use_auth_file:
Chris@673 271 remember_field = QtWidgets.QCheckBox()
Chris@452 272 remember_field.setChecked(self.auth_store.remember)
Chris@452 273 remember_field.setText(_('Remember these details while EasyMercurial is running'))
Chris@452 274 layout.addWidget(remember_field, 3, 1)
Chris@673 275 warning_field = QtWidgets.QLabel()
Chris@461 276 warning_field.setText(_('<qt><i><small>Do not use this option if anyone else has access to your computer!</small></i><br></qt>'))
Chris@457 277 warning_field.hide()
chris@656 278 remember_field.clicked.connect(warning_field.show)
Chris@457 279 layout.addWidget(warning_field, 4, 1, QtCore.Qt.AlignRight)
Chris@452 280
Chris@673 281 bb = QtWidgets.QDialogButtonBox()
Chris@452 282 ok = bb.addButton(bb.Ok)
Chris@452 283 cancel = bb.addButton(bb.Cancel)
Chris@452 284 cancel.setDefault(False)
Chris@452 285 cancel.setAutoDefault(False)
Chris@452 286 ok.setDefault(True)
chris@656 287 ok.clicked.connect(dialog.accept)
chris@656 288 cancel.clicked.connect(dialog.reject)
Chris@457 289 layout.addWidget(bb, 5, 0, 1, 2)
Chris@452 290
Chris@452 291 dialog.setWindowTitle(_('EasyMercurial: Login'))
Chris@452 292 dialog.show()
Chris@452 293
Chris@452 294 if not self.auth_store.user:
Chris@452 295 user_field.setFocus(True)
Chris@452 296 elif not self.auth_store.passwd:
Chris@452 297 passwd_field.setFocus(True)
Chris@452 298 else:
Chris@452 299 ok.setFocus(True)
Chris@452 300
Chris@452 301 dialog.raise_()
Chris@452 302 ok = dialog.exec_()
Chris@452 303 if not ok:
Chris@673 304 raise error.Abort(_('password entry cancelled'))
Chris@452 305
Chris@452 306 self.auth_store.user = user_field.text()
Chris@452 307 self.auth_store.passwd = passwd_field.text()
Chris@452 308
Chris@452 309 if remember_field:
Chris@452 310 self.auth_store.remember = remember_field.isChecked()
Chris@452 311
Chris@452 312 self.auth_store.save()
Chris@452 313
Chris@452 314 return (self.auth_store.user, self.auth_store.passwd)
Chris@438 315
Chris@440 316
Chris@440 317 def uisetup(ui):
Chris@440 318 if not easyhg_pyqt_ok:
Chris@673 319 raise error.Abort(_('Failed to load PyQt5 module required by easyhg.py'))
Chris@440 320 global easyhg_qtapp
Chris@673 321 easyhg_qtapp = QtWidgets.QApplication([])
Chris@440 322
Chris@440 323 def monkeypatch_method(cls):
Chris@440 324 def decorator(func):
Chris@440 325 setattr(cls, func.__name__, func)
Chris@440 326 return func
Chris@440 327 return decorator
Chris@440 328
Chris@440 329 orig_find = passwordmgr.find_user_password
Chris@440 330
Chris@427 331 @monkeypatch_method(passwordmgr)
Chris@427 332 def find_user_password(self, realm, authuri):
Chris@427 333
Chris@459 334 if not hasattr(self, '__easyhg_last'):
Chris@459 335 self.__easyhg_last = None
Chris@459 336
Chris@427 337 if not self.ui.interactive():
Chris@427 338 return orig_find(self, realm, authuri)
Chris@427 339 if not easyhg_pyqt_ok:
Chris@427 340 return orig_find(self, realm, authuri)
Chris@427 341
Chris@673 342 mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
Chris@673 343 authinfo = mgr.find_user_password(realm, authuri)
Chris@427 344 user, passwd = authinfo
Chris@427 345
Chris@470 346 repeat = False
Chris@459 347
Chris@459 348 if (realm, authuri) == self.__easyhg_last:
Chris@459 349 # If we are called again just after identical previous
Chris@459 350 # request, then the previously returned auth must have been
Chris@459 351 # wrong. So we note this to force password prompt (and avoid
Chris@459 352 # reusing bad password indefinitely). Thanks to
Chris@459 353 # mercurial_keyring (Marcin Kasperski) for this logic
Chris@470 354 repeat = True
Chris@470 355
Chris@470 356 if user and passwd and not repeat:
Chris@470 357 return orig_find(self, realm, authuri)
Chris@427 358
Chris@452 359 dialog = EasyHgAuthDialog(self.ui, authuri, user, passwd)
Chris@427 360
Chris@470 361 (user, passwd) = dialog.ask(repeat)
Chris@433 362
Chris@470 363 self.add_password(realm, authuri, user, passwd)
Chris@459 364 self.__easyhg_last = (realm, authuri)
Chris@427 365 return (user, passwd)
Chris@427 366
Chris@427 367