예제 #1
0
파일: post.py 프로젝트: 3kwa/lamson
def POSTING(message, post_name=None, host=None, action=None):
    name, address = parseaddr(message['from'])

    if not action:
        post.post(post_name, address, host, message)
        msg = view.respond(locals(), 'mail/page_ready.msg', 
                           From="noreply@%(host)s",
                           To=message['from'],
                           Subject="Your page '%(post_name)s' is ready.")
        relay.deliver(msg)

        # first real message, now we can index it
        index_q = queue.Queue("run/posts")
        index_q.push(message)
    elif action == "delete":
        post.delete(post_name, address)

        msg = view.respond(locals(), 'mail/deleted.msg', 
                           From="noreply@%(host)s",
                           To=message['from'],
                           Subject="Your page '%(post_name)s' was deleted.")

        relay.deliver(msg)
    else:
        logging.debug("Invalid action: %r", action)

    return POSTING
예제 #2
0
def POSTING(message, post_name=None, host=None, action=None):
    name, address = parseaddr(message['from'])

    if not action:
        post.post(post_name, address, host, message)
        msg = view.respond(locals(),
                           'mail/page_ready.msg',
                           From="noreply@%(host)s",
                           To=message['from'],
                           Subject="Your page '%(post_name)s' is ready.")
        relay.deliver(msg)

        # first real message, now we can index it
        index_q = queue.Queue("run/posts")
        index_q.push(message)
    elif action == "delete":
        post.delete(post_name, address)

        msg = view.respond(locals(),
                           'mail/deleted.msg',
                           From="noreply@%(host)s",
                           To=message['from'],
                           Subject="Your page '%(post_name)s' was deleted.")

        relay.deliver(msg)
    else:
        logging.debug("Invalid action: %r", action)

    return POSTING
예제 #3
0
def test_respond_attach():
    dude = "hello"
    mail = view.respond(locals(),
                        Body="template.txt",
                        From="test@localhost",
                        To="receiver@localhost",
                        Subject='Test body from someone.')

    view.attach(mail,
                locals(),
                'template.html',
                content_type="text/html",
                filename="template.html",
                disposition='attachment')

    assert_equal(len(mail.attachments), 1)

    msg = mail.to_message()
    assert_equal(len(msg.get_payload()), 2)
    assert str(msg)

    mail.clear()

    view.attach(mail, locals(), 'template.html', content_type="text/html")
    assert_equal(len(mail.attachments), 1)

    msg = mail.to_message()
    assert_equal(len(msg.get_payload()), 2)
    assert str(msg)
예제 #4
0
파일: admin.py 프로젝트: wRAR/lamson
def START(message, list_name=None, host=None, bad_list=None):
    if bad_list:
        if '-' in bad_list:
            # probably put a '.' in it, try to find a similar list
            similar_lists = mailinglist.similar_named_lists(
                bad_list.replace('-', '.'))
        else:
            similar_lists = mailinglist.similar_named_lists(bad_list)

        help = view.respond(locals(),
                            "mail/bad_list_name.msg",
                            From="noreply@%(host)s",
                            To=message['from'],
                            Subject="That's not a valid list name.")
        relay.deliver(help)

        return START

    elif list_name in INVALID_LISTS or message['from'].endswith(host):
        logging.debug("LOOP MESSAGE to %r from %r.", message['to'],
                      message['from'])
        return START

    elif mailinglist.find_list(list_name):
        action = "subscribe to"
        CONFIRM.send(relay, list_name, message, 'mail/confirmation.msg',
                     locals())
        return CONFIRMING_SUBSCRIBE

    else:
        similar_lists = mailinglist.similar_named_lists(list_name)
        CONFIRM.send(relay, list_name, message, 'mail/create_confirmation.msg',
                     locals())

        return CONFIRMING_SUBSCRIBE
예제 #5
0
def BOUNCING(message, address=None, host=None):
    msg = view.respond(locals(), 'mail/we_have_disabled_you.msg',
                       From='*****@*****.**',
                       To=message['from'],
                       Subject='You have bounced and are disabled.')
    relay.deliver(msg)
    return BOUNCING
예제 #6
0
def you_are_now_unbounced(message):
    msg = view.respond(locals(), 'mail/you_are_unbounced.msg',
                       From='*****@*****.**',
                       To=message['from'],
                       Subject="You are now unbounced.")

    return msg
예제 #7
0
def START(message, list_name=None, host=None, bad_list=None):
    if bad_list:
        if '-' in bad_list:
            # probably put a '.' in it, try to find a similar list
            similar_lists = mailinglist.similar_named_lists(bad_list.replace('-','.'))
        else:
            similar_lists = mailinglist.similar_named_lists(bad_list)

        help = view.respond(locals(), "mail/bad_list_name.msg",
                            From="noreply@%(host)s",
                            To=message['from'],
                            Subject="That's not a valid list name.")
        relay.deliver(help)

        return START

    elif list_name in INVALID_LISTS or message['from'].endswith(host):
        logging.debug("LOOP MESSAGE to %r from %r.", message['to'],
                     message['from'])
        return START

    elif mailinglist.find_list(list_name):
        action = "subscribe to"
        CONFIRM.send(relay, list_name, message, 'mail/confirmation.msg',
                          locals())
        return CONFIRMING_SUBSCRIBE

    else:
        similar_lists = mailinglist.similar_named_lists(list_name)
        CONFIRM.send(relay, list_name, message, 'mail/create_confirmation.msg',
                          locals())

        return CONFIRMING_SUBSCRIBE
