wire.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. """Implement standard (and unused) TCP protocols.
  4. These protocols are either provided by inetd, or are not provided at all.
  5. """
  6. import struct
  7. import time
  8. from zope.interface import implementer
  9. from twisted.internet import interfaces, protocol
  10. class Echo(protocol.Protocol):
  11. """
  12. As soon as any data is received, write it back (RFC 862).
  13. """
  14. def dataReceived(self, data):
  15. self.transport.write(data)
  16. class Discard(protocol.Protocol):
  17. """
  18. Discard any received data (RFC 863).
  19. """
  20. def dataReceived(self, data):
  21. # I'm ignoring you, nyah-nyah
  22. pass
  23. @implementer(interfaces.IProducer)
  24. class Chargen(protocol.Protocol):
  25. """
  26. Generate repeating noise (RFC 864).
  27. """
  28. noise = rb'@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ !"#$%&?'
  29. def connectionMade(self):
  30. self.transport.registerProducer(self, 0)
  31. def resumeProducing(self):
  32. self.transport.write(self.noise)
  33. def pauseProducing(self):
  34. pass
  35. def stopProducing(self):
  36. pass
  37. class QOTD(protocol.Protocol):
  38. """
  39. Return a quote of the day (RFC 865).
  40. """
  41. def connectionMade(self):
  42. self.transport.write(self.getQuote())
  43. self.transport.loseConnection()
  44. def getQuote(self):
  45. """
  46. Return a quote. May be overrriden in subclasses.
  47. """
  48. return b"An apple a day keeps the doctor away.\r\n"
  49. class Who(protocol.Protocol):
  50. """
  51. Return list of active users (RFC 866)
  52. """
  53. def connectionMade(self):
  54. self.transport.write(self.getUsers())
  55. self.transport.loseConnection()
  56. def getUsers(self):
  57. """
  58. Return active users. Override in subclasses.
  59. """
  60. return b"root\r\n"
  61. class Daytime(protocol.Protocol):
  62. """
  63. Send back the daytime in ASCII form (RFC 867).
  64. """
  65. def connectionMade(self):
  66. self.transport.write(time.asctime(time.gmtime(time.time())) + b"\r\n")
  67. self.transport.loseConnection()
  68. class Time(protocol.Protocol):
  69. """
  70. Send back the time in machine readable form (RFC 868).
  71. """
  72. def connectionMade(self):
  73. # is this correct only for 32-bit machines?
  74. result = struct.pack("!i", int(time.time()))
  75. self.transport.write(result)
  76. self.transport.loseConnection()
  77. __all__ = ["Echo", "Discard", "Chargen", "QOTD", "Who", "Daytime", "Time"]