Upstreaming of FeatureUtilities (part one)
[chromium-blink-merge.git] / ipc / ipc_channel_posix.h
blobae2de72f7fe3fa582a90ff379efb4b043b68f1ad
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef IPC_IPC_CHANNEL_POSIX_H_
6 #define IPC_IPC_CHANNEL_POSIX_H_
8 #include "ipc/ipc_channel.h"
10 #include <sys/socket.h> // for CMSG macros
12 #include <queue>
13 #include <set>
14 #include <string>
15 #include <vector>
17 #include "base/message_loop/message_loop.h"
18 #include "base/process/process.h"
19 #include "ipc/file_descriptor_set_posix.h"
20 #include "ipc/ipc_channel_reader.h"
22 #if !defined(OS_MACOSX)
23 // On Linux, the seccomp sandbox makes it very expensive to call
24 // recvmsg() and sendmsg(). The restriction on calling read() and write(), which
25 // are cheap, is that we can't pass file descriptors over them.
27 // As we cannot anticipate when the sender will provide us with file
28 // descriptors, we have to make the decision about whether we call read() or
29 // recvmsg() before we actually make the call. The easiest option is to
30 // create a dedicated socketpair() for exchanging file descriptors. Any file
31 // descriptors are split out of a message, with the non-file-descriptor payload
32 // going over the normal connection, and the file descriptors being sent
33 // separately over the other channel. When read()ing from a channel, we'll
34 // notice if the message was supposed to have come with file descriptors and
35 // use recvmsg on the other socketpair to retrieve them and combine them
36 // back with the rest of the message.
38 // Mac can also run in IPC_USES_READWRITE mode if necessary, but at this time
39 // doesn't take a performance hit from recvmsg and sendmsg, so it doesn't
40 // make sense to waste resources on having the separate dedicated socketpair.
41 // It is however useful for debugging between Linux and Mac to be able to turn
42 // this switch 'on' on the Mac as well.
44 // The HELLO message from the client to the server is always sent using
45 // sendmsg because it will contain the file descriptor that the server
46 // needs to send file descriptors in later messages.
47 #define IPC_USES_READWRITE 1
48 #endif
50 namespace IPC {
52 class ChannelPosix : public Channel,
53 public internal::ChannelReader,
54 public base::MessageLoopForIO::Watcher {
55 public:
56 // Mirror methods of Channel, see ipc_channel.h for description.
57 ChannelPosix(const IPC::ChannelHandle& channel_handle, Mode mode,
58 Listener* listener);
59 virtual ~ChannelPosix();
61 // Channel implementation
62 virtual bool Connect() OVERRIDE;
63 virtual void Close() OVERRIDE;
64 virtual bool Send(Message* message) OVERRIDE;
65 virtual base::ProcessId GetPeerPID() const OVERRIDE;
66 virtual int GetClientFileDescriptor() const OVERRIDE;
67 virtual int TakeClientFileDescriptor() OVERRIDE;
68 virtual bool AcceptsConnections() const OVERRIDE;
69 virtual bool HasAcceptedConnection() const OVERRIDE;
70 virtual bool GetPeerEuid(uid_t* peer_euid) const OVERRIDE;
71 virtual void ResetToAcceptingConnectionState() OVERRIDE;
73 void CloseClientFileDescriptor();
75 static bool IsNamedServerInitialized(const std::string& channel_id);
76 #if defined(OS_LINUX)
77 static void SetGlobalPid(int pid);
78 #endif // OS_LINUX
80 private:
81 bool CreatePipe(const IPC::ChannelHandle& channel_handle);
83 bool ProcessOutgoingMessages();
85 bool AcceptConnection();
86 void ClosePipeOnError();
87 int GetHelloMessageProcId();
88 void QueueHelloMessage();
89 void CloseFileDescriptors(Message* msg);
90 void QueueCloseFDMessage(int fd, int hops);
92 // ChannelReader implementation.
93 virtual ReadState ReadData(char* buffer,
94 int buffer_len,
95 int* bytes_read) OVERRIDE;
96 virtual bool WillDispatchInputMessage(Message* msg) OVERRIDE;
97 virtual bool DidEmptyInputBuffers() OVERRIDE;
98 virtual void HandleInternalMessage(const Message& msg) OVERRIDE;
100 #if defined(IPC_USES_READWRITE)
101 // Reads the next message from the fd_pipe_ and appends them to the
102 // input_fds_ queue. Returns false if there was a message receiving error.
103 // True means there was a message and it was processed properly, or there was
104 // no messages.
105 bool ReadFileDescriptorsFromFDPipe();
106 #endif
108 // Finds the set of file descriptors in the given message. On success,
109 // appends the descriptors to the input_fds_ member and returns true
111 // Returns false if the message was truncated. In this case, any handles that
112 // were sent will be closed.
113 bool ExtractFileDescriptorsFromMsghdr(msghdr* msg);
115 // Closes all handles in the input_fds_ list and clears the list. This is
116 // used to clean up handles in error conditions to avoid leaking the handles.
117 void ClearInputFDs();
119 // MessageLoopForIO::Watcher implementation.
120 virtual void OnFileCanReadWithoutBlocking(int fd) OVERRIDE;
121 virtual void OnFileCanWriteWithoutBlocking(int fd) OVERRIDE;
123 Mode mode_;
125 base::ProcessId peer_pid_;
127 // After accepting one client connection on our server socket we want to
128 // stop listening.
129 base::MessageLoopForIO::FileDescriptorWatcher
130 server_listen_connection_watcher_;
131 base::MessageLoopForIO::FileDescriptorWatcher read_watcher_;
132 base::MessageLoopForIO::FileDescriptorWatcher write_watcher_;
134 // Indicates whether we're currently blocked waiting for a write to complete.
135 bool is_blocked_on_write_;
136 bool waiting_connect_;
138 // If sending a message blocks then we use this variable
139 // to keep track of where we are.
140 size_t message_send_bytes_written_;
142 // File descriptor we're listening on for new connections if we listen
143 // for connections.
144 int server_listen_pipe_;
146 // The pipe used for communication.
147 int pipe_;
149 // For a server, the client end of our socketpair() -- the other end of our
150 // pipe_ that is passed to the client.
151 int client_pipe_;
152 mutable base::Lock client_pipe_lock_; // Lock that protects |client_pipe_|.
154 #if defined(IPC_USES_READWRITE)
155 // Linux/BSD use a dedicated socketpair() for passing file descriptors.
156 int fd_pipe_;
157 int remote_fd_pipe_;
158 #endif
160 // The "name" of our pipe. On Windows this is the global identifier for
161 // the pipe. On POSIX it's used as a key in a local map of file descriptors.
162 std::string pipe_name_;
164 // Messages to be sent are queued here.
165 std::queue<Message*> output_queue_;
167 // We assume a worst case: kReadBufferSize bytes of messages, where each
168 // message has no payload and a full complement of descriptors.
169 static const size_t kMaxReadFDs =
170 (Channel::kReadBufferSize / sizeof(IPC::Message::Header)) *
171 FileDescriptorSet::kMaxDescriptorsPerMessage;
173 // Buffer size for file descriptors used for recvmsg. On Mac the CMSG macros
174 // don't seem to be constant so we have to pick a "large enough" value.
175 #if defined(OS_MACOSX)
176 static const size_t kMaxReadFDBuffer = 1024;
177 #else
178 static const size_t kMaxReadFDBuffer = CMSG_SPACE(sizeof(int) * kMaxReadFDs);
179 #endif
181 // Temporary buffer used to receive the file descriptors from recvmsg.
182 // Code that writes into this should immediately read them out and save
183 // them to input_fds_, since this buffer will be re-used anytime we call
184 // recvmsg.
185 char input_cmsg_buf_[kMaxReadFDBuffer];
187 // File descriptors extracted from messages coming off of the channel. The
188 // handles may span messages and come off different channels from the message
189 // data (in the case of READWRITE), and are processed in FIFO here.
190 // NOTE: The implementation assumes underlying storage here is contiguous, so
191 // don't change to something like std::deque<> without changing the
192 // implementation!
193 std::vector<int> input_fds_;
195 #if defined(OS_MACOSX)
196 // On OSX, sent FDs must not be closed until we get an ack.
197 // Keep track of sent FDs here to make sure the remote is not
198 // trying to bamboozle us.
199 std::set<int> fds_to_close_;
200 #endif
202 // True if we are responsible for unlinking the unix domain socket file.
203 bool must_unlink_;
205 #if defined(OS_LINUX)
206 // If non-zero, overrides the process ID sent in the hello message.
207 static int global_pid_;
208 #endif // OS_LINUX
210 DISALLOW_IMPLICIT_CONSTRUCTORS(ChannelPosix);
213 } // namespace IPC
215 #endif // IPC_IPC_CHANNEL_POSIX_H_