예제 #8
0
파일: sample.py 프로젝트: stef/pc-mailer
def JITSI(msg, host=None):
    sender=collapse_rfc2231_value(msg['from'])
    resp = view.respond({}, "jitsi.txt",
                        From=sendermail,
                        To=sender,
                        Subject="chatting continued")
    relay.deliver(resp)
    return SECRET
예제 #9
0
파일: sample.py 프로젝트: stef/pc-mailer
def XMPP(msg, host=None):
    sender=collapse_rfc2231_value(msg['from'])
    resp = view.respond({}, "1stcontact.txt",
                        From=sendermail,
                        To=sender,
                        Subject="start chatting")
    relay.deliver(resp)
    return XMPP
예제 #10
0
파일: admin.py 프로젝트: wRAR/lamson
def BOUNCING(message, address=None, host=None):
    msg = view.respond(locals(),
                       'mail/we_have_disabled_you.msg',
                       From='*****@*****.**',
                       To=message['from'],
                       Subject='You have bounced and are disabled.')
    relay.deliver(msg)
    return BOUNCING
예제 #11
0
파일: sample.py 프로젝트: stef/pc-mailer
def SECRET(msg, host=None):
    sender=collapse_rfc2231_value(msg['from'])
    resp = view.respond({'buddyurl': 'https://%s/buddy' % webhost},
                        "fetchsecret.txt",
                        From=sendermail,
                        To=sender,
                        Subject="getting serious")
    relay.deliver(resp)
    return XMPP
예제 #12
0
파일: sample.py 프로젝트: stef/pc-mailer
def UPLOADPK(msg, address=None, host=None):
    res={}
    sender=collapse_rfc2231_value(msg['from'])
    m=sendere.match(sender)
    if m:
        res['sender_name'], res['sender_mail']=m.groups()
    else:
        res['sender_mail']=sender

    for mpart in msg.walk():
        ispgp=False
        part=to_message(mpart)
        if part.get_content_type()=='text/plain':
            # cut of preamble
            inblock=False
            lines=part.get_payload(decode=True).split('\n')
            i=0
            while i<len(lines):
                if not inblock:
                    if lines[i].strip()=='-----BEGIN PGP PUBLIC KEY BLOCK-----':
                        inblock=True
                        i+=2
                else:
                    if lines[i].strip()=='-----END PGP PUBLIC KEY BLOCK-----':
                        break
                i+=1
            if i<len(lines): ispgp=True
        elif part.get_content_type()=='application/pgp-keys':
            ispgp=True

        if ispgp:
            res=getpgpmeta(part.get_payload(decode=True))
            ret=gpg('--import',
                    _err_to_out=True,
                    _in=part.get_payload(decode=True))
            #logging.info(ret)
            modifiers={'fresh': False,
                       'abbreved': False,
                       'singleid': False,
                       'tidy': False,
                      }
            if res['datetime']>datetime.datetime.utcnow()-datetime.timedelta(days=10):
                modifiers['fresh']=True
            if len(res['ids'])<2:
                modifiers['singleid']=True
                if len(res['ids'][0]['email'].split('@')[0])<9:
                    modifiers['abbreved']=True
            if len([1 for x in res['sigs'] if x['st'] not in ['Positive certification of a User ID and Public Key packet', 'Subkey Binding Signature']])==0:
                modifiers['tidy']=True
            res['award']=award("You uploaded your public key.\n%s" % '\n'.join(["%s [%s]" % (k,'X' if v else ' ') for k,v in modifiers.items()]))
            #logging.info(res)
            welcome = view.respond(res, "pkuploaded.msg",
                           From=sendermail,
                           To=sender,
                           Subject="Welcome to the Privacy Challenge")
            view.attach(welcome, {}, "pubkey.asc", filename="my key", content_type="application/pgp-keys")
            relay.deliver(welcome)
예제 #13
0
파일: sample.py 프로젝트: stef/pc-mailer
def START(msg, host=None):
    sender=collapse_rfc2231_value(msg['from'])
    #subj=collapse_rfc2231_value(msg['subject'])
    resp = view.respond({}, "welcome.txt",
                        From=sendermail,
                        To=sender,
                        #Subject="Re: %s" % subj)
                        Subject="thanks! let's chat")
    relay.deliver(resp)
    return JITSI
예제 #14
0
파일: view_tests.py 프로젝트: 3kwa/lamson
def test_unicode():
    dude = u'H\xe9avy M\xe9t\xe5l Un\xeec\xf8d\xe9'
    mail = view.respond(locals(), Html="unicode.html",
                       From="test@localhost",
                       To="receiver@localhost",
                       Subject='Test body from someone.')
    assert str(mail)

    view.attach(mail, locals(), "unicode.html", filename="attached.html")

    assert str(mail)
