You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

postfix.py 3.9KB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. # -*- test-case-name: twisted.test.test_postfix -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Postfix mail transport agent related protocols.
  6. """
  7. import sys
  8. try:
  9. # Python 2
  10. from UserDict import UserDict
  11. except ImportError:
  12. # Python 3
  13. from collections import UserDict
  14. try:
  15. # Python 2
  16. from urllib import quote as _quote, unquote as _unquote
  17. except ImportError:
  18. # Python 3
  19. from urllib.parse import quote as _quote, unquote as _unquote
  20. from twisted.protocols import basic
  21. from twisted.protocols import policies
  22. from twisted.internet import protocol, defer
  23. from twisted.python import log
  24. from twisted.python.compat import unicode
  25. # urllib's quote functions just happen to match
  26. # the postfix semantics.
  27. def quote(s):
  28. quoted = _quote(s)
  29. if isinstance(quoted, unicode):
  30. quoted = quoted.encode("ascii")
  31. return quoted
  32. def unquote(s):
  33. if isinstance(s, bytes):
  34. s = s.decode("ascii")
  35. quoted = _unquote(s)
  36. return quoted.encode("ascii")
  37. class PostfixTCPMapServer(basic.LineReceiver, policies.TimeoutMixin):
  38. """
  39. Postfix mail transport agent TCP map protocol implementation.
  40. Receive requests for data matching given key via lineReceived,
  41. asks it's factory for the data with self.factory.get(key), and
  42. returns the data to the requester. None means no entry found.
  43. You can use postfix's postmap to test the map service::
  44. /usr/sbin/postmap -q KEY tcp:localhost:4242
  45. """
  46. timeout = 600
  47. delimiter = b'\n'
  48. def connectionMade(self):
  49. self.setTimeout(self.timeout)
  50. def sendCode(self, code, message=b''):
  51. """
  52. Send an SMTP-like code with a message.
  53. """
  54. self.sendLine(str(code).encode("ascii") + b' ' + message)
  55. def lineReceived(self, line):
  56. self.resetTimeout()
  57. try:
  58. request, params = line.split(None, 1)
  59. except ValueError:
  60. request = line
  61. params = None
  62. try:
  63. f = getattr(self, u'do_' + request.decode("ascii"))
  64. except AttributeError:
  65. self.sendCode(400, b'unknown command')
  66. else:
  67. try:
  68. f(params)
  69. except:
  70. excInfo = str(sys.exc_info()[1]).encode("ascii")
  71. self.sendCode(400, b'Command ' + request + b' failed: ' +
  72. excInfo)
  73. def do_get(self, key):
  74. if key is None:
  75. self.sendCode(400, b"Command 'get' takes 1 parameters.")
  76. else:
  77. d = defer.maybeDeferred(self.factory.get, key)
  78. d.addCallbacks(self._cbGot, self._cbNot)
  79. d.addErrback(log.err)
  80. def _cbNot(self, fail):
  81. msg = fail.getErrorMessage().encode("ascii")
  82. self.sendCode(400, msg)
  83. def _cbGot(self, value):
  84. if value is None:
  85. self.sendCode(500)
  86. else:
  87. self.sendCode(200, quote(value))
  88. def do_put(self, keyAndValue):
  89. if keyAndValue is None:
  90. self.sendCode(400, b"Command 'put' takes 2 parameters.")
  91. else:
  92. try:
  93. key, value = keyAndValue.split(None, 1)
  94. except ValueError:
  95. self.sendCode(400, b"Command 'put' takes 2 parameters.")
  96. else:
  97. self.sendCode(500, b'put is not implemented yet.')
  98. class PostfixTCPMapDictServerFactory(UserDict, protocol.ServerFactory):
  99. """
  100. An in-memory dictionary factory for PostfixTCPMapServer.
  101. """
  102. protocol = PostfixTCPMapServer
  103. class PostfixTCPMapDeferringDictServerFactory(protocol.ServerFactory):
  104. """
  105. An in-memory dictionary factory for PostfixTCPMapServer.
  106. """
  107. protocol = PostfixTCPMapServer
  108. def __init__(self, data=None):
  109. self.data = {}
  110. if data is not None:
  111. self.data.update(data)
  112. def get(self, key):
  113. return defer.succeed(self.data.get(key))