Debian Codegraph @

docs/core/examples/sendfd.py

raw
1 # Copyright (c) Twisted Matrix Laboratories.
2 # See LICENSE for details.
3
4 """
5 Server-side of an example for sending file descriptors between processes over
6 UNIX sockets. This server accepts connections on a UNIX socket and sends one
7 file descriptor to them, along with the name of the file it is associated with.
8
9 To run this example, run this program with two arguments: a path giving a UNIX
10 socket to listen on (must not exist) and a path to a file to send to clients
11 which connect (must exist). For example:
12
13 $ python sendfd.py /tmp/sendfd.sock /etc/motd
14
15 It will listen for client connections until stopped (eg, using Control-C). Most
16 interesting behavior happens on the client side.
17
18 See recvfd.py for the client side of this example.
19 """
20
21 if __name__ == "__main__":
22 import sendfd
23
24 raise SystemExit(sendfd.main())
25
26 import sys
27
28 from twisted.internet import reactor
29 from twisted.internet.protocol import Factory
30 from twisted.protocols.basic import LineOnlyReceiver
31 from twisted.python.filepath import FilePath
32 from twisted.python.log import startLogging
33
34
35 class SendFDProtocol(LineOnlyReceiver):
36 def connectionMade(self):
37 # Open the desired file and keep a reference to it - keeping it open
38 # until we know the other side has it. Closing it early will prevent
39 # it from actually being sent.
40 self.fObj = self.factory.content.open()
41
42 # Tell the transport to send it. It is not necessarily sent when this
43 # method returns. The reactor may need to run for a while longer before
44 # that happens.
45 self.transport.sendFileDescriptor(self.fObj.fileno())
46
47 # Send along *at least* one byte, since one file descriptor was sent.
48 # In this case, send along the name of the file to let the other side
49 # have some idea what they're getting.
50 encoding = sys.getfilesystemencoding()
51 self.sendLine(self.factory.content.path.encode(encoding))
52
53 # Give the other side a minute to deal with this. If they don't close
54 # the connection by then, we will do it for them.
55 self.timeoutCall = reactor.callLater(60, self.transport.loseConnection)
56
57 def connectionLost(self, reason):
58 # Clean up the file object, it is no longer needed.
59 self.fObj.close()
60 self.fObj = None
61
62 # Clean up the timeout, if necessary.
63 if self.timeoutCall.active():
64 self.timeoutCall.cancel()
65 self.timeoutCall = None
66
67
68 def main():
69 address = FilePath(sys.argv[1])
70 content = FilePath(sys.argv[2])
71
72 if address.exists():
73 raise SystemExit("Cannot listen on an existing path")
74
75 if not content.isfile():
76 raise SystemExit("Content file must exist")
77
78 startLogging(sys.stdout)
79
80 serverFactory = Factory()
81 serverFactory.content = content
82 serverFactory.protocol = SendFDProtocol
83
84 reactor.listenUNIX(address.path, serverFactory)
85 reactor.run()