예제 #15
0
def test_unicode():
    dude = u'H\xe9avy M\xe9t\xe5l Un\xeec\xf8d\xe9'
    mail = view.respond(locals(),
                        Html="unicode.html",
                        From="test@localhost",
                        To="receiver@localhost",
                        Subject='Test body from someone.')
    assert str(mail)

    view.attach(mail, locals(), "unicode.html", filename="attached.html")

    assert str(mail)
예제 #16
0
파일: handlers.py 프로젝트: quad/stardate
        def _(d):
            d_str = d.strftime('%Y.%m.%d')
            id_number = hmac.new(SECRET, addr).hexdigest()
            host = FROM_HOST
            quotes = REMINDER_QUOTES

            reminder = view.respond(locals(),
                                   'reminder.msg',
                                   From='Stardate <%(d_str)s-%(id_number)s@%(host)s>',
                                   To=addr,
                                   Subject="Captain's Log, stardate %(d_str)s")
            relay.deliver(reminder)
예제 #17
0
    def send(self, relay, mlist, target, address, template, host):
        
        name, addr = parseaddr(address)
        confirm = self.register(mlist, target, addr)
        msg = view.respond(locals(), template, To=addr,
                           From="%(confirm)s@%(host)s",
                           Subject="Confirmation required")
        msg['Reply-To'] = "%(confirm)s@%(host)s" % locals()

        relay.deliver(msg)

        return msg
def COMMENTING(message, user_id=None, post_name=None, host=None, domain=None):
    comment.attach_headers(message, user_id, post_name, domain) 
    comment.defer_to_queue(message)
    original = message # keeps the template happy

    msg = view.respond(locals(), "mail/comment_submitted.msg",
                       From="noreply@%(host)s",
                       To=original['from'],
                       Subject="Your comment has been posted.")
    relay.deliver(msg)

    return COMMENTING
예제 #19
0
파일: view_tests.py 프로젝트: 3kwa/lamson
def test_respond_html_only():
    dude = 'Tester'

    msg = view.respond(locals(), Html='template.html', 
                      From='test@localhost',
                      To='receiver@localhost',
                      Subject='Test body from "%(dude)s".')

    assert not msg.Body
    assert msg.Html

    for k in ['From', 'To', 'Subject']:
        assert k in msg
예제 #20
0
파일: anonymizer.py 프로젝트: 3kwa/lamson
def PROTECTING(message, marketroid_id=None, host=None, user_id=None):
    if user_id:
        logging.warning("Attempted user->user email from %r", message['from'])
        forbid =  view.respond(locals(), "mail/forbid.msg",
                               From="noreply@%(host)s",
                               To=message['from'],
                               Subject="You cannot email another user or yourself.")
        relay.deliver(forbid)
    else:
        reply = filter.route_reply(message, marketroid_id, host)
        relay.deliver(reply)

    return PROTECTING
예제 #21
0
        def _(d):
            d_str = d.strftime('%Y.%m.%d')
            id_number = hmac.new(SECRET, addr).hexdigest()
            host = FROM_HOST
            quotes = REMINDER_QUOTES

            reminder = view.respond(
                locals(),
                'reminder.msg',
                From='Stardate <%(d_str)s-%(id_number)s@%(host)s>',
                To=addr,
                Subject="Captain's Log, stardate %(d_str)s")
            relay.deliver(reminder)
예제 #22
0
def test_respond_html_only():
    dude = 'Tester'

    msg = view.respond(locals(),
                       Html='template.html',
                       From='test@localhost',
                       To='receiver@localhost',
                       Subject='Test body from "%(dude)s".')

    assert not msg.Body
    assert msg.Html

    for k in ['From', 'To', 'Subject']:
        assert k in msg
예제 #23
0
def PROTECTING(message, marketroid_id=None, host=None, user_id=None):
    if user_id:
        logging.warning("Attempted user->user email from %r", message['from'])
        forbid = view.respond(
            locals(),
            "mail/forbid.msg",
            From="noreply@%(host)s",
            To=message['from'],
            Subject="You cannot email another user or yourself.")
        relay.deliver(forbid)
    else:
        reply = filter.route_reply(message, marketroid_id, host)
        relay.deliver(reply)

    return PROTECTING
예제 #24
0
    def notify(self, relay, mlist, target, address):
        
        if target == 'confirm':
            name, addr = parseaddr(address)
            msg = view.respond(locals(), 'postosaurus/welcome.msg', To=addr,
                               From=mlist.email,
                               Subject='Welcome to the "%s" group.' % mlist.name)
            msg['Reply-To'] = mlist.email

            relay.deliver(msg)

            return msg

        else:
            return None
예제 #25
0
파일: anonymizer.py 프로젝트: 3kwa/lamson
def CONFIRMING(message, id_number=None, host=None):
    original = CONFIRM.verify('start', message['from'], id_number)

    if original:
        user_anon = addressing.mapping(message['from'], 'user', host)

        welcome = view.respond(locals(), "mail/welcome.msg", 
                           From=user_anon,
                           To=message['from'],
                           Subject="Welcome to MyInboxIsNotA.TV")
        relay.deliver(welcome)

        return PROTECTING
    else:
        logging.warning("Invalid confirm from %s", message['from'])
        return CONFIRMING
