Add gpgme-tool.socket-path configuration to smtplib.conf.
authorW. Trevor King <wking@tremily.us>
Wed, 10 Oct 2012 13:18:41 +0000 (09:18 -0400)
committerW. Trevor King <wking@tremily.us>
Wed, 10 Oct 2012 13:18:41 +0000 (09:18 -0400)
bin/send-pgp-mime.py
pgp_mime/__init__.py
pgp_mime/crypt.py
pgp_mime/key.py
pgp_mime/pgp.py

index 64cde6930570175e375b1ae6f2fd503d4099ef82..2de5527b7b7da9a6cb7ca262704fa7b106fc9f85 100755 (executable)
@@ -145,6 +145,11 @@ if __name__ == '__main__':
         for attachment in args.attachment:
             body.attach(load_attachment(
                     filename=attachment, encoding=args.encoding))
+
+    config = _configparser.ConfigParser()
+    config.read(args.config)
+    client_params = _pgp_mime.get_client_params(config)
+
     if args.sign_as:
         signers = [args.sign_as]
     else:
@@ -152,13 +157,14 @@ if __name__ == '__main__':
     if 'encrypt' in args.mode:
         recipients = [email for name,email in _pgp_mime.email_targets(header)]
     if args.mode == 'sign':
-        body = _pgp_mime.sign(body, signers=signers, allow_default_signer=True)
+        body = _pgp_mime.sign(
+            body, signers=signers, allow_default_signer=True, **client_params)
     elif args.mode == 'encrypt':
-        body = _pgp_mime.encrypt(body, recipients=recipients)
+        body = _pgp_mime.encrypt(body, recipients=recipients, **client_params)
     elif args.mode == 'sign-encrypt':
         body = _pgp_mime.sign_and_encrypt(
             body, signers=signers, recipients=recipients,
-            allow_default_signer=True)
+            allow_default_signer=True, **client_params)
     elif args.mode == 'plain':
         pass
     else:
@@ -168,10 +174,8 @@ if __name__ == '__main__':
     if args.output:
         print(message.as_string())
     else:
-        config = _configparser.ConfigParser()
-        config.read(args.config)
-        params = _pgp_mime.get_smtp_params(config)
-        smtp = _pgp_mime.get_smtp(*params)
+        smtp_params = _pgp_mime.get_smtp_params(config)
+        smtp = _pgp_mime.get_smtp(*smtp_params)
         try:
             _pgp_mime.mail(message, smtp)
         finally:
index 98a457364e48dae425079ba793de24ffdc46b116..f18d0257019874dd62b0dd2d571231c8280d9e53 100644 (file)
@@ -30,6 +30,7 @@ LOG.setLevel(_logging.ERROR)
 LOG.addHandler(_logging.StreamHandler())
 
 
