本文整理汇总了Python中goodcrypto.utils.log_file.LogFile.write_and_flush方法的典型用法代码示例。如果您正苦于以下问题:Python LogFile.write_and_flush方法的具体用法?Python LogFile.write_and_flush怎么用?Python LogFile.write_and_flush使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类goodcrypto.utils.log_file.LogFile
的用法示例。
在下文中一共展示了LogFile.write_and_flush方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: log_message
# 需要导入模块: from goodcrypto.utils.log_file import LogFile [as 别名]
# 或者: from goodcrypto.utils.log_file.LogFile import write_and_flush [as 别名]
def log_message(message):
''' Log a message to the local log. '''
global log
if log is None:
log = LogFile()
log.write_and_flush(message)
示例2: log_message
# 需要导入模块: from goodcrypto.utils.log_file import LogFile [as 别名]
# 或者: from goodcrypto.utils.log_file.LogFile import write_and_flush [as 别名]
def log_message(message):
'''
Log a message.
>>> from syr.log import BASE_LOG_DIR
>>> from syr.user import whoami
>>> log_message('test')
>>> os.path.exists(os.path.join(BASE_LOG_DIR, whoami(), 'goodcrypto.mail.message.utils.log'))
True
'''
global _log
if _log is None:
_log = LogFile()
_log.write_and_flush(message)
示例3: log_message
# 需要导入模块: from goodcrypto.utils.log_file import LogFile [as 别名]
# 或者: from goodcrypto.utils.log_file.LogFile import write_and_flush [as 别名]
def log_message(message):
'''
Log a message to the local log.
>>> import os.path
>>> from syr.log import BASE_LOG_DIR
>>> from syr.user import whoami
>>> log_message('test')
>>> os.path.exists(os.path.join(BASE_LOG_DIR, whoami(), 'goodcrypto.mail.user_keys.log'))
True
'''
global log
if log is None:
log = LogFile()
log.write_and_flush(message)
示例4: CryptoMessage
# 需要导入模块: from goodcrypto.utils.log_file import LogFile [as 别名]
# 或者: from goodcrypto.utils.log_file.LogFile import write_and_flush [as 别名]
#.........这里部分代码省略.........
def get_error_tag(self):
'''
Returns the error tags as a string to be added to the email_message text.
>>> crypto_message = CryptoMessage()
>>> crypto_message.set_error_tag('test error tag')
>>> tag = crypto_message.get_error_tag()
>>> tag == 'test error tag'
True
'''
if self.error_tags is None:
error_tag = ''
else:
error_tag = '\n'.join(self.error_tags)
if self.DEBUGGING: self.log_message("error tag:\n{}".format(error_tag))
return error_tag
def set_error_tag(self, new_tag):
'''
Sets the error tag to be added to the email_message text.
>>> crypto_message = CryptoMessage()
>>> crypto_message.set_error_tag(None)
>>> tag = crypto_message.get_error_tag()
>>> tag == ''
True
'''
if new_tag is None:
if self.DEBUGGING: self.log_message("tried to set blank error tag")
elif new_tag == '':
self.error_tags = []
if self.DEBUGGING: self.log_message("reset error tags")
else:
if is_string(new_tag):
new_tag = new_tag.strip('\n')
self.error_tags = [new_tag]
else:
self.error_tags = new_tag
if self.DEBUGGING: self.log_message("new tag:\n{}".format(self.error_tags))
def add_error_tag_once(self, new_tag):
'''
Add new error tag only if it isn't already in the error tag.
>>> crypto_message = CryptoMessage()
>>> crypto_message.add_error_tag_once(None)
>>> tag = crypto_message.get_error_tag().strip()
>>> tag == ''
True
'''
if new_tag is None:
pass
elif self.error_tags is None or new_tag not in self.error_tags:
new_tag = new_tag.strip('\n')
if len(self.error_tags) <= 0:
if self.DEBUGGING: self.log_message("adding to an empty error tag:\n{}".format(new_tag))
self.error_tags = [new_tag]
else:
self.log_message("adding to error tag:\n{}".format(new_tag))
if new_tag.startswith('.'):
self.error_tags[len(self.tags) - 1] += new_tag
else:
self.error_tags.append(new_tag)
def log_exception(self, exception):
'''
Log the message to the local and Exception logs.
>>> import os.path
>>> from syr.log import BASE_LOG_DIR
>>> from syr.user import whoami
>>> CryptoMessage().log_exception('test message')
>>> os.path.exists(os.path.join(BASE_LOG_DIR, whoami(), 'goodcrypto.mail.message.crypto_message.log'))
True
'''
self.log_message(exception)
record_exception(message=exception)
def log_message(self, message):
'''
Log the message to the local log.
>>> import os.path
>>> from syr.log import BASE_LOG_DIR
>>> from syr.user import whoami
>>> CryptoMessage().log_message('test')
>>> os.path.exists(os.path.join(BASE_LOG_DIR, whoami(), 'goodcrypto.mail.message.crypto_message.log'))
True
'''
if self.log is None:
self.log = LogFile()
self.log.write_and_flush(message)
示例5: RetrieveKey
# 需要导入模块: from goodcrypto.utils.log_file import LogFile [as 别名]
# 或者: from goodcrypto.utils.log_file.LogFile import write_and_flush [as 别名]
#.........这里部分代码省略.........
def __init__(self, email, encryption_name, keyserver, key_id, user_initiated_search):
'''
>>> # In honor of Werner Koch, developer of gpg.
>>> email = '[email protected]'
>>> crypto_name = 'GPG'
>>> srk_class = RetrieveKey(email, crypto_name, 'pgp.mit.edu', 'F2AD85AC1E42B367', '[email protected]')
>>> srk_class = RetrieveKey(None, crypto_name, 'pgp.mit.edu', 'F2AD85AC1E42B367', '[email protected]')
>>> srk_class = RetrieveKey(email, None, 'pgp.mit.edu', 'F2AD85AC1E42B367', '[email protected]')
>>> srk_class = RetrieveKey(email, crypto_name, None, 'F2AD85AC1E42B367', '[email protected]')
>>> srk_class = RetrieveKey(None, None, None, None, None)
'''
self.log = LogFile()
self.email = email
self.encryption_name = encryption_name
self.keyserver = keyserver
self.key_id = key_id
self.user_initiated_search = user_initiated_search
self.key_plugin = None
def start_retrieval(self):
'''
Queue retrieving key from the keyserver. When the job finishes, associated
database entries will be made from another queued job which is dependent on
the key retrieval's job.
Test extreme case.
>>> rk = RetrieveKey(None, None, None, None, None)
>>> rk.start_retrieval()
False
'''
if self.email == UNKNOWN_EMAIL:
email_or_fingerprint = self.key_id
else:
email_or_fingerprint = self.email
try:
result_ok = (self.email is not None and
self.encryption_name is not None and
self.keyserver is not None and
self.key_id is not None and
self.user_initiated_search is not None)
if result_ok:
self.key_plugin = KeyFactory.get_crypto(
self.encryption_name, crypto_software.get_key_classname(self.encryption_name))
result_ok = self.key_plugin is not None
if result_ok:
from goodcrypto.mail.keyserver_utils import add_contact_records
self.key_plugin.retrieve_key(self.key_id, self.keyserver)
retrieve_job = self.key_plugin.get_job()
queue = self.key_plugin.get_queue()
if queue is None or retrieve_job is None:
self.log_message('unable to queue job to add contact recs for {}'.format(
self.key_id))
result_ok = False
else:
self.log_message('starting to add contact records for {} (after job: {})'.format(
self.key_id, retrieve_job.get_id()))
add_contact_records(email_or_fingerprint,
self.encryption_name,
self.user_initiated_search,
retrieve_job.get_id(), queue.key)
result_ok = True
else:
result_ok = False
self.log_message('unable to queue retrieving {} key for {}'.format(
self.encryption_name, self.key_id))
except Exception as exception:
result_ok = False
record_exception()
self.log_message('EXCEPTION - see syr.exception.log for details')
self.log_message('finished queueing retreival for {} ok: {}'.format(email_or_fingerprint, result_ok))
return result_ok
def log_message(self, message):
'''
Log the message to the local log.
>>> import os.path
>>> from syr.log import BASE_LOG_DIR
>>> from syr.user import whoami
>>> RetrieveKey(None, None, None, None, None).log_message('test')
>>> os.path.exists(os.path.join(BASE_LOG_DIR, whoami(), 'goodcrypto.mail.retrieve_key.log'))
True
'''
if self.log is None:
self.log = LogFile()
self.log.write_and_flush(message)
示例6: Validator
# 需要导入模块: from goodcrypto.utils.log_file import LogFile [as 别名]
# 或者: from goodcrypto.utils.log_file.LogFile import write_and_flush [as 别名]
#.........这里部分代码省略.........
def is_message_valid(self):
'''
Returns true if the message is parsable, else false.
If a MIME message is not parsable, you should still be able to process it.
As we find different errors in messages, we should make sure this
method catches them.
>>> from goodcrypto_tests.mail.message_utils import get_basic_email_message
>>> good_message = get_basic_email_message()
>>> validator = Validator(good_message)
>>> validator.is_message_valid()
True
'''
is_valid = False
self.why = None
if self.email_message is None:
raise MessageException('Message is None')
else:
try:
self.email_message.write_to(StringIO())
if Validator.DEBUGGING:
self.log_message("message after check:\n{}".format(self.email_message.to_string()))
self._check_content(self.email_message)
is_valid = True
except Exception:
is_valid = False
# we explicitly want to catch everything here, even NPE
record_exception()
self.log_message('EXCEPTION - see syr.exception.log for details')
self.log_message('message is valid: {}'.format(is_valid))
return is_valid
def _check_content(self, part):
'''
Make sure we can read the content.
>>> from goodcrypto_tests.mail.message_utils import get_basic_email_message
>>> good_message = get_basic_email_message()
>>> validator = Validator(good_message)
>>> validator._check_content(validator.email_message)
'''
content_type = part.get_header('Content-Type')
self.log_message("MIME part content type: {}".format(content_type))
content = part.get_content()
if isinstance(content, MIMEMultipart):
count = 0
parts = content
for sub_part in parts:
self._check_content(sub_part)
count += 1
self.log_message('parts in message: {}'.format(count))
if count != parts.getCount():
self.why = "Unable to read all content. Reported: '{}', read: {}".format(
parts.getCount(), count)
raise MessageException(self.why)
def get_why(self):
'''
Gets why a message is invalid. Returns null if the message is valid.
>>> from goodcrypto_tests.mail.message_utils import get_basic_email_message
>>> good_message = get_basic_email_message()
>>> validator = Validator(good_message)
>>> validator.get_why() is None
True
'''
return self.why
def log_message(self, message):
'''
Log the message to the local log.
>>> import os.path
>>> from syr.log import BASE_LOG_DIR
>>> from syr.user import whoami
>>> from goodcrypto_tests.mail.message_utils import get_basic_email_message
>>> good_message = get_basic_email_message()
>>> validator = Validator(good_message)
>>> validator.log_message('test')
>>> os.path.exists(os.path.join(BASE_LOG_DIR, whoami(), 'goodcrypto.mail.message.validator.log'))
True
'''
if self.log is None:
self.log = LogFile()
self.log.write_and_flush(message)
示例7: HeaderKeys
# 需要导入模块: from goodcrypto.utils.log_file import LogFile [as 别名]
# 或者: from goodcrypto.utils.log_file.LogFile import write_and_flush [as 别名]
#.........这里部分代码省略.........
record_exception()
self.log_message('EXCEPTION - see syr.exception.log for details')
return matches, error
def _import_accepted_crypto_software(self, from_user, crypto_message):
'''
Import the encryption software the contact can use (internal use only).
'''
accepted_crypto_packages = crypto_message.get_accepted_crypto_software()
self.update_accepted_crypto(from_user, accepted_crypto_packages)
return accepted_crypto_packages
def update_accepted_crypto(self, email, encryption_software_list):
''' Update the list of encryption software accepted by user.
'''
if email is None:
self.log_message("email not defined so no need to update accepted crypto")
elif encryption_software_list is None or len(encryption_software_list) <= 0:
self.log_message('no encryption programs defined for {}'.format(email))
else:
contact = contacts.get(email)
if contact is None:
# if the contact doesn't exist, then add them with the first encryption program
encryption_program = encryption_software_list[0]
contact = contacts.add(email, encryption_program, source=MESSAGE_HEADER)
self.log_message("added {} to contacts".format(email))
# associate each encryption program in the list with this contact
for encryption_program in encryption_software_list:
try:
contacts_crypto = contacts.get_contacts_crypto(email, encryption_program)
if contacts_crypto is None:
encryption_software = crypto_software.get(encryption_program)
if encryption_software is None:
self.log_message('{} encryption software unknown'.format(encryption_program))
self.log_message(
'unable to add contacts crypt for {} using {} encryption software unknown'.format(email, encryption_program))
else:
contacts_crypto = contacts.add_contacts_crypto(
contact=contact, encryption_software=encryption_software, source=MESSAGE_HEADER)
except Exception:
record_exception()
self.log_message('EXCEPTION - see syr.exception.log for details')
def update_fingerprint(self, email, encryption_name, new_fingerprint, verified=False):
'''
Set the fingerprint for the encryption software for this email.
If the fingerprint doesn't match the crypto's fingerprint, it won't
be saved in the database.
'''
if email is None or encryption_name is None:
result_ok = False
self.log_message("missing data to save {} fingerprint for {}".format(encryption_name, email))
else:
self.log_message('updating {} fingerprint for {}'.format(encryption_name, email))
contacts_crypto = contacts.get_contacts_crypto(email, encryption_name=encryption_name)
if contacts_crypto is None:
contact = contacts.add(email, encryption_name, source=MESSAGE_HEADER)
contacts_crypto = contacts.get_contacts_crypto(email, encryption_name=encryption_name)
if contacts_crypto is None:
result_ok = False
self.log_message("unable to save contact's {} fingerprint".format(encryption_name))
else:
try:
need_update = False
if new_fingerprint != contacts_crypto.fingerprint:
contacts_crypto.fingerprint = new_fingerprint
need_update = True
self.log_message("contacts_crypto fingerprint: {}".format(contacts_crypto.fingerprint))
if contacts_crypto.verified != verified:
contacts_crypto.verified = verified
need_update = True
self.log_message('Updated verification status: {}'.format(verified))
if need_update:
contacts_crypto.save()
self.log_message('saved changes')
result_ok = True
except:
self.log_message('EXCEPTION - see syr.exception.log for details')
record_exception()
result_ok = False
return result_ok
def log_message(self, message):
'''
Log the message to the local log.
'''
if self.log is None:
self.log = LogFile()
self.log.write_and_flush(message)
示例8: Debundle
# 需要导入模块: from goodcrypto.utils.log_file import LogFile [as 别名]
# 或者: from goodcrypto.utils.log_file.LogFile import write_and_flush [as 别名]
#.........这里部分代码省略.........
except:
self.log_message('bad part of message discarded')
self.log_message('EXCEPTION - see syr.exception.log for details')
record_exception()
result_ok = True
self.log_message('good bundled message contains {} inner message(s)'.format(self.messages_sent))
except CryptoException as crypto_exception:
raise MessageException(value=crypto_exception.value)
except MessageException as message_exception:
raise MessageException(value=message_exception.value)
except:
record_exception()
self.log_message('EXCEPTION - see syr.exception.log for details')
result_ok = False
return result_ok
def create_inner_message(self, content):
''' Create the inner crypto message. '''
inner_crypto_message = None
try:
original_message, addendum = parse_bundled_message(content)
if original_message is None or len(original_message.strip()) <= 0 or addendum is None:
self.log_message('discarded padding')
else:
sender = addendum[mime_constants.FROM_KEYWORD]
recipient = addendum[mime_constants.TO_KEYWORD]
if sender is None or recipient is None:
self.log_message('discarded badly formatted message')
else:
if self.DEBUGGING: self.log_message('DEBUG: content of part: {}'.format(content))
metadata_crypted_with = self.crypto_message.get_metadata_crypted_with()
inner_crypto_message = CryptoMessage(EmailMessage(original_message))
inner_crypto_message.set_smtp_sender(sender)
inner_crypto_message.set_smtp_recipient(recipient)
inner_crypto_message.set_metadata_crypted(True)
inner_crypto_message.set_metadata_crypted_with(metadata_crypted_with)
self.log_message('created message from {}'.format(sender))
self.log_message('created message to {}'.format(recipient))
self.log_message("metadata decrypted with: {}".format(
inner_crypto_message.get_metadata_crypted_with()))
if self.DEBUGGING: self.log_message('original message: {}'.format(original_message))
except:
inner_crypto_message = None
record_exception()
self.log_message('EXCEPTION - see syr.exception.log for details')
return inner_crypto_message
def decrypt_and_send_message(self, inner_crypto_message):
''' Decrypt and send a message. '''
result_ok = False
sender = recipient = message = decrypted_crypto_message = None
try:
decrypt = Decrypt(inner_crypto_message)
decrypted_crypto_message = decrypt.process_message()
sender = decrypted_crypto_message.smtp_sender()
recipient = decrypted_crypto_message.smtp_recipient()
message = decrypted_crypto_message.get_email_message().get_message().as_string()
self.log_message('message to {} decrypted: {}'.format(
recipient, decrypted_crypto_message.is_crypted()))
if send_message(sender, recipient, message):
result_ok = True
self.log_message('sent message to {}'.format(recipient))
if self.DEBUGGING: self.log_message('DEBUG: message:\n{}'.format(message))
else:
result_ok = False
except AttributeError as attribute_error:
result_ok = False
self.log_message(attribute_error)
except:
result_ok = False
record_exception()
self.log_message('EXCEPTION - see syr.exception.log for details')
if not result_ok:
report_message_undeliverable(message, sender)
self.log_message('reported message undeliverable')
# we're returning the decrypted message to allow tests to verify everything went smoothly
return result_ok, decrypted_crypto_message
def log_message(self, message):
'''
Log the message to the local log.
'''
if self.log is None:
self.log = LogFile()
self.log.write_and_flush(message)
示例9: GPGPlugin
# 需要导入模块: from goodcrypto.utils.log_file import LogFile [as 别名]
# 或者: from goodcrypto.utils.log_file.LogFile import write_and_flush [as 别名]
#.........这里部分代码省略.........
def is_good_result(self):
'''
Return if the exit code is a good result
'''
return gpg_constants.GOOD_RESULT
def is_error_result(self):
'''
Return if the exit code is an error
'''
return gpg_constants.ERROR_RESULT
def is_timedout_result(self):
'''
Return if job timed out
'''
return gpg_constants.TIMED_OUT_RESULT
def log_data(self, data, message="data"):
''' Log data. '''
if self.DEBUGGING:
self.log_message("{}:\n{}".format(message, data))
def log_message(self, message):
''' Log a message. '''
if self.log is None:
self.log = LogFile()
self.log.write_and_flush(message)
def _sign_and_encrypt_now(self, data, from_user_id, to_user_id, passphrase, clear_sign, args):
'''
Sign and encrypt the data now. Only used internally. Use one of the public
functions to sign, encrypt, and armor data, and finally clear sign it.
'''
encrypted_data = error_message = None
try:
if data is None:
error_message = 'Could not sign and encrypt because there is no data.'
self.log_message(error_message)
elif from_user_id is None:
error_message = 'Could not sign and encrypt because there is no FROM user id.'
self.log_message(error_message)
elif to_user_id is None:
error_message = 'Could not sign and encrypt because there is no TO user id.'
self.log_message(error_message)
elif passphrase is None:
error_message = 'Could not sign and encrypt because there is no passphrase.'
self.log_message(error_message)
else:
self.log_data(data)
result_code, gpg_output, gpg_error = self.gpg_command(
args, passphrase=passphrase, data=data, wait_for_results=True)
self.log_message('results after signing, encrypting, and armoring: {}'.format(result_code))
if result_code == gpg_constants.GOOD_RESULT:
if clear_sign:
encrypted_data, error_message = self.sign(gpg_output, from_user_id, passphrase)
self.log_message('results after clear signing: {}'.format(len(encrypted_data) > 0))
示例10: Filter
# 需要导入模块: from goodcrypto.utils.log_file import LogFile [as 别名]
# 或者: from goodcrypto.utils.log_file.LogFile import write_and_flush [as 别名]
#.........这里部分代码省略.........
self.log_message('sent notice to {} about {}'.format(to_address, error_message))
except:
record_exception()
self.log_message('EXCEPTION - see syr.exception.log for details')
return result_ok
def reject_message(self, error_message, message=None):
'''
Reject a message that had an unexpected error and return the to address.
>>> # This message will fail if testing on dev system
>>> to_address = get_admin_email()
>>> filter = Filter('root', 'root', 'bad message')
>>> filter.reject_message('Unknown message') == to_address
True
'''
try:
if message is None:
message = self.out_message
if email_in_domain(self.sender):
to_address = self.sender
subject = i18n('Undelivered Mail: Unable to send message')
elif email_in_domain(self.recipient):
to_address = self.recipient
subject = i18n('Error: Unable to receive message')
else:
to_address = get_admin_email()
subject = i18n('Message rejected.')
notice = '{}'.format(error_message)
if message is not None:
notice += '\n\n===================\n{}'.format(message)
notify_user(to_address, subject, notice)
except:
raise
return to_address
def bounce_outbound_message(self, error_message):
''' Bounce a message that a local user originated. '''
self.log_message(error_message)
self.log_message('EXCEPTION - see syr.exception.log for details')
record_exception()
subject = i18n('{} - Undelivered Mail: Unable to protect message'.format(TAG_ERROR))
utils.bounce_message(self.in_message, self.sender, subject, error_message)
def wrap_inbound_message(self, error_message, debundled_message):
''' Wrap an inbound message that had a serious error. '''
self.log_message(error_message)
body = error_message
try:
processed_message = debundled_message.crypto_message
error_tags = processed_message.get_error_tags()
if error_tags and len(error_tags) > 0:
for tag in error_tags:
body += '\n{}'.format(tag)
if options.add_long_tags():
long_tags = processed_message.get_tags()
if long_tags and len(long_tags) > 0:
for tag in long_tags:
body += '\n{}'.format(tag)
except:
pass
subject = i18n('{} - Unable to decrypt message'.format(TAG_ERROR))
utils.bounce_message(self.in_message, self.recipient, subject, body)
def drop_message(self, error_message):
''' Drop a message that we shouldn't process from a remote user. '''
self.log_message(error_message)
self.log_message('EXCEPTION - see syr.exception.log for details')
record_exception()
subject = i18n('{} - Unable to decrypt message'.format(TAG_ERROR))
utils.drop_message(self.in_message, self.recipient, subject, error_message)
def log_message(self, message):
'''
Record debugging messages.
>>> import os.path
>>> from syr.log import BASE_LOG_DIR
>>> from syr.user import whoami
>>> filter = Filter('[email protected]', ['[email protected]'], 'message')
>>> filter.log_message('test')
>>> os.path.exists(os.path.join(BASE_LOG_DIR, whoami(), 'goodcrypto.mail.message.filter.log'))
True
'''
if self.log is None:
self.log = LogFile()
self.log.write_and_flush(message)
示例11: Encrypt
# 需要导入模块: from goodcrypto.utils.log_file import LogFile [as 别名]
# 或者: from goodcrypto.utils.log_file.LogFile import write_and_flush [as 别名]
#.........这里部分代码省略.........
result_ok = self._clear_sign_message_with_keys(crypto, from_user_id, passcode)
self._log_message('signed message: {}'.format(result_ok))
else:
# the message hasn't been signed, but we have
# successfully processed it
self.crypto_message.set_filtered(True)
except Exception:
result_ok = False
record_exception()
self._log_message('EXCEPTION - see syr.exception.log for details')
return result_ok
def _clear_sign_message_with_keys(self, crypto, from_user_id, passcode):
'''
Sign a message with the From key.
'''
if is_content_type_text(self.crypto_message.get_email_message().get_message()):
encrypt_utils.sign_text_message(self.crypto_message, crypto, from_user_id, passcode)
else:
encrypt_utils.sign_mime_message(self.crypto_message, crypto, from_user_id, passcode)
return self.crypto_message.is_crypted()
def _add_outbound_record(self, original_crypto_message, inner_encrypted_with):
''' Add an outbound record that a message was sent privately.'''
self.crypto_message.set_crypted_with(inner_encrypted_with)
# use the original message, not the protected one
if original_crypto_message is None:
original_crypto_message = copy.copy(self.crypto_message)
self._log_message('copying crypto message before saving history record')
else:
original_crypto_message.set_crypted(True)
original_crypto_message.set_crypted_with(inner_encrypted_with)
original_crypto_message.set_metadata_crypted(True)
original_crypto_message.set_metadata_crypted_with(self.crypto_message.get_metadata_crypted_with())
if self.crypto_message.is_private_signed():
original_crypto_message.set_private_signed(True)
if self.crypto_message.is_private_sig_verified():
original_crypto_message.set_private_signers(self.crypto_message.private_signers_list())
if self.crypto_message.is_clear_signed():
original_crypto_message.set_clear_signed(True)
if self.crypto_message.is_clear_sig_verified():
original_crypto_message.set_clear_signers(self.crypto_message.clear_signers_list())
if self.crypto_message.is_dkim_signed():
original_crypto_message.set_dkim_signed(True)
if self.crypto_message.is_dkim_sig_verified():
original_crypto_message.set_dkim_sig_verified(True)
history.add_outbound_record(original_crypto_message, self.verification_code)
def _start_check_for_encryption(self, from_user, to_user):
''' Start checking if the user uses encryption. '''
# don't look for keys if the to_user's domain is also using goodcrypto
if contacts.get(get_metadata_address(email=to_user)) is None:
# start by adding a record so we don't search for a key again
contact = contacts.add(to_user, None)
# search for the keys; if one's found, send email to the from
# user so they can verify the fingerprint
self._log_message('queuing search for a key for {}'.format(to_user))
queue_keyserver_search(to_user, from_user)
else:
self._log_message('{} is also using goodcrypto so not searching for a key'.format(to_user))
def _log_exception(self, msg):
'''
Log the message to the local and Exception logs.
'''
self._log_message(msg)
record_exception(message=msg)
def _log_error(error_message):
'''
Log an error.
'''
record_exception()
self._log_message('EXCEPTION - see syr.exception.log for details')
try:
self.crypto_message.add_error_tag_once('{} {}'.format(
SERIOUS_ERROR_PREFIX, error_message))
except Exception:
record_exception()
self._log_message('EXCEPTION - see syr.exception.log for details')
def _log_message(self, message):
'''
Log the message to the local log.
'''
if self._log is None:
self._log = LogFile()
self._log.write_and_flush(message)
示例12: SearchKeyserver
# 需要导入模块: from goodcrypto.utils.log_file import LogFile [as 别名]
# 或者: from goodcrypto.utils.log_file.LogFile import write_and_flush [as 别名]
#.........这里部分代码省略.........
try:
if self._is_ready_for_search():
result_ok = True
# start the search, but don't wait for the results
self.key_plugin.search_for_key(self.email, self.keyserver)
search_job = self.key_plugin.get_job()
queue = self.key_plugin.get_queue()
# if the search job or queue are done, then retrieve the key
if queue is None or search_job is None:
get_key(self.email, self.encryption_name, self.keyserver,
self.user_initiated_search, search_job, queue)
else:
from goodcrypto.mail.keyserver_utils import get_key
ONE_MINUTE = 60 # one minute, in seconds
DEFAULT_TIMEOUT = 10 * ONE_MINUTE
# otherwise, set up another job in the queue to retrieve the
# key as soon as the search for the key id is finished
result_ok = get_key(self.email,
self.encryption_name,
self.keyserver,
self.user_initiated_search,
search_job.get_id(), queue.key)
self.log_message('retrieving {} key for {}: {}'.format(
self.encryption_name, self.email, result_ok))
else:
result_ok = False
except Exception as exception:
result_ok = False
record_exception()
self.log_message('EXCEPTION - see syr.exception.log for details')
self.log_message('finished starting search on {} for {} ok: {}'.format(
self.keyserver, self.email, result_ok))
return result_ok
def _is_ready_for_search(self):
'''
Verify that we're ready to search for this key.
Test extreme case.
>>> srk_class = SearchKeyserver(None, None, None, None)
>>> srk_class._is_ready_for_search()
False
'''
ready = False
try:
ready = (self.email is not None and
self.encryption_name is not None and
self.keyserver is not None and
self.user_initiated_search is not None and
not email_in_domain(self.email))
if ready:
self.key_plugin = KeyFactory.get_crypto(
self.encryption_name, crypto_software.get_key_classname(self.encryption_name))
ready = self.key_plugin is not None
if ready:
# make sure we don't already have crypto defined for this user
contacts_crypto = contacts.get_contacts_crypto(self.email, self.encryption_name)
if contacts_crypto is None or contacts_crypto.fingerprint is None:
fingerprint, expiration = self.key_plugin.get_fingerprint(self.email)
if fingerprint is not None:
ready = False
self.log_message('{} public key exists for {}: {}'.format(
self.encryption_name, self.email, fingerprint))
else:
ready = False
self.log_message('crypto for {} already defined'.format(self.email))
except Exception as exception:
record_exception()
self.log_message('EXCEPTION - see syr.exception.log for details')
ready = False
return ready
def log_message(self, message):
'''
Log the message to the local log.
>>> import os.path
>>> from syr.log import BASE_LOG_DIR
>>> from syr.user import whoami
>>> SearchKeyserver(None, None, None, None).log_message('test')
>>> os.path.exists(os.path.join(BASE_LOG_DIR, whoami(), 'goodcrypto.mail.search_keyserver.log'))
True
'''
if self.log is None:
self.log = LogFile()
self.log.write_and_flush(message)
示例13: MailAPI
# 需要导入模块: from goodcrypto.utils.log_file import LogFile [as 别名]
# 或者: from goodcrypto.utils.log_file.LogFile import write_and_flush [as 别名]
#.........这里部分代码省略.........
return ok
def format_result(self, action, ok, error_message=None):
'''Format the action's result.'''
if error_message is None:
result = {api_constants.ACTION_KEY: action, api_constants.OK_KEY: ok}
else:
result = {
api_constants.ACTION_KEY: action,
api_constants.OK_KEY: ok,
api_constants.ERROR_KEY: error_message
}
return result
def format_message_result(self, action, ok, message):
'''Format the action's result.'''
result = {
api_constants.ACTION_KEY: action,
api_constants.OK_KEY: ok,
api_constants.MESSAGE_KEY: message
}
return result
def format_bad_result(self, error_message):
'''Format the bad result for the action.'''
result = None
if self.action and len(self.action) > 0:
result = self.format_result(self.action, False, error_message=error_message)
else:
result = self.format_result('Unknown', False, error_message=error_message)
self.log_message('action result: {}'.format(error_message))
return result
def get_api_response(self, request, result):
''' Get API reponse as JSON. '''
json_result = json.dumps(result)
self.log_message('json results: {}'.format(''.join(json_result)))
response = render_to_response('mail/api_response.html',
{'result': ''.join(json_result),},
context_instance=RequestContext(request))
return response
def log_attempted_access(self, results):
'''Log an attempted access to the api.'''
self.log_message('attempted access from {} for {}'.format(self.ip, results))
def log_bad_form(self, request, form):
''' Log the bad fields entered.'''
# see django.contrib.formtools.utils.security_hash()
# for example of form traversal
for field in form:
if (hasattr(form, 'cleaned_data') and
field.name in form.cleaned_data):
name = field.name
else:
# mark invalid data
name = '__invalid__' + field.name
self.log_message('name: {}; data: {}'.format(name, field.data))
try:
if form.name.errors:
self.log_message(' ' + form.name.errors)
if form.email.errors:
self.log_message(' ' + form.email.errors)
except:
pass
self.log_message('logged bad api form')
def log_message(self, message):
'''
Log the message to the local log.
>>> import os.path
>>> from syr.log import BASE_LOG_DIR
>>> from syr.user import whoami
>>> MailAPI().log_message('test')
>>> os.path.exists(os.path.join(BASE_LOG_DIR, whoami(), 'goodcrypto.mail.api.log'))
True
'''
if self.log is None:
self.log = LogFile()
self.log.write_and_flush(message)
示例14: execute_gpg_command
# 需要导入模块: from goodcrypto.utils.log_file import LogFile [as 别名]
# 或者: from goodcrypto.utils.log_file.LogFile import write_and_flush [as 别名]
def execute_gpg_command(home_dir, initial_args, passphrase=None, data=None):
'''
Issue a GPG command in its own worker so there are no concurrency challenges.
'''
log = LogFile(filename='goodcrypto.oce.gpg_exec_queue.log')
gpg_exec = None
try:
if initial_args is not None:
new_args = []
for arg in initial_args:
new_args.append(arg)
initial_args = new_args
log.write_and_flush('gpg exec: {}'.format(initial_args))
auto_check_trustdb = gpg_constants.CHECK_TRUSTDB in initial_args
# different higher levels may try to generate the same key
# so only allow one key to be generated
if gpg_constants.GEN_KEY in initial_args:
command_ready = need_private_key(home_dir, data)
if not command_ready:
result_code = gpg_constants.GOOD_RESULT
gpg_output = gpg_constants.KEY_EXISTS
gpg_error = None
log.write_and_flush('{}'.format(gpg_output))
# if deleting a key, get the fingerprint because gpg
# only allows deletion in batch mode with the fingerprint
elif gpg_constants.DELETE_KEYS in initial_args:
fingerprint = prep_to_delete_key(home_dir, initial_args)
if fingerprint is not None:
initial_args = [gpg_constants.DELETE_KEYS, fingerprint]
log.write_and_flush('ready to delete key: {}'.format(fingerprint))
command_ready = True
else:
command_ready = True
if command_ready:
gpg_exec = GPGExec(home_dir, auto_check_trustdb=auto_check_trustdb)
result_code, gpg_output, gpg_error = gpg_exec.execute(
initial_args, passphrase, data)
log.write_and_flush('result code: {}'.format(result_code))
except JobTimeoutException as job_exception:
log.write_and_flush('gpg exec {}'.format(str(job_exception)))
result_code = gpg_constants.TIMED_OUT_RESULT
gpg_error = str(job_exception)
gpg_output = None
log.write_and_flush('EXCEPTION - see syr.exception.log for details')
record_exception()
except Exception as exception:
result_code = gpg_constants.ERROR_RESULT
gpg_output = None
gpg_error = str(exception)
log.write_and_flush('EXCEPTION - see syr.exception.log for details')
record_exception()
if gpg_exec is not None and gpg_exec.gpg_home is not None:
gpg_exec.clear_gpg_lock_files()
gpg_exec.clear_gpg_tmp_files()
log.flush()
return result_code, gpg_output, gpg_error
示例15: GPGExec
# 需要导入模块: from goodcrypto.utils.log_file import LogFile [as 别名]
# 或者: from goodcrypto.utils.log_file.LogFile import write_and_flush [as 别名]
#.........这里部分代码省略.........
lines.append('# algorithm and ciphers\n')
lines.append('#-----------------------------\n')
lines.append('# list of personal digest preferences. When multiple digests are supported by\n')
lines.append('# all recipients, choose the strongest one\n')
lines.append('personal-cipher-preferences AES256 AES192 AES CAST5\n')
lines.append('# list of personal digest preferences. When multiple ciphers are supported by\n')
lines.append('# all recipients, choose the strongest one\n')
lines.append('personal-digest-preferences SHA512 SHA384 SHA256 SHA224\n')
lines.append('# message digest algorithm used when signing a key\n')
lines.append('cert-digest-algo SHA512\n')
lines.append('# This preference list is used for new keys and becomes the default for\n')
lines.append('# "setpref" in the edit menu\n')
lines.append('default-preference-list SHA512 SHA384 SHA256 SHA224 AES256 AES192 AES CAST5 ZLIB BZIP2 ZIP Uncompressed\n')
'''
lines.append('# when outputting certificates, view user IDs distinctly from keys:\n')
lines.append('fixed-list-mode\n')
lines.append("# long keyids are more collision-resistant than short keyids (it's trivial to make a key with any desired short keyid)")
lines.append('keyid-format 0xlong\n')
lines.append('# when multiple digests are supported by all recipients, choose the strongest one:\n')
lines.append('personal-digest-preferences SHA512 SHA384 SHA256 SHA224\n')
lines.append('# preferences chosen for new keys should prioritize stronger algorithms: \n')
lines.append('default-preference-list SHA512 SHA384 SHA256 SHA224 AES256 AES192 AES CAST5 BZIP2 ZLIB ZIP Uncompressed\n')
lines.append("# If you use a graphical environment (and even if you don't) you should be using an agent:")
lines.append('# (similar arguments as https://www.debian-administration.org/users/dkg/weblog/64)\n')
lines.append('use-agent\n')
lines.append('# You should always know at a glance which User IDs gpg thinks are legitimately bound to the keys in your keyring:\n')
lines.append('verify-options show-uid-validity\n')
lines.append('list-options show-uid-validity\n')
lines.append('# include an unambiguous indicator of which key made a signature:\n')
lines.append('# (see http://thread.gmane.org/gmane.mail.notmuch.general/3721/focus=7234)\n')
lines.append('sig-notation [email protected]=%g\n')
lines.append('# when making an OpenPGP certification, use a stronger digest than the default SHA1:\n')
lines.append('cert-digest-algo SHA256\n')
'''
self.log_message('creating {}'.format(gpg_conf))
with open(gpg_conf, 'wt') as f:
for line in lines:
f.write(line)
sh.chmod('0400', gpg_conf)
self.log_message('created {}'.format(gpg_conf))
except Exception:
record_exception()
self.log_message('EXCEPTION - see syr.exception.log for details')
def clear_gpg_lock_files(self):
'''
Delete gpg lock files.
Warning: Calling this method when a valid lock file exists can have very
serious consequences.
Lock files are in gpg home directory and are in the form
".*.lock", ".?*", or possibly "trustdb.gpg.lock".
'''
try:
if self.gpg_home is None:
self.log_message("unable to clear gpg's lock files because home dir unknown")
else:
filenames = os.listdir(self.gpg_home)
if filenames and len(filenames) > 0:
for name in filenames:
if name.endswith(gpg_constants.LOCK_FILE_SUFFIX):
os.remove(os.path.join(self.gpg_home, name))
self.log_message("deleted lock file " + name)
except Exception:
record_exception()
self.log_message('EXCEPTION - see syr.exception.log for details')
def clear_gpg_tmp_files(self):
'''
Delete gpg tmp files.
'''
TmpPREFIX = 'tmp'
TmpSUFFIX = '~'
try:
if self.gpg_home is None:
self.log_message("unable to clear gpg's tmp files because home dir unknown")
else:
filenames = os.listdir(self.gpg_home)
if filenames and len(filenames) > 0:
for name in filenames:
if name.startswith(TmpPREFIX) and name.endswith(TmpSUFFIX):
os.remove(os.path.join(self.gpg_home, name))
except Exception:
record_exception()
self.log_message('EXCEPTION - see syr.exception.log for details')
def log_message(self, message):
'''
Log the message.
'''
if self.log is None:
self.log = LogFile()
self.log.write_and_flush(message)