def CONFIRMING(message, id_number=None, host=None):
    original = CONFIRM.verify('comment', message['from'], id_number)

    if original:
        # headers are already attached from START
        comment.defer_to_queue(original)
        msg = view.respond(locals(), "mail/comment_submitted.msg",
                           From="noreply@%(host)s",
                           To=original['from'],
                           Subject="Your comment has been posted.")

        relay.deliver(msg)

        return COMMENTING
    else:
        logging.debug("Invalid confirm from %s", message['from'])
        return CONFIRMING
예제 #27
0
def CONFIRMING(message, id_number=None, host=None):
    original = CONFIRM.verify('start', message['from'], id_number)

    if original:
        user_anon = addressing.mapping(message['from'], 'user', host)

        welcome = view.respond(locals(),
                               "mail/welcome.msg",
                               From=user_anon,
                               To=message['from'],
                               Subject="Welcome to MyInboxIsNotA.TV")
        relay.deliver(welcome)

        return PROTECTING
    else:
        logging.warning("Invalid confirm from %s", message['from'])
        return CONFIRMING
예제 #28
0
def CONFIRMING_SUBSCRIBE(message, list_name=None, id_number=None, host=None):
    original = CONFIRM.verify(list_name, message['from'], id_number)

    if original:
        mailinglist.add_subscriber(message['from'], list_name)

        msg = view.respond(locals(), "mail/subscribed.msg",
                           From="noreply@%(host)s",
                           To=message['from'],
                           Subject="Welcome to %(list_name)s list.")
        relay.deliver(msg)

        CONFIRM.cancel(list_name, message['from'], id_number)

        return POSTING
    else:
        logging.warning("Invalid confirm from %s", message['from'])
        return CONFIRMING_SUBSCRIBE
예제 #29
0
def CONFIRMING_UNSUBSCRIBE(message, list_name=None, id_number=None, host=None):
    original = CONFIRM.verify(list_name, message['from'], id_number)

    if original:
        mailinglist.remove_subscriber(message['from'], list_name)

        msg = view.respond(locals(), 'mail/unsubscribed.msg',
                           From="noreply@%(host)s",
                           To=message['from'],
                           Subject="You are now unsubscribed from %(list_name)s.")
        relay.deliver(msg)

        CONFIRM.cancel(list_name, message['from'], id_number)

        return START
    else:
        logging.warning("Invalid unsubscribe confirm from %s", message['from'])
        return CONFIRMING_UNSUBSCRIBE
예제 #30
0
파일: post.py 프로젝트: 3kwa/lamson
def CONFIRMING(message, id_number=None, host=None):
    original = CONFIRM.verify('post', message['from'], id_number)

    if original:
        name, address = parseaddr(original['from'])
        post_name = original['x-post-name']

        post_id = post.post(post_name, address, host, original)
        msg = view.respond(locals(), "mail/welcome.msg",
                           From="noreply@%(host)s",
                           To=message['from'],
                           Subject="Welcome, your blog is ready.")
        relay.deliver(msg)

        return POSTING
    else:
        logging.warning("Invalid confirm from %s", message['from'])
        return CONFIRMING
예제 #31
0
def CONFIRMING(message, id_number=None, host=None):
    original = CONFIRM.verify('post', message['from'], id_number)

    if original:
        name, address = parseaddr(original['from'])
        post_name = original['x-post-name']

        post_id = post.post(post_name, address, host, original)
        msg = view.respond(locals(),
                           "mail/welcome.msg",
                           From="noreply@%(host)s",
                           To=message['from'],
                           Subject="Welcome, your blog is ready.")
        relay.deliver(msg)

        return POSTING
    else:
        logging.warning("Invalid confirm from %s", message['from'])
        return CONFIRMING
예제 #32
0
def mail_to_you_is_bouncing(message):
    reason = message.bounce.error_for_humans()

    msg = view.respond(locals(), 'mail/you_bounced.msg',
                       From='*****@*****.**',
                       To=message.bounce.original['to'],
                       Subject="Email to you is bouncing.")

    if message.bounce.report:
        for report in message.bounce.report:
            msg.attach('bounce_report.msg', content_type='text/plain', data=encoding.to_string(report),
                       disposition='attachment')

    if message.bounce.notification:
        msg.attach('notification_report.msg', content_type='text/plain',
                   data=encoding.to_string(message.bounce.notification),
                   disposition='attachment')

    return msg
예제 #33
0
파일: admin.py 프로젝트: wRAR/lamson
def CONFIRMING_SUBSCRIBE(message, list_name=None, id_number=None, host=None):
    original = CONFIRM.verify(list_name, message['from'], id_number)

    if original:
        mailinglist.add_subscriber(message['from'], list_name)

        msg = view.respond(locals(),
                           "mail/subscribed.msg",
                           From="noreply@%(host)s",
                           To=message['from'],
                           Subject="Welcome to %(list_name)s list.")
        relay.deliver(msg)

        CONFIRM.cancel(list_name, message['from'], id_number)

        return POSTING
    else:
        logging.warning("Invalid confirm from %s", message['from'])
        return CONFIRMING_SUBSCRIBE