+from .crypt import get_client_params
 from .pgp import sign, encrypt, sign_and_encrypt, decrypt, verify
 from .email import (
     header_from_text, guess_encoding, encodedMIMEText, strip_bcc, append_text,
index 9c2a2d23e525d91d6f8b68db4b62925c0452fa97..7ba09c60c40c848686d3109d523db73424a27c66 100644 (file)
@@ -26,12 +26,41 @@ from . import LOG as _LOG
 from . import signature as _signature
 
 
-def get_client(**kwargs):
+SOCKET_PATH = _os_path.expanduser(_os_path.join('~', '.gnupg', 'S.gpgme-tool'))
+
+
+def get_client_params(config):
+    r"""Retrieve Assuan client paramters from a config file.
+
+    >>> from configparser import ConfigParser
+    >>> config = ConfigParser()
+    >>> config.read_string('\n'.join([
+    ...             '[gpgme-tool]',
+    ...             'socket-path: /tmp/S.gpgme-tool',
+    ...             ]))
+    >>> get_client_params(config)
+    {'socket_path': '/tmp/S.gpgme-tool'}
+    >>> config = ConfigParser()
+    >>> get_smtp_params(ConfigParser())
+    {'socket_path': None}
+    """
+    params = {'socket_path': None}
+    try:
+        params['socket_path'] = config.get('gpgme-tool', 'socket-path')
+    except _configparser.NoSectionError:
+        return params
+    except _configparser.NoOptionError:
+        pass
+    return params
+
+def get_client(socket_path=None):
+    if socket_path is None:
+        socket_path = socket_path
     logger = _logging.getLogger('{}.{}'.format(_LOG.name, 'pyassuan'))
     client = _client.AssuanClient(
         name='pgp-mime', logger=logger, use_sublogger=False,
         close_on_disconnect=True)
-    client.connect(socket_path='/tmp/gpgme-tool.sock')
+    client.connect(socket_path=socket_path)
     return client
 
 def disconnect(client):
@@ -63,7 +92,7 @@ def _write(fd, data):
 
 def sign_and_encrypt_bytes(data, signers=None, recipients=None,
                            always_trust=False, mode='detach',
-                           allow_default_signer=False):
+                           allow_default_signer=False, **kwargs):
     r"""Sign ``data`` with ``signers`` and encrypt to ``recipients``.
 
     Just sign (with a detached signature):
@@ -99,7 +128,7 @@ def sign_and_encrypt_bytes(data, signers=None, recipients=None,
     """
     input_read,input_write = _os.pipe()
     output_read,output_write = _os.pipe()
-    client = get_client()
+    client = get_client(**kwargs)
     try:
         hello(client)
         if signers:
