1 # -*- test-case-name: twisted.test.test_postfix -*-
2 # Copyright (c) Twisted Matrix Laboratories.
3 # See LICENSE for details.
6 Postfix mail transport agent related protocols.
13 from twisted.protocols import basic
14 from twisted.protocols import policies
15 from twisted.internet import protocol, defer
16 from twisted.python import log
18 # urllib's quote functions just happen to match
19 # the postfix semantics.
21 return urllib.quote(s)
24 return urllib.unquote(s)
26 class PostfixTCPMapServer(basic.LineReceiver, policies.TimeoutMixin):
27 """Postfix mail transport agent TCP map protocol implementation.
29 Receive requests for data matching given key via lineReceived,
30 asks it's factory for the data with self.factory.get(key), and
31 returns the data to the requester. None means no entry found.
33 You can use postfix's postmap to test the map service::
35 /usr/sbin/postmap -q KEY tcp:localhost:4242
42 def connectionMade(self):
43 self.setTimeout(self.timeout)
45 def sendCode(self, code, message=''):
46 "Send an SMTP-like code with a message."
47 self.sendLine('%3.3d %s' % (code, message or ''))
49 def lineReceived(self, line):
52 request, params = line.split(None, 1)
57 f = getattr(self, 'do_' + request)
58 except AttributeError:
59 self.sendCode(400, 'unknown command')
64 self.sendCode(400, 'Command %r failed: %s.' % (request, sys.exc_info()[1]))
66 def do_get(self, key):
68 self.sendCode(400, 'Command %r takes 1 parameters.' % 'get')
70 d = defer.maybeDeferred(self.factory.get, key)
71 d.addCallbacks(self._cbGot, self._cbNot)
74 def _cbNot(self, fail):
75 self.sendCode(400, fail.getErrorMessage())
77 def _cbGot(self, value):
81 self.sendCode(200, quote(value))
83 def do_put(self, keyAndValue):
84 if keyAndValue is None:
85 self.sendCode(400, 'Command %r takes 2 parameters.' % 'put')
88 key, value = keyAndValue.split(None, 1)
90 self.sendCode(400, 'Command %r takes 2 parameters.' % 'put')
92 self.sendCode(500, 'put is not implemented yet.')
95 class PostfixTCPMapDictServerFactory(protocol.ServerFactory,
97 """An in-memory dictionary factory for PostfixTCPMapServer."""
99 protocol = PostfixTCPMapServer
101 class PostfixTCPMapDeferringDictServerFactory(protocol.ServerFactory):
102 """An in-memory dictionary factory for PostfixTCPMapServer."""
104 protocol = PostfixTCPMapServer
106 def __init__(self, data=None):
109 self.data.update(data)
112 return defer.succeed(self.data.get(key))