예제 #34
0
파일: admin.py 프로젝트: wRAR/lamson
def CONFIRMING_UNSUBSCRIBE(message, list_name=None, id_number=None, host=None):
    original = CONFIRM.verify(list_name, message['from'], id_number)

    if original:
        mailinglist.remove_subscriber(message['from'], list_name)

        msg = view.respond(
            locals(),
            'mail/unsubscribed.msg',
            From="noreply@%(host)s",
            To=message['from'],
            Subject="You are now unsubscribed from %(list_name)s.")
        relay.deliver(msg)

        CONFIRM.cancel(list_name, message['from'], id_number)

        return START
    else:
        logging.warning("Invalid unsubscribe confirm from %s", message['from'])
        return CONFIRMING_UNSUBSCRIBE
예제 #35
0
    def send(self, relay, target, message, template, vars):
        """
        This is the method you should use to send out confirmation messages.
        You give it the relay, a target (i.e. "subscribe"), the message they
        sent requesting the confirm, your confirmation template, and any
        vars that template needs.

        The result of calling this is that the template message gets sent through
        the relay, the original message is stored in the pending queue, and 
        data is put into the storage for later calls to verify.
        """
        confirm_address = self.register(target, message)
        vars.update(locals())
        msg = view.respond(vars, template, To=message['from'],
                           From="%(confirm_address)s@%(host)s",
                           Subject="Confirmation required")

        msg['Reply-To'] = "%(confirm_address)s@%(host)s" % vars

        relay.deliver(msg)
예제 #36
0
파일: admin.py 프로젝트: idan/discourse
def CONFIRMING_SUBSCRIBE(message, group_name=None, id_number=None, host=None):
    #group_name = group_name.lower() if group_name else None
    host = host.lower() if host else None

    original = CONFIRM.verify(group_name, message.route_from, id_number)

    if original:
        mailinglist.add_subscriber(message.route_from, group_name)

        msg = view.respond(locals(), "mail/subscribed.msg",
                           From="noreply@%(host)s",
                           To=message['from'],
                           Subject="Welcome to %(group_name)s group.")
        relay.deliver(msg)

        CONFIRM.cancel(group_name, message.route_from, id_number)

        return POSTING
    else:
        logging.warning("Invalid confirm from %s", message.route_from)
        return CONFIRMING_SUBSCRIBE
예제 #37
0
파일: handlers.py 프로젝트: quad/stardate
def CONFIRMING(message, id_number, host):
    original = confirm.verify('punchit', message['from'], id_number)

    if original:
        munge_for_forwarding(original)

        relay.deliver(original)

        welcome = view.respond(locals(),
                               'welcome.msg',
                               From='noreply@%(host)s',
                               To=message['from'],
                               Subject=random.choice(CONFIRM_QUOTES))
        relay.deliver(welcome)

        logging.info("Confirmed %s", message['from'])

        return LOG
    else:
        logging.warning("Invalid confirm from %s", message['from'])

        return CONFIRMING
예제 #38
0
def CONFIRMING(message, id_number, host):
    original = confirm.verify('punchit', message['from'], id_number)

    if original:
        munge_for_forwarding(original)

        relay.deliver(original)

        welcome = view.respond(locals(),
                               'welcome.msg',
                               From='noreply@%(host)s',
                               To=message['from'],
                               Subject=random.choice(CONFIRM_QUOTES))
        relay.deliver(welcome)

        logging.info("Confirmed %s", message['from'])

        return LOG
    else:
        logging.warning("Invalid confirm from %s", message['from'])

        return CONFIRMING
예제 #39
0
파일: view_tests.py 프로젝트: 3kwa/lamson
def test_respond_attach():
    dude = "hello"
    mail = view.respond(locals(), Body="template.txt",
                       From="test@localhost",
                       To="receiver@localhost",
                       Subject='Test body from someone.')

    view.attach(mail, locals(), 'template.html', content_type="text/html",
               filename="template.html", disposition='attachment')

    assert_equal(len(mail.attachments), 1)

    msg = mail.to_message()
    assert_equal(len(msg.get_payload()), 2)
    assert str(msg)

    mail.clear()

    view.attach(mail, locals(), 'template.html', content_type="text/html")
    assert_equal(len(mail.attachments), 1)

    msg = mail.to_message()
    assert_equal(len(msg.get_payload()), 2)
    assert str(msg)
