aboutsummaryrefslogtreecommitdiffstats
path: root/pygn2m
blob: 4acd2f2955ae8929651b722bd8de681015d683c5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""News to mail gateway script. Copyright 2000 Cosimo Alfarano

Author: Cosimo Alfarano
Date: June 11 2000

pygs - Copyright 2000 by Cosimo Alfarano <Alfarano@Students.CS.UniBo.It>
You can use this software under the terms of the GPL. If we meet some day,
and you think this stuff is worth it, you can buy me a beer in return.

Thanks to md for this useful formula. Beer is beer.

Gets news article from stdin and sends it via SMTP.
"""
from __future__ import print_function
import sys
import os
import argparse

sys.path.append('/usr/lib/pyg')

import whitelist
import news2mail
from mail2news import VERSION, DESC


def parse_cmdline():
    """
    set a dictionary with smtp new header in gw parameter (gw.smtpheads)
    return (test,verbose) boolean tuple
    """
    parser = argparse.ArgumentParser(
        description='pyg version %s - Copyright 2000 Cosimo Alfarano\n%s' %
        (VERSION, DESC))

    parser.add_argument('-H', '--smtpserver', default='')
    parser.add_argument('-s', '--sender', required=True, default='')
    parser.add_argument('-e', '--envelope', default='')
    parser.add_argument('-t', '--to', dest='rcpt', required=True)
    parser.add_argument('-w', '--wlfile')
    parser.add_argument('-l', '--logfile')

    parser.add_argument('-T', '--test',
                        help='test mode (not send article via SMTP)',
                        action='store_true')
    parser.add_argument('-d', '--debug',
                        action='store_true')
    parser.add_argument('-V', '--verbose', help='verbose output',
                        action='store_true')

    opts = parser.parse_args()

#  By rfc822 [Resent-]Sender: should be ever set, unless == From:
# (not this case). Should be a human, while [Resent-]From: may be a program.

    if opts.rcpt == '' or opts.sender == '':
        raise argparse.ArgumentError('missing command line option')

    if opts.envelope == '' and opts.sender != '':
        opts.envelope = opts.sender

    return opts


"""main is structured in 4 phases:
    1) check and set pyg's internal variables
    2) check whitelist for users' permission
    3) format rfc 822 headers from input article
    4) open smtp connection and send e-mail
"""

try:

    """phase 1:
    check and set pyg's internal variables
    """

    n2m = news2mail.news2mail()
    owner = None

    # it returns only test, other parms are set directly in the actual
    # parameter
    args = parse_cmdline()

    # check if n2m has some file prefercences set on commandline
    if args.wlfile is None:
        wl = os.path.expanduser('~/pyg.whitelist')
    else:
        wl = args.wlfile

    if args.logfile is None:
        log = os.path.expanduser('~/pyg.log')
    else:
        log = args.logfile

#     print 'using %s %s\n' % (wl,log)

    wl = whitelist.whitelist(wl, log)

    # reads stdin and parses article separating head from body
    n2m.readfile()
#    n2m.parsearticle()

    """phase 2:
    check whitelist for user's permission
    """

    # make a first check of From: address
    owner = wl.checkfrom(n2m.nntpheads['From'])
    if owner is None:
        if sys.stdin.isatty() == 1 or args.test:
            print ('"%s" is not in whitelist!' % (n2m.nntpheads['From'][:-1]))
        else:
            wl.logmsg(n2m.nntpheads, wl.DENY)

        # if verbose, I want to print out headers, so I can't
        # exit now.
        if not args.verbose:
            sys.exit(1)

    """phase 3:
    format rfc 822 headers from input article
    """

    n2m.mergeheads()  # make unique dict from NNTP and SMTP dicts

    n2m.addheads()  # add some important heads
    n2m.renameheads()  # rename useless heads
    n2m.removeheads()  # remove other heads

    n2m.sortheads()  # sort remaining heads :)

    # prints formatted email message only (without send) if user wants
    if args.verbose:
        for line in n2m.headers:
            print(line)

    if owner is None:
        sys.exit(1)

    """phase 4:
    open smtp connection and send e-mail
    """

    if len(n2m.headers) > 0:
        wl.logmsg(n2m.heads_dict, wl.ACCEPT, owner)
        if not args.test:
            n2m.sendarticle()
    else:
        print('Error: No Headers!!!')

except KeyboardInterrupt:
    print('Keyboard Interrupt')
    sys.exit(1)