@@ -142,7 +171,7 @@ def sign_and_encrypt_bytes(data, signers=None, recipients=None,
                 _os.close(fd)
     return d
 
-def decrypt_bytes(data):
+def decrypt_bytes(data, **kwargs):
     r"""Decrypt ``data``.
 
     >>> b = '\n'.join([
@@ -166,7 +195,7 @@ def decrypt_bytes(data):
     """
     input_read,input_write = _os.pipe()
     output_read,output_write = _os.pipe()
-    client = get_client()
+    client = get_client(**kwargs)
     try:
         hello(client)
         client.send_fds([input_read])
@@ -189,7 +218,7 @@ def decrypt_bytes(data):
                 _os.close(fd)
     return d
 
-def verify_bytes(data, signature=None, always_trust=False):
+def verify_bytes(data, signature=None, always_trust=False, **kwargs):
     r"""Verify a signature on ``data``, possibly decrypting first.
 
     These tests assume you didn't trust the distributed test key.
@@ -359,7 +388,7 @@ def verify_bytes(data, signature=None, always_trust=False):
     else:
         message_read = message_write = -1
         output_read,output_write = _os.pipe()
-    client = get_client()
+    client = get_client(**kwargs)
     verified = None
     signatures = []
     try:
index 00ba12784f11f8248b52c28c60dcb5fd74188778..8873335892d57b95278ffe715a3dc6e98549ab1e 100644 (file)
@@ -113,7 +113,7 @@ class Key (object):
         return int(self.fingerprint, 16)
 
 
-def lookup_keys(patterns=None):
+def lookup_keys(patterns=None, **kwargs):
     """Lookup keys matching any patterns listed in ``patterns``.
 
     >>> import pprint
@@ -144,7 +144,7 @@ def lookup_keys(patterns=None):
     [..., <Key 4332B6E3>, ...]
     """
     _LOG.debug('lookup key: {}'.format(patterns))
-    client = _crypt.get_client()
+    client = _crypt.get_client(**kwargs)
     parameters = []
     if patterns:
         args = [' '.join(patterns)]
index c9060114ea5a74e33578a33523a00c662d27ad7d..96aaff5d7f21fcaaf70e61186a3cb794902210c9 100644 (file)
@@ -27,7 +27,7 @@ from .email import email_targets as _email_targets
 from .email import strip_bcc as _strip_bcc
 
 
-def sign(message, signers=None, allow_default_signer=False):
+def sign(message, signers=None, **kwargs):
     r"""Sign a ``Message``, returning the signed version.
 
     multipart/signed
@@ -107,9 +107,7 @@ def sign(message, signers=None, allow_default_signer=False):
     """
     body = message.as_string().encode('us-ascii').replace(b'\n', b'\r\n')
     # use email.policy.SMTP once we get Python 3.3
-    signature = str(_sign_and_encrypt_bytes(
-            data=body, signers=signers,
-            allow_default_signer=allow_default_signer), 'us-ascii')
+    signature = str(_sign_and_encrypt_bytes(data=body, **kwargs), 'us-ascii')
     sig = _MIMEApplication(
         _data=signature,
         _subtype='pgp-signature; name="signature.asc"',
@@ -124,7 +122,7 @@ def sign(message, signers=None, allow_default_signer=False):
     msg['Content-Disposition'] = 'inline'
     return msg
 
-def encrypt(message, recipients=None, always_trust=True):
+def encrypt(message, recipients=None, **kwargs):
     r"""Encrypt a ``Message``, returning the encrypted version.
 
     multipart/encrypted
@@ -197,8 +195,7 @@ def encrypt(message, recipients=None, always_trust=True):
         recipients = [email for name,email in _email_targets(message)]
         _LOG.debug('extracted encryption recipients: {}'.format(recipients))
     encrypted = str(_sign_and_encrypt_bytes(
-            data=body, recipients=recipients,
-            always_trust=always_trust), 'us-ascii')
+            data=body, recipients=recipients, **kwargs), 'us-ascii')
     enc = _MIMEApplication(
         _data=encrypted,
         _subtype='octet-stream; name="encrypted.asc"',
@@ -219,8 +216,7 @@ def encrypt(message, recipients=None, always_trust=True):
     msg['Content-Disposition'] = 'inline'
     return msg
 
-def sign_and_encrypt(message, signers=None, recipients=None,
-                     always_trust=False, allow_default_signer=False):
+def sign_and_encrypt(message, signers=None, recipients=None, **kwargs):
     r"""Sign and encrypt a ``Message``, returning the encrypted version.
 
     multipart/encrypted
@@ -295,10 +291,10 @@ def sign_and_encrypt(message, signers=None, recipients=None,
     if recipients is None:
         recipients = [email for name,email in _email_targets(message)]
         _LOG.debug('extracted encryption recipients: {}'.format(recipients))
-    encrypted = str(_sign_and_encrypt_bytes(
-            data=body, signers=signers, recipients=recipients,
-            always_trust=always_trust,
-            allow_default_signer=allow_default_signer), 'us-ascii')
+    encrypted = str(
+        _sign_and_encrypt_bytes(
+            data=body, signers=signers, recipients=recipients, **kwargs),
+        'us-ascii')
     enc = _MIMEApplication(
         _data=encrypted,
         _subtype='octet-stream; name="encrypted.asc"',
@@ -372,7 +368,7 @@ def _get_signed_parts(message):
         raise ValueError('missing application/pgp-signature part')
     return (body, signature)
 
-def decrypt(message):
+def decrypt(message, **kwargs):
     r"""Decrypt a multipart/encrypted message.
 
     >>> from pgp_mime.email import encodedMIMEText
@@ -422,10 +418,10 @@ def decrypt(message):
     encrypted = body.get_payload(decode=True)
     if not isinstance(encrypted, bytes):
         encrypted = encrypted.encode('us-ascii')
-    decrypted,verified,result = _verify_bytes(encrypted)
+    decrypted,verified,result = _verify_bytes(encrypted, **kwargs)
     return _message_from_bytes(decrypted)
 
-def verify(message):
+def verify(message, **kwargs):
     r"""Verify a signature on ``message``, possibly decrypting first.
 
     >>> from pgp_mime.email import encodedMIMEText
@@ -623,6 +619,6 @@ def verify(message):
         sig_data = sig_data.encode('us-ascii')
     decrypted,verified,result = _verify_bytes(
         body.as_string().encode('us-ascii').replace(b'\n', b'\r\n'),
-        signature=sig_data)
+        signature=sig_data, **kwargs)
     # use email.policy.SMTP once we get Python 3.3
     return (_copy.deepcopy(body), verified, result)