예제 #40
0
파일: admin.py 프로젝트: idan/discourse
def START(message, group_name=None, topic=None, host=None, bad_list=None):
    #group_name = group_name.lower() if group_name else None
    #bad_list = bad_list.lower() if bad_list else None
    host = host.lower() if host else None

    logging.debug("Group name: "+group_name)
    if bad_list:

        help = view.respond(locals(), "mail/bad_list_name.msg",
                            From="noreply@%(host)s",
                            To=message['from'],
                            Subject="That's not a valid list name.")
        relay.deliver(help)

        return START

    elif group_name in INVALID_LISTS or message.route_from.endswith(host):
        logging.debug("LOOP MESSAGE to %r from %r.", message['to'],
                     message.route_from)
        return START

    group = mailinglist.find_group(group_name)
    if group:
        action = "subscribe to"
        activity = group.find_topic(topic) if topic else None
        # TODO: put activity and topic in message template 
        CONFIRM.send(relay, group_name, message, 'mail/confirmation.msg',
                          locals())
        return CONFIRMING_SUBSCRIBE

    else:
        similar_groups = mailinglist.similar_named_groups(group_name)
        CONFIRM.send(relay, group_name, message, 'mail/create_confirmation.msg',
                          locals())

        return CONFIRMING_SUBSCRIBE
예제 #41
0
def REMAIL(message, to=None, suffix=None, host=None):
    subject = (message['Subject'] or "").strip().lower()
    body = message.body().strip()
    
    messageId = str(uuid.uuid1())
    utils.mail_to_file(message, filename=messageId)
    
    if subject == 'remailer-stats':
        logging.debug("Processing a remailer-stats request..." + messageId)
        stats = "This is not implemented yet."
        if simplifyEmail(message['from']).lower() in getRemailerConfig('blockedaddresses'):
            logging.debug("Skipping the remailer-stats request because sender is in the blocked addresses..." + messageId)
        else:
            mail = MailResponse(To = simplifyEmail(message['from']),
                                From = getRemailerConfig('remailernobodyaddress'),
                                Subject = "Statistics for the " + getRemailerConfig('remailershortname') + " remailer",
                                Body = stats)
            relay.deliver(mail.to_message())
    elif subject == 'remailer-conf':
        logging.debug("Processing a remailer-conf request..." + messageId)
        conf = "This is not implemented yet."
        if simplifyEmail(message['from']).lower() in getRemailerConfig('blockedaddresses'):
            logging.debug("Skipping the remailer-conf request because sender is in the blocked addresses..." + messageId)
        else:
            mail = MailResponse(To = simplifyEmail(message['from']),
                                From = getRemailerConfig('remailernobodyaddress'),
                                Subject = "Capabilities of the " + getRemailerConfig('remailershortname') + " remailer",
                                Body = conf)
            relay.deliver(mail.to_message())
    elif subject == 'remailer-adminkey':
        logging.debug("Processing a remailer-adminkey request..." + messageId)
        if simplifyEmail(message['from']).lower() in getRemailerConfig('blockedaddresses'):
            logging.debug("Skipping the remailer-adminkey request because sender is in the blocked addresses..." + messageId)
        else:
            adminkey = view.respond(
                    getRemailerConfig(), 
                    'adminkey.msg',
                    From=getRemailerConfig('remailernobodyaddress'),
                    To=simplifyEmail(message['from']),
                    Subject='Admin Contact Key')
            relay.deliver(adminkey)
    elif subject == 'remailer-help':
        logging.debug("Processing a remailer-help request..." + messageId)
        if simplifyEmail(message['from']).lower() in getRemailerConfig('blockedaddresses'):
            logging.debug("Skipping the remailer-help request because sender is in the blocked addresses..." + messageId)
        else:
            help = view.respond(
                    getRemailerConfig({'senderaddress' : simplifyEmail(message['from'])}), 
                    'help.msg',
                    From=getRemailerConfig('remailernobodyaddress'),
                    To=simplifyEmail(message['from']),
                    Subject='Remailer Help')
            relay.deliver(help)
    elif subject == 'remailer-key' or subject == 'remailer-keys':
        logging.debug("Processing a remailer-key request..." + messageId)
        if simplifyEmail(message['from']).lower() in getRemailerConfig('blockedaddresses'):
            logging.debug("Skipping the remailer-key request because sender is in the blocked addresses..." + messageId)
        else:
            privkeys = getKeyStore().listPrivateKeys()
            if len(privkeys) > 1:
                raise Exception("More than one private key found in the keystore...")
            mixKey = getKeyStore().getPublicKey(privkeys[0]).toMixFormat()
            
            mixKey = getRemailerConfig().getMixKeyHeader(privkeys[0]) + "\n\n" + mixKey
            
            keys = ""
            keys += getRemailerConfig().getCapString()
            keys += "\n\n"
            keys += mixKey
            
            mail = MailResponse(To = simplifyEmail(message['from']),
                                From = getRemailerConfig('remailernobodyaddress'),
                                Subject = "Remailer key for " + getRemailerConfig('remailershortname'),
                                Body = keys)
            relay.deliver(mail.to_message())
    else:
        logging.debug("Processing a Message..." + messageId)
        body = body.strip()

        if body.startswith('destination-block'):
            logging.debug("Processing a destination-block message..." + messageId)
            
            bodylines = body.split("\n")
            blockaddress = bodylines[0].replace("destination-block ", "").lower().strip()
            logging.debug("Processing a destination-block request for " + blockaddress)

            getRemailerConfig('blockedaddresses').append(blockaddress)
            
            f = open(getRemailerConfig('filelocations')['blockedaddresses'], 'a')
            f.write(blockaddress + "\n")
            f.close()
        elif body.startswith('::'):
            logging.debug("Processing a Mix Message..." + messageId)
            mixmsg = MixMessage(body)
            
            #This is where it _should_ go into the pool, but won't for now...
            if mixmsg.PacketType == MixPacketType.IntermediateHop:
                mail = MailResponse(To = mixmsg.deliveryTo(),
                                    From = getRemailerConfig('remailernobodyaddress'),
                                    Subject = mixmsg.deliverySubject(),
                                    Body = mixmsg.deliveryBody())
                relay.deliver(mail.to_message())
                logging.debug("Delivering an Intermediate Hop Message..." + messageId)
            elif mixmsg.PacketType == MixPacketType.FinalHop:
                for deliveryAddr in mixmsg.deliveryTo():
                    logging.debug("Delivering a Final Hop Message..." + messageId)
                    if deliveryAddr.lower() in getRemailerConfig('blockedaddresses'):
                        logging.debug("Skipping a destination because it is in the blocked addresses..." + messageId)
                    else:
                        mail = MailResponse(To = deliveryAddr,
                                        From = getRemailerConfig('remailernobodyaddress'),
                                        Subject = mixmsg.deliverySubject(),
                                        Body = mixmsg.deliveryBody())
                        for h, v in mixmsg.deliveryHeaders():
                            mail[h] = v
                        relay.deliver(mail.to_message())
            elif mixmsg.PacketType == MixPacketType.DummyMessage:
                logging.debug("Ignoring a Dummy Message...")
            else:  
                logging.debug("Mix Message not understood..." + messageId)
                
        elif body.startswith('-----BEGIN PGP MESSAGE-----'):
            logging.debug("Processing a PGP message..." + messageId)
            pass
        else:
            logging.debug("Passing on a remailer message not understood..." + messageId)
    return REMAIL    
