-
Notifications
You must be signed in to change notification settings - Fork 0
/
cookie
executable file
·349 lines (241 loc) · 10.7 KB
/
cookie
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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
#!/usr/bin/env python
import sys, untwisted
from qwer import *
from twisted.internet import reactor
from twisted.python import log
from twisted.web import http
from untwisted import db, promise, rfc5234, rfc5321, rfc5322, smtp, tcp
log.startLogging(sys.stdout)
conn = db.connect(db='cookie', user='root')
# Lookup sender address for recognized recipient or generate sender address for
# unrecognized recipient
def address(recipient):
try:
for cursor in conn:
sender, = cursor.execute('SELECT sender FROM address WHERE address = %s', recipient).next()
except StopIteration:
sender = untwisted.randstr(6, '0123456789abcdefghijklmnopqrstuvwxyz')
for cursor in conn:
cursor.execute('INSERT INTO address (address, sender) VALUES (%s, %s)', recipient, sender)
return sender
@untwisted.call
@promise.resume
def _():
connect = tcp.connect('localhost', 1894)
class server(smtp.server):
class __metaclass__(smtp.server.__metaclass__):
@promise.resume
def __call__(ctx, transport):
ctx = type.__call__(ctx, transport)
# Technically we needn't wait for a downstream connection or greeting
# before processing an upstream MAIL command, but this complicates our
# implementation: We *must* wait for a downstream connection before
# issuing any downstream commands. Receiving a MAIL command before a
# hello command - or receiving *any* command before issuing a greeting
# - is in violation of SMTP specification, so advantage of this
# optimization is vanishing
#
#ctx.client = smtp.pipeline(connect())
#ctx.client.transport.then(untwisted.partial(setattr, ctx.client, 'transport'))
ctx.client = type.__call__(smtp.pipeline, (yield connect()))
# Greeting
transport.write(str((yield ctx.client.reply(untwisted.wildcard))))
# Proxy all commands outside mail transaction
#return ...
raise StopIteration(ctx.mail())
reset = False
class mail(smtp.server.mail):
def __init__(ctx):
smtp.server.mail.__init__(ctx)
ctx.recipient = [].append
def sender(ctx, sender):
ctx.sender = sender
# Finish replying to any previous command before replying to upstream
# client
return ctx.ctx.client.head
@promise.resume
def start(ctx, command, state):
if 'MAIL' == command.verb:
#return ...
raise StopIteration(smtp.server.mail.start(ctx, command, state))
# Finish sending any previous downstream mail transaction before
# issuing any more commands to downstream server
ctx.ctx.reset = yield ctx.ctx.reset
if command.verb in ('EHLO', 'HELO', 'RSET'):
ctx.ctx.reset = False
# Proxy all commands outside mail transaction
ctx.ctx.client.transport.write(str(command))
def callback(command):
try:
reply = yield
except smtp.reply as reply:
if command.verb in ('EHLO', 'HELO', 'RSET'):
ctx.ctx.reset = True
ctx.ctx.transport.write(str(reply))
ctx.ctx.client.reply().then(untwisted.head(lambda: callback(command)))
#return ...
raise StopIteration(state((yield ctx.ctx.command()), state))
@promise.resume
def content(ctx, content):
if (yield ctx.ctx.reset):
ctx.ctx.client.rset().then(lambda _: setattr(ctx.ctx, 'reset', False))
mail = type.__call__(ctx.ctx.client.mail)
# Upstream client authenticated,
# http://thread.gmane.org/gmane.mail.postfix.user/215958
protocol = '(?:ESMTPA|ESMTPSA)'
With = qwer(rfc5322.CFWS, 'with', rfc5322.FWS, protocol)
optInfo = qwer('(?:', rfc5321.via, ')?', With, '(?:', rfc5321.id, ')?(?:', rfc5321.For, ')?(?:', rfc5321.additionalRegisteredClauses, ')?')
stamp = qwer(rfc5321.fromDomain, rfc5321.byDomain, optInfo, '(?:', rfc5322.CFWS, ')?;', rfc5322.FWS, rfc5322.dateTime)
timeStampLine = qwer('Received:', rfc5322.FWS, stamp, rfc5234.CRLF)
try:
timeStampLine.match(content)
# Not authenticated, ESMTPA
except ValueError:
try:
messageId = rfc5322.messageId.search(content, 'idLeft, idRight')
except ValueError:
pass
else:
for recipient in ctx.recipient.__self__:
for cursor in conn:
count, = cursor.execute('SELECT COUNT(*) FROM address WHERE sender = %s', recipient.localPart).next()
if count:
for cursor in conn:
cursor.execute('INSERT INTO message_id (message_id, sender) VALUES (%s, %s)', messageId.join('@'), recipient.localPart)
mail.mail(ctx.sender).then(lambda _: setattr(ctx.ctx, 'reset', True))
for recipient in ctx.recipient.__self__:
mail.rcpt(recipient)
@untwisted.head
def callback():
try:
reply = yield
except smtp.reply as reply:
pass
ctx.ctx.transport.write(str(reply))
(yield mail.data(content)).then(callback)
ctx.ctx.reset = False
#return ...
raise StopIteration(ctx.ctx.mail())
# Authenticated, ESMTPA
def messageId(qwer):
try:
msgId = qwer.search(content, 'msgId ( idLeft, idRight )')
except ValueError:
raise Exception
# In-Reply-To and References can each contain multiple message ids,
# but mail can have only one envelope sender. Iterate over message
# ids until an associated sender address is found and return it
for msgId in msgId:
try:
for cursor in conn:
sender, = cursor.execute('SELECT sender FROM message_id WHERE message_id = %s', msgId['*'].join('@')).next()
return sender
except StopIteration:
pass
raise Exception
def replace(sender, mailbox):
result = 'From:'
if mailbox.nameAddr:
result += str(mailbox.displayName) + str(mailbox['displayName + CFWS']) + '<' + str(mailbox['localPart CFWS:first-child']) + sender + str(mailbox['localPart * + CFWS']) + '@' + str(mailbox['domain CFWS:first-child']) + 'nottheoilrig.com' + str(mailbox['domain * + CFWS']) + '>' + str(mailbox['domain + CFWS'])
else:
result += str(mailbox['localPart CFWS:first-child']) + sender + str(mailbox['localPart * + CFWS']) + '@' + str(mailbox['domain CFWS:first-child']) + 'nottheoilrig.com' + str(mailbox['domain * + CFWS'])
result += '\r\n'
return result
# Replace sender address and send mail to one or many recipients
def send(*recipient):
mail.mail(sender + '@nottheoilrig.com').then(lambda _: setattr(ctx.ctx, 'reset', True))
for recipient in recipient:
mail.rcpt(recipient)
return mail.data(rfc5322.From.replace(untwisted.partial(replace, sender), content, 'mailbox ( nameAddr, displayName, CFWS, localPart, dotAtomText, DQUOTE, domain )', count=1))
try:
sender = yield messageId(rfc5322.inReplyTo)
except Exception:
try:
sender = yield messageId(rfc5322.references)
except Exception:
# Wait for first mail, an unexpected reply falls through, aborting
# this and additional mail. An unexpected reply is caught and
# proxied to the upstream client. All success replies are
# expected, so an unexpected reply is an error
#head, *rest = ctx.recipient.__self__
head, rest = ctx.recipient.__self__[0], ctx.recipient.__self__[1:]
# Closure
sender = address(head)
yield send(head)
if rest:
ctx.ctx.client.head.then(untwisted.compose(ctx.ctx.transport.write, str))
@promise.resume
def sendRest():
# We only get this far if head mail transaction is complete -
# though we don't yet know whether it's an error
reset = False
for recipient in rest:
if reset:
rsetReply = ctx.ctx.client.rset()
sender = address(recipient)
mailReply = mail.mail(sender + '@nottheoilrig.com')
mail.rcpt(recipient)
@untwisted.head
def callback():
try:
yield
except smtp.reply:
# TODO Bounce
pass
try:
(yield mail.data(rfc5322.From.replace(untwisted.partial(replace, sender), content, 'mailbox ( nameAddr, displayName, CFWS, localPart, dotAtomText, DQUOTE, domain )', count=1))).then(callback)
except smtp.reply:
# Damn, can't rebind reset in nested scope!
try:
yield rsetReply
reset = False
except (smtp.reply, UnboundLocalError):
pass
try:
yield mailReply
reset = True
except smtp.reply:
pass
# TODO Bounce
#return ...
raise StopIteration(reset)
ctx.ctx.reset = sendRest()
else:
@untwisted.head
def callback():
try:
reply = yield
except smtp.reply as reply:
pass
ctx.ctx.transport.write(str(reply))
ctx.ctx.client.head.then(callback)
#return ...
raise StopIteration(ctx.ctx.mail())
@untwisted.head
def callback():
try:
reply = yield
except smtp.reply as reply:
pass
ctx.ctx.transport.write(str(reply))
(yield send(*ctx.recipient.__self__)).then(callback)
ctx.ctx.reset = False
listen = tcp.listen(1438, interface='localhost')
while True:
server((yield listen()))
@untwisted.call
class factory(http.HTTPFactory):
class protocol(http.HTTPChannel):
class requestFactory(http.Request):
def requestReceived(ctx, method, resource, version):
ctx.client = ctx.channel.transport.getPeer()
ctx.clientproto = version
try:
qwer('/', rfc5322.addrSpec).match(resource)
except ValueError:
ctx.setResponseCode(http.NOT_FOUND)
else:
ctx.write(address(resource[1:]))
ctx.finish()
reactor.listenTCP(8743, factory, interface='localhost')
reactor.run()