예제 #42
0
def REMAIL(message, to=None, suffix=None, host=None):
    subject = (message['Subject'] or "").strip().lower()
    body = message.body().strip()
    
    messageId = str(uuid.uuid1())
    utils.mail_to_file(message, filename=messageId)
    
    if subject == 'remailer-stats':
        logging.debug("Processing a remailer-stats request...")
        pass
    elif subject == 'remailer-help':
        logging.debug("Processing a remailer-help request...")
        help = view.respond(
                getRemailerConfig({'senderaddress' : simplifyEmail(message['from'])}), 
                'help.msg',
                From=getRemailerConfig('remailernobodyaddress'),
                To=message['from'],
                Subject='Remailer Help')
        relay.deliver(help)
        pass
    elif subject == 'remailer-key' or subject == 'remailer-keys':
        logging.debug("Processing a remailer-key request...")
        
        privkeys = getKeyStore().listPrivateKeys()
        if len(privkeys) > 1:
            raise Exception("More than one private key found in the keystore...")
        mixKey = getKeyStore().getPublicKey(privkeys[0]).toMixFormat()
        
        mixKey = getRemailerConfig().getMixKeyHeader(privkeys[0]) + "\n\n" + mixKey
        
        keys = ""
        keys += getRemailerConfig().getCapString()
        keys += "\n\n"
        keys += mixKey
        
        mail = MailResponse(To = simplifyEmail(message['from']),
                            From = getRemailerConfig('remailernobodyaddress'),
                            Subject = "Remailer key for " + getRemailerConfig('remailershortname'),
                            Body = keys)
        relay.deliver(mail.to_message())
    else:
        logging.debug("Processing a Message...")
        body = body.strip()

        if body.startswith('destination-block'):
            logging.debug("Processing a destination-block message...")
            pass
        elif body.startswith('::'):
            logging.debug("Processing a Mix Message...")
            mixmsg = MixMessage(body)
            
            #This is where it _should_ go into the pool, but won't for now...
            if mixmsg.PacketType == MixPacketType.IntermediateHop:
                mail = MailResponse(To = mixmsg.deliveryTo(),
                                    From = getRemailerConfig('remailernobodyaddress'),
                                    Subject = mixmsg.deliverySubject(),
                                    Body = mixmsg.deliveryBody())
                relay.deliver(mail.to_message())
                logging.debug("Delivering an Intermediate Hop Message...")
            elif mixmsg.PacketType == MixPacketType.FinalHop:
                for deliveryAddr in mixmsg.deliveryTo():
                    mail = MailResponse(To = deliveryAddr,
                                    From = getRemailerConfig('remailernobodyaddress'),
                                    Subject = mixmsg.deliverySubject(),
                                    Body = mixmsg.deliveryBody())
                    for h, v in mixmsg.deliveryHeaders():
                        mail[h] = v
                    relay.deliver(mail.to_message())
                    logging.debug("Delivering a Final Hop Message...")
            elif mixmsg.PacketType == MixPacketType.DummyMessage:
                logging.debug("Ignoring a Dummy Message...")
            else:  
                logging.debug("Mix Message not understood...", messageId)
                
        elif body.startswith('-----BEGIN PGP MESSAGE-----'):
            logging.debug("Processing a PGP message...")
            pass
        else:
            logging.debug("Passing on a remailer message not understood...")
    return REMAIL    
예제 #43
0
def test_most_basic_form():
    msg = view.respond(locals(), 'template.txt')
    assert msg.Body
예제 #44
0
파일: sample.py 프로젝트: stef/pc-mailer
def otrfp(msg, address=None, host=None):
    sender=collapse_rfc2231_value(msg['from'])
    m=sendere.match(sender)
    res={}
    if m:
        res['sender_name'], res['sender_mail']=m.groups()
    else:
        res['sender_mail']=sender

    for mpart in msg.walk():
        part=to_message(mpart)
        # cut of preamble
        inblock=False
        lines=part.get_payload(decode=True).split('\n')
        i=0
        #logging.info(lines)
        while i<len(lines):
            if not inblock:
                if lines[i].strip()=='-----BEGIN PGP SIGNED MESSAGE-----' or lines[i].strip()=='-----BEGIN PGP MESSAGE-----':
                    inblock=True
                    i+=2
            else:
                if lines[i].strip()=='-----END PGP SIGNATURE-----' or lines[i].strip()=='-----END PGP MESSAGE-----':
                    break
            i+=1
        #logging.info(i)
        if i<len(lines):
            res.update(getpgpmeta(part.get_payload(decode=True)))
            ret=gpg('-d',
                    _ok_code=[0,2],
                    _in=part.get_payload(decode=True))
            #logging.info('ret '+str(ret))
            #logging.info('stderr '+ret.stderr)
            res['msg']='\n'.join(["> %s" % x for x in ret.stdout.split('\n')])
            # extra points,
            #   - no named recipient
            #   - signed
            #logging.info(res['keys'])
            modifiers={'sekrit': False, 'signed': False}
            if len([x for x in res['keys'] if x['key_id']!="0000000000000000"])==0:
                modifiers['sekrit']=True
            else: 
                logging.warn([x for x in res['keys'] if x['key_id']!="0000000000000000"])
            signed={}
            for line in ret.stderr.split('\n'):
                if line.startswith('gpg: Signature made '):
                    # gpg: Signature made Fri 11 May 2012 04:43:04 PM CEST using RSA key ID XXXXXX
                    m=signed1re.match(line)
                    if m:
                        #logging.info(m.groups())
                        signed['date']=dparse(str(m.group(1)))
                        signed['algo']=m.group(2)
                        signed['key_id']=m.group(3)
                elif line.startswith('gpg: Good signature from '):
                    # gpg: Good signature from "name <mail>"
                    m=signed2re.match(line)
                    if m:
                        #logging.info(m.groups())
                        signed['name']=m.group(1)
                        signed['mail']=m.group(2)
                    modifiers['signed']=True
            if not signed:
                plssign = view.respond(res, "plssign.msg",
                                       From=sendermail,
                                       To=sender,
                                       Subject="OTR fingerprint help")
                relay.deliver(plssign)
                continue
            res['signed']=signed
            res['award']=award("you bootstrapped OTR trust using PGP.\n%s" % '\n'.join(["%s [%s]" % (k,'X' if v else ' ') for k,v in modifiers.items()]))
            #logging.info(res)
            jid=None
            fp=None
            secret=None
            for line in to_message(from_string(ret.stdout)).get_payload(decode=True).split('\n'):
                if not line.strip(): continue
                if line=='-- ': break
                if jid and fp:
                    secret=line
                    break
                #logging.info("line "+line)
                m=otrfpre.match(line)
                if m:
                    #logging.info(m.groups())
                    jid, fp = m.group(1), m.group(2)
            if jid and fp:
                with FileLock('%s/otr/otr/%s.fpr' % (basepath, botjid)):
                    fr=open('%s/otr/otr/%s.fpr' % (basepath, botjid), 'r')
                    fw=open('%s/otr/otr/%s.fpr.new' % (basepath, botjid), 'w')
                    for line in fr:
                        #logging.info(line)
                        #logging.info("%s\t%s\tjabber\t%s" % (jid,
                        #                              botjid,
                        #                              fp.lower().replace(' ','')))
                        if line.startswith("%s\t%s\tjabber\t%s" % (jid,
                                                                   botjid,
                                                                   fp.lower().replace(' ',''))):
                            fw.write("%s\t%s\tjabber\t%s\ttrust\n" % (jid,
                                                                    botjid,
                                                                    fp.lower().replace(' ','')))
                        else:
                            fw.write(line)
                    fw.close()
                    fr.close()
                    os.unlink('%s/otr/otr/%s.fpr' % (basepath, botjid))
                    shutil.move('%s/otr/otr/%s.fpr.new' % (basepath, botjid),
                                '%s/otr/otr/%s.fpr' % (basepath, botjid))
            if secret:
                fs=open('%s/otr/otr/%s.s' % (basepath, jid), 'w')
                fs.write("%s %s" % (signed['key_id'], secret))
                fs.close()
            welcome = view.respond(res, "otrtrust.msg",
                           From=sendermail,
                           To=sender,
                           Subject="OTR fingerprint received")
            relay.deliver(welcome)