Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(72)

Side by Side Diff: ipc/ipc_channel_posix.cc

Issue 5749001: Add support for sockets that can listen and accept a connection. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Fix up use of DCHECK which was causing release build failures Created 10 years ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « ipc/ipc_channel_posix.h ('k') | ipc/ipc_channel_posix_unittest.cc » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright (c) 2010 The Chromium Authors. All rights reserved. 1 // Copyright (c) 2010 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "ipc/ipc_channel_posix.h" 5 #include "ipc/ipc_channel_posix.h"
6 6
7 #include <errno.h> 7 #include <errno.h>
8 #include <fcntl.h> 8 #include <fcntl.h>
9 #include <stddef.h> 9 #include <stddef.h>
10 #include <sys/types.h> 10 #include <sys/types.h>
11 #include <sys/socket.h> 11 #include <sys/socket.h>
12 #include <sys/stat.h> 12 #include <sys/stat.h>
13 #include <sys/un.h> 13 #include <sys/un.h>
14 14
15 #include <string> 15 #include <string>
16 #include <map> 16 #include <map>
17 17
18 #include "base/command_line.h" 18 #include "base/command_line.h"
19 #include "base/eintr_wrapper.h" 19 #include "base/eintr_wrapper.h"
20 #include "base/file_path.h"
21 #include "base/file_util.h"
20 #include "base/global_descriptors_posix.h" 22 #include "base/global_descriptors_posix.h"
21 #include "base/lock.h" 23 #include "base/lock.h"
22 #include "base/logging.h" 24 #include "base/logging.h"
23 #include "base/process_util.h" 25 #include "base/process_util.h"
24 #include "base/scoped_ptr.h" 26 #include "base/scoped_ptr.h"
25 #include "base/singleton.h" 27 #include "base/singleton.h"
26 #include "base/string_util.h" 28 #include "base/string_util.h"
27 #include "ipc/ipc_descriptors.h" 29 #include "ipc/ipc_descriptors.h"
28 #include "ipc/ipc_switches.h" 30 #include "ipc/ipc_switches.h"
29 #include "ipc/file_descriptor_set_posix.h" 31 #include "ipc/file_descriptor_set_posix.h"
30 #include "ipc/ipc_logging.h" 32 #include "ipc/ipc_logging.h"
31 #include "ipc/ipc_message_utils.h" 33 #include "ipc/ipc_message_utils.h"
32 34
33 namespace IPC { 35 namespace IPC {
34 36
35 // IPC channels on Windows use named pipes (CreateNamedPipe()) with 37 // IPC channels on Windows use named pipes (CreateNamedPipe()) with
36 // channel ids as the pipe names. Channels on POSIX use anonymous 38 // channel ids as the pipe names. Channels on POSIX use sockets as
37 // Unix domain sockets created via socketpair() as pipes. These don't 39 // pipes These don't quite line up.
38 // quite line up.
39 // 40 //
40 // When creating a child subprocess, the parent side of the fork 41 // When creating a child subprocess we use a socket pair and the parent side of
41 // arranges it such that the initial control channel ends up on the 42 // the fork arranges it such that the initial control channel ends up on the
42 // magic file descriptor kPrimaryIPCChannel in the child. Future 43 // magic file descriptor kPrimaryIPCChannel in the child. Future
43 // connections (file descriptors) can then be passed via that 44 // connections (file descriptors) can then be passed via that
44 // connection via sendmsg(). 45 // connection via sendmsg().
46 //
47 // A POSIX IPC channel can also be set up as a server for a bound UNIX domain
48 // socket, and will handle multiple connect and disconnect sequences. Currently
49 // it is limited to one connection at a time.
45 50
46 //------------------------------------------------------------------------------ 51 //------------------------------------------------------------------------------
47 namespace { 52 namespace {
48 53
49 // The PipeMap class works around this quirk related to unit tests: 54 // The PipeMap class works around this quirk related to unit tests:
50 // 55 //
51 // When running as a server, we install the client socket in a 56 // When running as a server, we install the client socket in a
52 // specific file descriptor number (@kPrimaryIPCChannel). However, we 57 // specific file descriptor number (@kPrimaryIPCChannel). However, we
53 // also have to support the case where we are running unittests in the 58 // also have to support the case where we are running unittests in the
54 // same process. (We do not support forking without execing.) 59 // same process. (We do not support forking without execing.)
(...skipping 66 matching lines...) Expand 10 before | Expand all | Expand 10 after
121 } 126 }
122 127
123 private: 128 private:
124 Lock lock_; 129 Lock lock_;
125 typedef std::map<std::string, int> ChannelToFDMap; 130 typedef std::map<std::string, int> ChannelToFDMap;
126 ChannelToFDMap map_; 131 ChannelToFDMap map_;
127 132
128 friend struct DefaultSingletonTraits<PipeMap>; 133 friend struct DefaultSingletonTraits<PipeMap>;
129 }; 134 };
130 135
131 // Used to map a channel name to the equivalent FD # in the current process.
132 // Returns -1 if the channel is unknown.
133 int ChannelNameToFD(const std::string& channel_id) {
134 // See the large block comment above PipeMap for the reasoning here.
135 const int fd = PipeMap::GetInstance()->Lookup(channel_id);
136
137 if (fd != -1) {
138 int dup_fd = dup(fd);
139 if (dup_fd < 0)
140 PLOG(FATAL) << "dup(" << fd << ") " << channel_id;
141 return dup_fd;
142 }
143
144 return fd;
145 }
146
147 //------------------------------------------------------------------------------ 136 //------------------------------------------------------------------------------
148 // The standard size on linux is 108, mac is 104. To maintain consistency 137 // Verify that kMaxPipeNameLength is a decent size.
149 // across platforms we standardize on the smaller value.
150 const size_t kMaxPipeNameLength = 104;
151 COMPILE_ASSERT(sizeof(((sockaddr_un*)0)->sun_path) >= kMaxPipeNameLength, 138 COMPILE_ASSERT(sizeof(((sockaddr_un*)0)->sun_path) >= kMaxPipeNameLength,
152 BAD_SUN_PATH_LENGTH); 139 BAD_SUN_PATH_LENGTH);
153 140
154 // Creates a Fifo with the specified name ready to listen on. 141 // Creates a unix domain socket bound to the specified name that is listening
155 bool CreateServerFifo(const std::string& pipe_name, int* server_listen_fd) { 142 // for connections.
143 bool CreateServerUnixDomainSocket(const std::string& pipe_name,
144 int* server_listen_fd) {
156 DCHECK(server_listen_fd); 145 DCHECK(server_listen_fd);
157 DCHECK_GT(pipe_name.length(), 0u); 146 DCHECK_GT(pipe_name.length(), 0u);
158 DCHECK_LT(pipe_name.length(), kMaxPipeNameLength); 147 DCHECK_LT(pipe_name.length(), kMaxPipeNameLength);
159 148
160 if (pipe_name.length() == 0 || pipe_name.length() >= kMaxPipeNameLength) { 149 if (pipe_name.length() == 0 || pipe_name.length() >= kMaxPipeNameLength) {
161 return false; 150 return false;
162 } 151 }
163 152
164 // Create socket. 153 // Create socket.
165 int fd = socket(AF_UNIX, SOCK_STREAM, 0); 154 int fd = socket(AF_UNIX, SOCK_STREAM, 0);
166 if (fd < 0) { 155 if (fd < 0) {
167 return false; 156 return false;
168 } 157 }
169 158
170 // Make socket non-blocking 159 // Make socket non-blocking
171 if (fcntl(fd, F_SETFL, O_NONBLOCK) == -1) { 160 if (fcntl(fd, F_SETFL, O_NONBLOCK) == -1) {
172 PLOG(ERROR) << "fcntl " << pipe_name; 161 PLOG(ERROR) << "fcntl(O_NONBLOCK) " << pipe_name;
173 if (HANDLE_EINTR(close(fd)) < 0) 162 if (HANDLE_EINTR(close(fd)) < 0)
174 PLOG(ERROR) << "close " << pipe_name; 163 PLOG(ERROR) << "close " << pipe_name;
175 return false; 164 return false;
176 } 165 }
177 166
178 // Delete any old FS instances. 167 // Delete any old FS instances.
179 unlink(pipe_name.c_str()); 168 unlink(pipe_name.c_str());
180 169
170 // Make sure the path we need exists.
171 FilePath path(pipe_name);
172 FilePath dir_path = path.DirName();
173 if (!file_util::CreateDirectory(dir_path)) {
174 return false;
175 }
176
181 // Create unix_addr structure 177 // Create unix_addr structure
182 struct sockaddr_un unix_addr; 178 struct sockaddr_un unix_addr;
183 memset(&unix_addr, 0, sizeof(unix_addr)); 179 memset(&unix_addr, 0, sizeof(unix_addr));
184 unix_addr.sun_family = AF_UNIX; 180 unix_addr.sun_family = AF_UNIX;
185 snprintf(unix_addr.sun_path, kMaxPipeNameLength, "%s", pipe_name.c_str()); 181 int path_len = snprintf(unix_addr.sun_path, IPC::kMaxPipeNameLength,
186 size_t unix_addr_len = offsetof(struct sockaddr_un, sun_path) + 182 "%s", pipe_name.c_str());
187 strlen(unix_addr.sun_path) + 1; 183 DCHECK_EQ(static_cast<int>(pipe_name.length()), path_len);
184 size_t unix_addr_len = offsetof(struct sockaddr_un,
185 sun_path) + path_len + 1;
188 186
189 // Bind the socket. 187 // Bind the socket.
190 if (bind(fd, reinterpret_cast<const sockaddr*>(&unix_addr), 188 if (bind(fd, reinterpret_cast<const sockaddr*>(&unix_addr),
191 unix_addr_len) != 0) { 189 unix_addr_len) != 0) {
192 PLOG(ERROR) << "bind " << pipe_name; 190 PLOG(ERROR) << "bind " << pipe_name;
193 if (HANDLE_EINTR(close(fd)) < 0) 191 if (HANDLE_EINTR(close(fd)) < 0)
194 PLOG(ERROR) << "close " << pipe_name; 192 PLOG(ERROR) << "close " << pipe_name;
195 return false; 193 return false;
196 } 194 }
197 195
198 // Start listening on the socket. 196 // Start listening on the socket.
199 const int listen_queue_length = 1; 197 const int listen_queue_length = 1;
200 if (listen(fd, listen_queue_length) != 0) { 198 if (listen(fd, listen_queue_length) != 0) {
201 PLOG(ERROR) << "listen " << pipe_name; 199 PLOG(ERROR) << "listen " << pipe_name;
202 if (HANDLE_EINTR(close(fd)) < 0) 200 if (HANDLE_EINTR(close(fd)) < 0)
203 PLOG(ERROR) << "close " << pipe_name; 201 PLOG(ERROR) << "close " << pipe_name;
204 return false; 202 return false;
205 } 203 }
206 204
207 *server_listen_fd = fd; 205 *server_listen_fd = fd;
208 return true; 206 return true;
209 } 207 }
210 208
211 // Accept a connection on a fifo. 209 // Accept a connection on a socket we are listening to.
212 bool ServerAcceptFifoConnection(int server_listen_fd, int* server_socket) { 210 bool ServerAcceptConnection(int server_listen_fd, int* server_socket) {
213 DCHECK(server_socket); 211 DCHECK(server_socket);
214 212
215 int accept_fd = HANDLE_EINTR(accept(server_listen_fd, NULL, 0)); 213 int accept_fd = HANDLE_EINTR(accept(server_listen_fd, NULL, 0));
216 if (accept_fd < 0) 214 if (accept_fd < 0)
217 return false; 215 return false;
218 if (fcntl(accept_fd, F_SETFL, O_NONBLOCK) == -1) { 216 if (fcntl(accept_fd, F_SETFL, O_NONBLOCK) == -1) {
219 PLOG(ERROR) << "fcntl " << accept_fd; 217 PLOG(ERROR) << "fcntl(O_NONBLOCK) " << accept_fd;
220 if (HANDLE_EINTR(close(accept_fd)) < 0) 218 if (HANDLE_EINTR(close(accept_fd)) < 0)
221 PLOG(ERROR) << "close " << accept_fd; 219 PLOG(ERROR) << "close " << accept_fd;
222 return false; 220 return false;
223 } 221 }
224 222
225 *server_socket = accept_fd; 223 *server_socket = accept_fd;
226 return true; 224 return true;
227 } 225 }
228 226
229 bool ClientConnectToFifo(const std::string &pipe_name, int* client_socket) { 227 bool CreateClientUnixDomainSocket(const std::string& pipe_name,
228 int* client_socket) {
230 DCHECK(client_socket); 229 DCHECK(client_socket);
231 DCHECK_GT(pipe_name.length(), 0u); 230 DCHECK_GT(pipe_name.length(), 0u);
232 DCHECK_LT(pipe_name.length(), kMaxPipeNameLength); 231 DCHECK_LT(pipe_name.length(), kMaxPipeNameLength);
233 232
234 if (pipe_name.length() == 0 || pipe_name.length() >= kMaxPipeNameLength) { 233 if (pipe_name.length() == 0 || pipe_name.length() >= kMaxPipeNameLength) {
235 return false; 234 return false;
236 } 235 }
237 236
238 // Create socket. 237 // Create socket.
239 int fd = socket(AF_UNIX, SOCK_STREAM, 0); 238 int fd = socket(AF_UNIX, SOCK_STREAM, 0);
240 if (fd < 0) { 239 if (fd < 0) {
241 PLOG(ERROR) << "socket " << pipe_name; 240 PLOG(ERROR) << "socket " << pipe_name;
242 return false; 241 return false;
243 } 242 }
244 243
245 // Make socket non-blocking 244 // Make socket non-blocking
246 if (fcntl(fd, F_SETFL, O_NONBLOCK) == -1) { 245 if (fcntl(fd, F_SETFL, O_NONBLOCK) == -1) {
247 PLOG(ERROR) << "fcntl " << pipe_name; 246 PLOG(ERROR) << "fcntl(O_NONBLOCK) " << pipe_name;
248 if (HANDLE_EINTR(close(fd)) < 0) 247 if (HANDLE_EINTR(close(fd)) < 0)
249 PLOG(ERROR) << "close " << pipe_name; 248 PLOG(ERROR) << "close " << pipe_name;
250 return false; 249 return false;
251 } 250 }
252 251
253 // Create server side of socket. 252 // Create server side of socket.
254 struct sockaddr_un server_unix_addr; 253 struct sockaddr_un server_unix_addr;
255 memset(&server_unix_addr, 0, sizeof(server_unix_addr)); 254 memset(&server_unix_addr, 0, sizeof(server_unix_addr));
256 server_unix_addr.sun_family = AF_UNIX; 255 server_unix_addr.sun_family = AF_UNIX;
257 snprintf(server_unix_addr.sun_path, kMaxPipeNameLength, "%s", 256 int path_len = snprintf(server_unix_addr.sun_path, IPC::kMaxPipeNameLength,
258 pipe_name.c_str()); 257 "%s", pipe_name.c_str());
259 size_t server_unix_addr_len = offsetof(struct sockaddr_un, sun_path) + 258 DCHECK_EQ(static_cast<int>(pipe_name.length()), path_len);
260 strlen(server_unix_addr.sun_path) + 1; 259 size_t server_unix_addr_len = offsetof(struct sockaddr_un,
260 sun_path) + path_len + 1;
261 261
262 if (HANDLE_EINTR(connect(fd, reinterpret_cast<sockaddr*>(&server_unix_addr), 262 if (HANDLE_EINTR(connect(fd, reinterpret_cast<sockaddr*>(&server_unix_addr),
263 server_unix_addr_len)) != 0) { 263 server_unix_addr_len)) != 0) {
264 PLOG(ERROR) << "connect " << pipe_name; 264 PLOG(ERROR) << "connect " << pipe_name;
265 if (HANDLE_EINTR(close(fd)) < 0) 265 if (HANDLE_EINTR(close(fd)) < 0)
266 PLOG(ERROR) << "close " << pipe_name; 266 PLOG(ERROR) << "close " << pipe_name;
267 return false; 267 return false;
268 } 268 }
269 269
270 *client_socket = fd; 270 *client_socket = fd;
271 return true; 271 return true;
272 } 272 }
273 273
274 bool SocketWriteErrorIsRecoverable() { 274 bool SocketWriteErrorIsRecoverable() {
275 #if defined(OS_MACOSX) 275 #if defined(OS_MACOSX)
276 // On OS X if sendmsg() is trying to send fds between processes and there 276 // On OS X if sendmsg() is trying to send fds between processes and there
277 // isn't enough room in the output buffer to send the fd structure over 277 // isn't enough room in the output buffer to send the fd structure over
278 // atomically then EMSGSIZE is returned. 278 // atomically then EMSGSIZE is returned.
279 // 279 //
280 // EMSGSIZE presents a problem since the system APIs can only call us when 280 // EMSGSIZE presents a problem since the system APIs can only call us when
281 // there's room in the socket buffer and not when there is "enough" room. 281 // there's room in the socket buffer and not when there is "enough" room.
282 // 282 //
283 // The current behavior is to return to the event loop when EMSGSIZE is 283 // The current behavior is to return to the event loop when EMSGSIZE is
284 // received and hopefull service another FD. This is however still 284 // received and hopefull service another FD. This is however still
285 // technically a busy wait since the event loop will call us right back until 285 // technically a busy wait since the event loop will call us right back until
286 // the receiver has read enough data to allow passing the FD over atomically. 286 // the receiver has read enough data to allow passing the FD over atomically.
287 return errno == EAGAIN || errno == EMSGSIZE; 287 return errno == EAGAIN || errno == EMSGSIZE;
288 #else 288 #else
289 return errno == EAGAIN; 289 return errno == EAGAIN;
290 #endif 290 #endif // OS_MACOSX
291 } 291 }
292 292
293 } // namespace 293 } // namespace
294 //------------------------------------------------------------------------------ 294 //------------------------------------------------------------------------------
295 295
296 Channel::ChannelImpl::ChannelImpl(const IPC::ChannelHandle& channel_handle, 296 Channel::ChannelImpl::ChannelImpl(const IPC::ChannelHandle& channel_handle,
297 Mode mode, Listener* listener) 297 Mode mode, Listener* listener)
298 : mode_(mode), 298 : mode_(mode),
299 is_blocked_on_write_(false), 299 is_blocked_on_write_(false),
300 waiting_connect_(true),
300 message_send_bytes_written_(0), 301 message_send_bytes_written_(0),
301 uses_fifo_(CommandLine::ForCurrentProcess()->HasSwitch(
302 switches::kIPCUseFIFO)),
303 server_listen_pipe_(-1), 302 server_listen_pipe_(-1),
304 pipe_(-1), 303 pipe_(-1),
305 client_pipe_(-1), 304 client_pipe_(-1),
306 #if defined(IPC_USES_READWRITE) 305 #if defined(IPC_USES_READWRITE)
307 fd_pipe_(-1), 306 fd_pipe_(-1),
308 remote_fd_pipe_(-1), 307 remote_fd_pipe_(-1),
309 #endif 308 #endif // IPC_USES_READWRITE
309 pipe_name_(channel_handle.name),
310 listener_(listener), 310 listener_(listener),
311 waiting_connect_(true), 311 must_unlink_(false),
312 factory_(this) { 312 factory_(this) {
313 if (!CreatePipe(channel_handle, mode_)) { 313 // Check to see if we want to implement using domain sockets.
314 bool uses_domain_socket = false;
315 bool listening_socket = false;
316 if (mode_ == MODE_NAMED_SERVER) {
317 uses_domain_socket = true;
318 listening_socket = true;
319 mode_ = MODE_SERVER;
320 } else if (mode_ == MODE_NAMED_CLIENT) {
321 uses_domain_socket = true;
322 mode_ = MODE_CLIENT;
323 }
324 if (!CreatePipe(channel_handle, uses_domain_socket, listening_socket)) {
325 // The pipe may have been closed already.
326 const char *modestr = (mode_ == MODE_SERVER
327 || mode_ == MODE_NAMED_SERVER) ? "server" : "client";
314 // The pipe may have been closed already. 328 // The pipe may have been closed already.
315 LOG(WARNING) << "Unable to create pipe named \"" << channel_handle.name 329 LOG(WARNING) << "Unable to create pipe named \"" << channel_handle.name
316 << "\" in " << (mode_ == MODE_SERVER ? "server" : "client") 330 << "\" in " << modestr << " mode";
317 << " mode";
318 } 331 }
319 } 332 }
320 333
321 Channel::ChannelImpl::~ChannelImpl() { 334 Channel::ChannelImpl::~ChannelImpl() {
322 Close(); 335 Close();
323 } 336 }
324 337
325 // static
326 void AddChannelSocket(const std::string& name, int socket) {
327 PipeMap::GetInstance()->Insert(name, socket);
328 }
329
330 // static
331 void RemoveAndCloseChannelSocket(const std::string& name) {
332 PipeMap::GetInstance()->RemoveAndClose(name);
333 }
334
335 // static
336 bool ChannelSocketExists(const std::string& name) {
337 return PipeMap::GetInstance()->Lookup(name) != -1;
338 }
339
340 // static
341 bool SocketPair(int* fd1, int* fd2) { 338 bool SocketPair(int* fd1, int* fd2) {
342 int pipe_fds[2]; 339 int pipe_fds[2];
343 if (socketpair(AF_UNIX, SOCK_STREAM, 0, pipe_fds) != 0) { 340 if (socketpair(AF_UNIX, SOCK_STREAM, 0, pipe_fds) != 0) {
344 PLOG(ERROR) << "socketpair()"; 341 PLOG(ERROR) << "socketpair()";
345 return false; 342 return false;
346 } 343 }
347 344
348 // Set both ends to be non-blocking. 345 // Set both ends to be non-blocking.
349 if (fcntl(pipe_fds[0], F_SETFL, O_NONBLOCK) == -1 || 346 if (fcntl(pipe_fds[0], F_SETFL, O_NONBLOCK) == -1 ||
350 fcntl(pipe_fds[1], F_SETFL, O_NONBLOCK) == -1) { 347 fcntl(pipe_fds[1], F_SETFL, O_NONBLOCK) == -1) {
351 PLOG(ERROR) << "fcntl(O_NONBLOCK)"; 348 PLOG(ERROR) << "fcntl(O_NONBLOCK)";
352 if (HANDLE_EINTR(close(pipe_fds[0])) < 0) 349 if (HANDLE_EINTR(close(pipe_fds[0])) < 0)
353 PLOG(ERROR) << "close"; 350 PLOG(ERROR) << "close";
354 if (HANDLE_EINTR(close(pipe_fds[1])) < 0) 351 if (HANDLE_EINTR(close(pipe_fds[1])) < 0)
355 PLOG(ERROR) << "close"; 352 PLOG(ERROR) << "close";
356 return false; 353 return false;
357 } 354 }
358 355
359 *fd1 = pipe_fds[0]; 356 *fd1 = pipe_fds[0];
360 *fd2 = pipe_fds[1]; 357 *fd2 = pipe_fds[1];
361 358
362 return true; 359 return true;
363 } 360 }
364 361
365 bool Channel::ChannelImpl::CreatePipe(const IPC::ChannelHandle &channel_handle, 362 bool Channel::ChannelImpl::CreatePipe(const IPC::ChannelHandle& channel_handle,
366 Mode mode) { 363 bool uses_domain_sockets,
364 bool listening_socket) {
367 DCHECK(server_listen_pipe_ == -1 && pipe_ == -1); 365 DCHECK(server_listen_pipe_ == -1 && pipe_ == -1);
368 pipe_name_ = channel_handle.name; 366
369 pipe_ = channel_handle.socket.fd; 367 // Four possible cases:
370 if (uses_fifo_) { 368 // 1) It's a channel wrapping a pipe that is given to us.
371 // This only happens in unit tests; see the comment above PipeMap. 369 // 2) It's for a named channel, so we create it.
372 // TODO(playmobil): We shouldn't need to create fifos on disk. 370 // 3) It's for a client that we implement ourself. This is used
373 // TODO(playmobil): If we do, they should be in the user data directory. 371 // in unittesting.
374 // TODO(playmobil): Cleanup any stale fifos. 372 // 4) It's the initial IPC channel:
375 if (mode == MODE_SERVER) { 373 // 4a) Client side: Pull the pipe out of the GlobalDescriptors set.
376 if (!CreateServerFifo(pipe_name_, &server_listen_pipe_)) { 374 // 4b) Server side: create the pipe.
375
376 if (channel_handle.socket.fd != -1) {
377 // Case 1 from comment above.
378 pipe_ = channel_handle.socket.fd;
379 #if defined(IPC_USES_READWRITE)
380 // Test the socket passed into us to make sure it is nonblocking.
381 // We don't want to call read/write on a blocking socket.
382 int value = fcntl(pipe_, F_GETFL);
383 if (value == -1) {
384 PLOG(ERROR) << "fcntl(F_GETFL) " << pipe_name_;
385 return false;
386 }
387 if (!(value & O_NONBLOCK)) {
388 LOG(ERROR) << "Socket " << pipe_name_ << " must be O_NONBLOCK";
389 return false;
390 }
391 #endif // IPC_USES_READWRITE
392 } else if (uses_domain_sockets) {
393 // Case 2 from comment above.
394 must_unlink_ = true;
395 if (mode_ == MODE_SERVER) {
396 if (!CreateServerUnixDomainSocket(pipe_name_, &pipe_)) {
377 return false; 397 return false;
378 } 398 }
379 } else { 399 } else if (mode_ == MODE_CLIENT) {
380 if (!ClientConnectToFifo(pipe_name_, &pipe_)) { 400 if (!CreateClientUnixDomainSocket(pipe_name_, &pipe_)) {
381 return false; 401 return false;
382 } 402 }
383 waiting_connect_ = false;
384 } 403 }
385 } else { 404 } else {
386 // This is the normal (non-unit-test) case, where we're using sockets. 405 pipe_ = PipeMap::GetInstance()->Lookup(pipe_name_);
387 // Three possible cases: 406 if (mode_ == MODE_CLIENT) {
388 // 1) It's for a channel we already have a pipe for; reuse it. 407 if (pipe_ != -1) {
389 // 2) It's the initial IPC channel: 408 // Case 3 from comment above.
390 // 2a) Server side: create the pipe. 409 // We only allow one connection.
391 // 2b) Client side: Pull the pipe out of the GlobalDescriptors set. 410 pipe_ = HANDLE_EINTR(dup(pipe_));
392 if (pipe_ < 0) { 411 PipeMap::GetInstance()->RemoveAndClose(pipe_name_);
393 pipe_ = ChannelNameToFD(pipe_name_);
394 }
395 if (pipe_ < 0) {
396 // Initial IPC channel.
397 if (mode == MODE_SERVER) {
398 if (!SocketPair(&pipe_, &client_pipe_))
399 return false;
400 AddChannelSocket(pipe_name_, client_pipe_);
401 } else { 412 } else {
413 // Case 4a from comment above.
402 // Guard against inappropriate reuse of the initial IPC channel. If 414 // Guard against inappropriate reuse of the initial IPC channel. If
403 // an IPC channel closes and someone attempts to reuse it by name, the 415 // an IPC channel closes and someone attempts to reuse it by name, the
404 // initial channel must not be recycled here. http://crbug.com/26754. 416 // initial channel must not be recycled here. http://crbug.com/26754.
405 static bool used_initial_channel = false; 417 static bool used_initial_channel = false;
406 if (used_initial_channel) { 418 if (used_initial_channel) {
407 LOG(FATAL) << "Denying attempt to reuse initial IPC channel for " 419 LOG(FATAL) << "Denying attempt to reuse initial IPC channel for "
408 << pipe_name_; 420 << pipe_name_;
409 return false; 421 return false;
410 } 422 }
411 used_initial_channel = true; 423 used_initial_channel = true;
412 424
413 pipe_ = base::GlobalDescriptors::GetInstance()->Get(kPrimaryIPCChannel); 425 pipe_ = base::GlobalDescriptors::GetInstance()->Get(kPrimaryIPCChannel);
414 } 426 }
427 } else if (mode_ == MODE_SERVER) {
428 // Case 4b from comment above.
429 if (pipe_ != -1) {
430 LOG(ERROR) << "Server already exists for " << pipe_name_;
431 return false;
432 }
433 if (!SocketPair(&pipe_, &client_pipe_))
434 return false;
435 PipeMap::GetInstance()->Insert(pipe_name_, client_pipe_);
415 } else { 436 } else {
416 waiting_connect_ = mode == MODE_SERVER; 437 LOG(FATAL) << "Unknown mode " << mode_;
438 return false;
417 } 439 }
418 } 440 }
419 441
420 // Create the Hello message to be sent when Connect is called 442 if (mode_ == MODE_SERVER) {
421 scoped_ptr<Message> msg(new Message(MSG_ROUTING_NONE, 443 if (listening_socket) {
422 HELLO_MESSAGE_TYPE, 444 server_listen_pipe_ = pipe_;
423 IPC::Message::PRIORITY_NORMAL)); 445 pipe_ = -1;
424 #if defined(IPC_USES_READWRITE)
425 if (!uses_fifo_) {
426 // Create a dedicated socketpair() for exchanging file descriptors.
427 // See comments for IPC_USES_READWRITE for details.
428 if (mode == MODE_SERVER) {
429 fd_pipe_ = -1;
430 } else if (remote_fd_pipe_ == -1) {
431 if (!SocketPair(&fd_pipe_, &remote_fd_pipe_)) {
432 return false;
433 }
434 } 446 }
435 } 447 }
436 #endif 448
437 if (!msg->WriteInt(base::GetCurrentProcId())) { 449 #if defined(IPC_USES_READWRITE)
438 Close(); 450 // Create a dedicated socketpair() for exchanging file descriptors.
439 return false; 451 // See comments for IPC_USES_READWRITE for details.
452 if (mode_ == MODE_CLIENT) {
453 if (!SocketPair(&fd_pipe_, &remote_fd_pipe_)) {
454 return false;
455 }
440 } 456 }
457 #endif // IPC_USES_READWRITE
441 458
442 output_queue_.push(msg.release());
443 return true; 459 return true;
444 } 460 }
445 461
446 bool Channel::ChannelImpl::Connect() { 462 bool Channel::ChannelImpl::Connect() {
447 if (mode_ == MODE_SERVER && uses_fifo_) { 463 if (server_listen_pipe_ == -1 && pipe_ == -1) {
448 if (server_listen_pipe_ == -1) { 464 NOTREACHED() << "Must call create on a channel before calling connect";
449 return false; 465 return false;
450 } 466 }
467
468 bool did_connect = true;
469 if (server_listen_pipe_ != -1) {
470 // Watch the pipe for connections, and turn any connections into
471 // active sockets.
451 MessageLoopForIO::current()->WatchFileDescriptor( 472 MessageLoopForIO::current()->WatchFileDescriptor(
452 server_listen_pipe_, 473 server_listen_pipe_,
453 true, 474 true,
454 MessageLoopForIO::WATCH_READ, 475 MessageLoopForIO::WATCH_READ,
455 &server_listen_connection_watcher_, 476 &server_listen_connection_watcher_,
456 this); 477 this);
457 } else { 478 } else {
458 if (pipe_ == -1) { 479 did_connect = AcceptConnection();
459 return false;
460 }
461 MessageLoopForIO::current()->WatchFileDescriptor(
462 pipe_,
463 true,
464 MessageLoopForIO::WATCH_READ,
465 &read_watcher_,
466 this);
467 waiting_connect_ = mode_ == MODE_SERVER;
468 } 480 }
469 481 return did_connect;
470 if (!waiting_connect_)
471 return ProcessOutgoingMessages();
472 return true;
473 } 482 }
474 483
475 bool Channel::ChannelImpl::ProcessIncomingMessages() { 484 bool Channel::ChannelImpl::ProcessIncomingMessages() {
476 ssize_t bytes_read = 0; 485 ssize_t bytes_read = 0;
477 486
478 struct msghdr msg = {0}; 487 struct msghdr msg = {0};
479 struct iovec iov = {input_buf_, Channel::kReadBufferSize}; 488 struct iovec iov = {input_buf_, Channel::kReadBufferSize};
480 489
481 msg.msg_iovlen = 1; 490 msg.msg_iovlen = 1;
482 msg.msg_control = input_cmsg_buf_; 491 msg.msg_control = input_cmsg_buf_;
483 492
484 for (;;) { 493 for (;;) {
485 msg.msg_iov = &iov; 494 msg.msg_iov = &iov;
486 495
487 if (bytes_read == 0) { 496 if (bytes_read == 0) {
488 if (pipe_ == -1) 497 if (pipe_ == -1)
489 return false; 498 return false;
490 499
491 // Read from pipe. 500 // Read from pipe.
492 // recvmsg() returns 0 if the connection has closed or EAGAIN if no data 501 // recvmsg() returns 0 if the connection has closed or EAGAIN if no data
493 // is waiting on the pipe. 502 // is waiting on the pipe.
494 #if defined(IPC_USES_READWRITE) 503 #if defined(IPC_USES_READWRITE)
495 if (fd_pipe_ >= 0) { 504 if (fd_pipe_ >= 0) {
496 bytes_read = HANDLE_EINTR(read(pipe_, input_buf_, 505 bytes_read = HANDLE_EINTR(read(pipe_, input_buf_,
497 Channel::kReadBufferSize)); 506 Channel::kReadBufferSize));
498 msg.msg_controllen = 0; 507 msg.msg_controllen = 0;
499 } else 508 } else
500 #endif 509 #endif // IPC_USES_READWRITE
501 { 510 {
502 msg.msg_controllen = sizeof(input_cmsg_buf_); 511 msg.msg_controllen = sizeof(input_cmsg_buf_);
503 bytes_read = HANDLE_EINTR(recvmsg(pipe_, &msg, MSG_DONTWAIT)); 512 bytes_read = HANDLE_EINTR(recvmsg(pipe_, &msg, MSG_DONTWAIT));
504 } 513 }
505 if (bytes_read < 0) { 514 if (bytes_read < 0) {
506 if (errno == EAGAIN) { 515 if (errno == EAGAIN) {
507 return true; 516 return true;
508 #if defined(OS_MACOSX) 517 #if defined(OS_MACOSX)
509 } else if (errno == EPERM) { 518 } else if (errno == EPERM) {
510 // On OSX, reading from a pipe with no listener returns EPERM 519 // On OSX, reading from a pipe with no listener returns EPERM
511 // treat this as a special case to prevent spurious error messages 520 // treat this as a special case to prevent spurious error messages
512 // to the console. 521 // to the console.
513 return false; 522 return false;
514 #endif // defined(OS_MACOSX) 523 #endif // OS_MACOSX
515 } else if (errno == ECONNRESET || errno == EPIPE) { 524 } else if (errno == ECONNRESET || errno == EPIPE) {
516 return false; 525 return false;
517 } else { 526 } else {
518 PLOG(ERROR) << "pipe error (" << pipe_ << ")"; 527 PLOG(ERROR) << "pipe error (" << pipe_ << ")";
519 return false; 528 return false;
520 } 529 }
521 } else if (bytes_read == 0) { 530 } else if (bytes_read == 0) {
522 // The pipe has closed... 531 // The pipe has closed...
523 return false; 532 return false;
524 } 533 }
(...skipping 34 matching lines...) Expand 10 before | Expand all | Expand 10 after
559 DCHECK(payload_len % sizeof(int) == 0); 568 DCHECK(payload_len % sizeof(int) == 0);
560 wire_fds = reinterpret_cast<int*>(CMSG_DATA(cmsg)); 569 wire_fds = reinterpret_cast<int*>(CMSG_DATA(cmsg));
561 num_wire_fds = payload_len / 4; 570 num_wire_fds = payload_len / 4;
562 571
563 if (msg.msg_flags & MSG_CTRUNC) { 572 if (msg.msg_flags & MSG_CTRUNC) {
564 LOG(ERROR) << "SCM_RIGHTS message was truncated" 573 LOG(ERROR) << "SCM_RIGHTS message was truncated"
565 << " cmsg_len:" << cmsg->cmsg_len 574 << " cmsg_len:" << cmsg->cmsg_len
566 << " fd:" << pipe_; 575 << " fd:" << pipe_;
567 for (unsigned i = 0; i < num_wire_fds; ++i) 576 for (unsigned i = 0; i < num_wire_fds; ++i)
568 if (HANDLE_EINTR(close(wire_fds[i])) < 0) 577 if (HANDLE_EINTR(close(wire_fds[i])) < 0)
569 PLOG(ERROR) << "close" << i; 578 PLOG(ERROR) << "close " << i;
570 return false; 579 return false;
571 } 580 }
572 break; 581 break;
573 } 582 }
574 } 583 }
575 } 584 }
576 585
577 // Process messages from input buffer. 586 // Process messages from input buffer.
578 const char *p; 587 const char *p;
579 const char *end; 588 const char *end;
(...skipping 38 matching lines...) Expand 10 before | Expand all | Expand 10 after
618 int len = static_cast<int>(message_tail - p); 627 int len = static_cast<int>(message_tail - p);
619 Message m(p, len); 628 Message m(p, len);
620 const uint16 header_fds = m.header()->num_fds; 629 const uint16 header_fds = m.header()->num_fds;
621 if (header_fds) { 630 if (header_fds) {
622 // the message has file descriptors 631 // the message has file descriptors
623 const char* error = NULL; 632 const char* error = NULL;
624 if (header_fds > num_fds - fds_i) { 633 if (header_fds > num_fds - fds_i) {
625 // the message has been completely received, but we didn't get 634 // the message has been completely received, but we didn't get
626 // enough file descriptors. 635 // enough file descriptors.
627 #if defined(IPC_USES_READWRITE) 636 #if defined(IPC_USES_READWRITE)
628 if (!uses_fifo_) { 637 char dummy;
629 char dummy; 638 struct iovec fd_pipe_iov = { &dummy, 1 };
630 struct iovec fd_pipe_iov = { &dummy, 1 }; 639 msg.msg_iov = &fd_pipe_iov;
631 msg.msg_iov = &fd_pipe_iov; 640 msg.msg_controllen = sizeof(input_cmsg_buf_);
632 msg.msg_controllen = sizeof(input_cmsg_buf_); 641 ssize_t n = HANDLE_EINTR(recvmsg(fd_pipe_, &msg, MSG_DONTWAIT));
633 ssize_t n = HANDLE_EINTR(recvmsg(fd_pipe_, &msg, MSG_DONTWAIT)); 642 if (n == 1 && msg.msg_controllen > 0) {
634 if (n == 1 && msg.msg_controllen > 0) { 643 for (struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg); cmsg;
635 for (struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg); cmsg; 644 cmsg = CMSG_NXTHDR(&msg, cmsg)) {
636 cmsg = CMSG_NXTHDR(&msg, cmsg)) { 645 if (cmsg->cmsg_level == SOL_SOCKET &&
637 if (cmsg->cmsg_level == SOL_SOCKET && 646 cmsg->cmsg_type == SCM_RIGHTS) {
638 cmsg->cmsg_type == SCM_RIGHTS) { 647 const unsigned payload_len = cmsg->cmsg_len - CMSG_LEN(0);
639 const unsigned payload_len = cmsg->cmsg_len - CMSG_LEN(0); 648 DCHECK(payload_len % sizeof(int) == 0);
640 DCHECK(payload_len % sizeof(int) == 0); 649 wire_fds = reinterpret_cast<int*>(CMSG_DATA(cmsg));
641 wire_fds = reinterpret_cast<int*>(CMSG_DATA(cmsg)); 650 num_wire_fds = payload_len / 4;
642 num_wire_fds = payload_len / 4;
643 651
644 if (msg.msg_flags & MSG_CTRUNC) { 652 if (msg.msg_flags & MSG_CTRUNC) {
645 LOG(ERROR) << "SCM_RIGHTS message was truncated" 653 LOG(ERROR) << "SCM_RIGHTS message was truncated"
646 << " cmsg_len:" << cmsg->cmsg_len 654 << " cmsg_len:" << cmsg->cmsg_len
647 << " fd:" << pipe_; 655 << " fd:" << pipe_;
648 for (unsigned i = 0; i < num_wire_fds; ++i) 656 for (unsigned i = 0; i < num_wire_fds; ++i)
649 if (HANDLE_EINTR(close(wire_fds[i])) < 0) 657 if (HANDLE_EINTR(close(wire_fds[i])) < 0)
650 PLOG(ERROR) << "close" << i; 658 PLOG(ERROR) << "close " << i;
651 return false; 659 return false;
652 }
653 break;
654 } 660 }
661 break;
655 } 662 }
656 if (input_overflow_fds_.empty()) { 663 }
657 fds = wire_fds; 664 if (input_overflow_fds_.empty()) {
658 num_fds = num_wire_fds; 665 fds = wire_fds;
659 } else { 666 num_fds = num_wire_fds;
660 if (num_wire_fds > 0) { 667 } else {
661 const size_t prev_size = input_overflow_fds_.size(); 668 if (num_wire_fds > 0) {
662 input_overflow_fds_.resize(prev_size + num_wire_fds); 669 const size_t prev_size = input_overflow_fds_.size();
663 memcpy(&input_overflow_fds_[prev_size], wire_fds, 670 input_overflow_fds_.resize(prev_size + num_wire_fds);
664 num_wire_fds * sizeof(int)); 671 memcpy(&input_overflow_fds_[prev_size], wire_fds,
665 } 672 num_wire_fds * sizeof(int));
666 fds = &input_overflow_fds_[0];
667 num_fds = input_overflow_fds_.size();
668 } 673 }
674 fds = &input_overflow_fds_[0];
675 num_fds = input_overflow_fds_.size();
669 } 676 }
670 } 677 }
671 if (header_fds > num_fds - fds_i) 678 if (header_fds > num_fds - fds_i)
672 #endif 679 #endif // IPC_USES_READWRITE
673 error = "Message needs unreceived descriptors"; 680 error = "Message needs unreceived descriptors";
674 } 681 }
675 682
676 if (header_fds > 683 if (header_fds >
677 FileDescriptorSet::MAX_DESCRIPTORS_PER_MESSAGE) { 684 FileDescriptorSet::MAX_DESCRIPTORS_PER_MESSAGE) {
678 // There are too many descriptors in this message 685 // There are too many descriptors in this message
679 error = "Message requires an excessive number of descriptors"; 686 error = "Message requires an excessive number of descriptors";
680 } 687 }
681 688
682 if (error) { 689 if (error) {
683 LOG(WARNING) << error 690 LOG(WARNING) << error
684 << " channel:" << this 691 << " channel:" << this
685 << " message-type:" << m.type() 692 << " message-type:" << m.type()
686 << " header()->num_fds:" << header_fds 693 << " header()->num_fds:" << header_fds
687 << " num_fds:" << num_fds 694 << " num_fds:" << num_fds
688 << " fds_i:" << fds_i; 695 << " fds_i:" << fds_i;
689 #if defined(CHROMIUM_SELINUX) 696 #if defined(CHROMIUM_SELINUX)
690 LOG(WARNING) << "In the case of SELinux this can be caused when " 697 LOG(WARNING) << "In the case of SELinux this can be caused when "
691 "using a --user-data-dir to which the default " 698 "using a --user-data-dir to which the default "
692 "policy doesn't give the renderer access to. "; 699 "policy doesn't give the renderer access to. ";
693 #endif 700 #endif // CHROMIUM_SELINUX
694 // close the existing file descriptors so that we don't leak them 701 // close the existing file descriptors so that we don't leak them
695 for (unsigned i = fds_i; i < num_fds; ++i) 702 for (unsigned i = fds_i; i < num_fds; ++i)
696 if (HANDLE_EINTR(close(fds[i])) < 0) 703 if (HANDLE_EINTR(close(fds[i])) < 0)
697 PLOG(ERROR) << "close" << i; 704 PLOG(ERROR) << "close " << i;
698 input_overflow_fds_.clear(); 705 input_overflow_fds_.clear();
699 // abort the connection 706 // abort the connection
700 return false; 707 return false;
701 } 708 }
702 709
703 m.file_descriptor_set()->SetDescriptors( 710 m.file_descriptor_set()->SetDescriptors(
704 &fds[fds_i], header_fds); 711 &fds[fds_i], header_fds);
705 fds_i += header_fds; 712 fds_i += header_fds;
706 } 713 }
707 DVLOG(2) << "received message on channel @" << this 714 DVLOG(2) << "received message on channel @" << this
708 << " with type " << m.type() << " on fd " << pipe_; 715 << " with type " << m.type() << " on fd " << pipe_;
709 if (m.routing_id() == MSG_ROUTING_NONE && 716 if (IsHelloMessage(&m)) {
710 m.type() == HELLO_MESSAGE_TYPE) {
711 // The Hello message contains only the process id. 717 // The Hello message contains only the process id.
712 void *iter = NULL; 718 void *iter = NULL;
713 int pid; 719 int pid;
714 if (!m.ReadInt(&iter, &pid)) { 720 if (!m.ReadInt(&iter, &pid)) {
715 NOTREACHED(); 721 NOTREACHED();
716 } 722 }
717 #if defined(IPC_USES_READWRITE) 723 #if defined(IPC_USES_READWRITE)
718 if (mode_ == MODE_SERVER && !uses_fifo_) { 724 if (mode_ == MODE_SERVER) {
719 // On non-Mac, the Hello message from the client to the server 725 // With IPC_USES_READWRITE, the Hello message from the client to the
720 // also contains the fd_pipe_, which will be used for all 726 // server also contains the fd_pipe_, which will be used for all
721 // subsequent file descriptor passing. 727 // subsequent file descriptor passing.
722 DCHECK_EQ(m.file_descriptor_set()->size(), 1U); 728 DCHECK_EQ(m.file_descriptor_set()->size(), 1U);
723 base::FileDescriptor descriptor; 729 base::FileDescriptor descriptor;
724 if (!m.ReadFileDescriptor(&iter, &descriptor)) { 730 if (!m.ReadFileDescriptor(&iter, &descriptor)) {
725 NOTREACHED(); 731 NOTREACHED();
726 } 732 }
727 fd_pipe_ = descriptor.fd; 733 fd_pipe_ = descriptor.fd;
728 CHECK(descriptor.auto_close); 734 CHECK(descriptor.auto_close);
729 } 735 }
730 #endif 736 #endif // IPC_USES_READWRITE
731 listener_->OnChannelConnected(pid); 737 listener_->OnChannelConnected(pid);
732 } else { 738 } else {
733 listener_->OnMessageReceived(m); 739 listener_->OnMessageReceived(m);
734 } 740 }
735 p = message_tail; 741 p = message_tail;
736 } else { 742 } else {
737 // Last message is partial. 743 // Last message is partial.
738 break; 744 break;
739 } 745 }
740 input_overflow_fds_ = std::vector<int>(&fds[fds_i], &fds[num_fds]); 746 input_overflow_fds_ = std::vector<int>(&fds[fds_i], &fds[num_fds]);
741 fds_i = 0; 747 fds_i = 0;
742 fds = &input_overflow_fds_[0]; 748 fds = &input_overflow_fds_[0];
743 num_fds = input_overflow_fds_.size(); 749 num_fds = input_overflow_fds_.size();
744 } 750 }
745 input_overflow_buf_.assign(p, end - p); 751 input_overflow_buf_.assign(p, end - p);
746 input_overflow_fds_ = std::vector<int>(&fds[fds_i], &fds[num_fds]); 752 input_overflow_fds_ = std::vector<int>(&fds[fds_i], &fds[num_fds]);
747 753
748 // When the input data buffer is empty, the overflow fds should be too. If 754 // When the input data buffer is empty, the overflow fds should be too. If
749 // this is not the case, we probably have a rogue renderer which is trying 755 // this is not the case, we probably have a rogue renderer which is trying
750 // to fill our descriptor table. 756 // to fill our descriptor table.
751 if (input_overflow_buf_.empty() && !input_overflow_fds_.empty()) { 757 if (input_overflow_buf_.empty() && !input_overflow_fds_.empty()) {
752 // We close these descriptors in Close() 758 // We close these descriptors in Close()
753 return false; 759 return false;
754 } 760 }
755 761
756 bytes_read = 0; // Get more data. 762 bytes_read = 0; // Get more data.
757 } 763 }
758
759 return true;
760 } 764 }
761 765
762 bool Channel::ChannelImpl::ProcessOutgoingMessages() { 766 bool Channel::ChannelImpl::ProcessOutgoingMessages() {
763 DCHECK(!waiting_connect_); // Why are we trying to send messages if there's 767 DCHECK(!waiting_connect_); // Why are we trying to send messages if there's
764 // no connection? 768 // no connection?
765 is_blocked_on_write_ = false; 769 if (output_queue_.empty())
770 return true;
766 771
767 if (output_queue_.empty()) { 772 if (pipe_ == -1)
768 return true;
769 }
770
771 if (pipe_ == -1) {
772 return false; 773 return false;
773 }
774 774
775 // Write out all the messages we can till the write blocks or there are no 775 // Write out all the messages we can till the write blocks or there are no
776 // more outgoing messages. 776 // more outgoing messages.
777 while (!output_queue_.empty()) { 777 while (!output_queue_.empty()) {
778 Message* msg = output_queue_.front(); 778 Message* msg = output_queue_.front();
779 779
780 #if defined(IPC_USES_READWRITE)
781 scoped_ptr<Message> hello;
782 if (remote_fd_pipe_ != -1 &&
783 msg->routing_id() == MSG_ROUTING_NONE &&
784 msg->type() == HELLO_MESSAGE_TYPE) {
785 hello.reset(new Message(MSG_ROUTING_NONE,
786 HELLO_MESSAGE_TYPE,
787 IPC::Message::PRIORITY_NORMAL));
788 void* iter = NULL;
789 int pid;
790 if (!msg->ReadInt(&iter, &pid) ||
791 !hello->WriteInt(pid)) {
792 NOTREACHED();
793 }
794 DCHECK_EQ(hello->size(), msg->size());
795 if (!hello->WriteFileDescriptor(base::FileDescriptor(remote_fd_pipe_,
796 false))) {
797 NOTREACHED();
798 }
799 msg = hello.get();
800 DCHECK_EQ(msg->file_descriptor_set()->size(), 1U);
801 }
802 #endif
803
804 size_t amt_to_write = msg->size() - message_send_bytes_written_; 780 size_t amt_to_write = msg->size() - message_send_bytes_written_;
805 DCHECK(amt_to_write != 0); 781 DCHECK(amt_to_write != 0);
806 const char* out_bytes = reinterpret_cast<const char*>(msg->data()) + 782 const char* out_bytes = reinterpret_cast<const char*>(msg->data()) +
807 message_send_bytes_written_; 783 message_send_bytes_written_;
808 784
809 struct msghdr msgh = {0}; 785 struct msghdr msgh = {0};
810 struct iovec iov = {const_cast<char*>(out_bytes), amt_to_write}; 786 struct iovec iov = {const_cast<char*>(out_bytes), amt_to_write};
811 msgh.msg_iov = &iov; 787 msgh.msg_iov = &iov;
812 msgh.msg_iovlen = 1; 788 msgh.msg_iovlen = 1;
813 char buf[CMSG_SPACE( 789 char buf[CMSG_SPACE(
(...skipping 27 matching lines...) Expand all
841 cmsg->cmsg_len = CMSG_LEN(sizeof(int) * num_fds); 817 cmsg->cmsg_len = CMSG_LEN(sizeof(int) * num_fds);
842 msg->file_descriptor_set()->GetDescriptors( 818 msg->file_descriptor_set()->GetDescriptors(
843 reinterpret_cast<int*>(CMSG_DATA(cmsg))); 819 reinterpret_cast<int*>(CMSG_DATA(cmsg)));
844 msgh.msg_controllen = cmsg->cmsg_len; 820 msgh.msg_controllen = cmsg->cmsg_len;
845 821
846 // DCHECK_LE above already checks that 822 // DCHECK_LE above already checks that
847 // num_fds < MAX_DESCRIPTORS_PER_MESSAGE so no danger of overflow. 823 // num_fds < MAX_DESCRIPTORS_PER_MESSAGE so no danger of overflow.
848 msg->header()->num_fds = static_cast<uint16>(num_fds); 824 msg->header()->num_fds = static_cast<uint16>(num_fds);
849 825
850 #if defined(IPC_USES_READWRITE) 826 #if defined(IPC_USES_READWRITE)
851 if (!uses_fifo_ && 827 if (!IsHelloMessage(msg)) {
852 (msg->routing_id() != MSG_ROUTING_NONE ||
853 msg->type() != HELLO_MESSAGE_TYPE)) {
854 // Only the Hello message sends the file descriptor with the message. 828 // Only the Hello message sends the file descriptor with the message.
855 // Subsequently, we can send file descriptors on the dedicated 829 // Subsequently, we can send file descriptors on the dedicated
856 // fd_pipe_ which makes Seccomp sandbox operation more efficient. 830 // fd_pipe_ which makes Seccomp sandbox operation more efficient.
857 struct iovec fd_pipe_iov = { const_cast<char *>(""), 1 }; 831 struct iovec fd_pipe_iov = { const_cast<char *>(""), 1 };
858 msgh.msg_iov = &fd_pipe_iov; 832 msgh.msg_iov = &fd_pipe_iov;
859 fd_written = fd_pipe_; 833 fd_written = fd_pipe_;
860 bytes_written = HANDLE_EINTR(sendmsg(fd_pipe_, &msgh, MSG_DONTWAIT)); 834 bytes_written = HANDLE_EINTR(sendmsg(fd_pipe_, &msgh, MSG_DONTWAIT));
861 msgh.msg_iov = &iov; 835 msgh.msg_iov = &iov;
862 msgh.msg_controllen = 0; 836 msgh.msg_controllen = 0;
863 if (bytes_written > 0) { 837 if (bytes_written > 0) {
864 msg->file_descriptor_set()->CommitAll(); 838 msg->file_descriptor_set()->CommitAll();
865 } 839 }
866 } 840 }
867 #endif 841 #endif // IPC_USES_READWRITE
868 } 842 }
869 843
870 if (bytes_written == 1) { 844 if (bytes_written == 1) {
871 fd_written = pipe_; 845 fd_written = pipe_;
872 #if defined(IPC_USES_READWRITE) 846 #if defined(IPC_USES_READWRITE)
873 if (mode_ != MODE_SERVER && !uses_fifo_ && 847 if (mode_ != MODE_SERVER && IsHelloMessage(msg)) {
874 msg->routing_id() == MSG_ROUTING_NONE &&
875 msg->type() == HELLO_MESSAGE_TYPE) {
876 DCHECK_EQ(msg->file_descriptor_set()->size(), 1U); 848 DCHECK_EQ(msg->file_descriptor_set()->size(), 1U);
877 } 849 }
878 if (!uses_fifo_ && !msgh.msg_controllen) { 850 if (!msgh.msg_controllen) {
879 bytes_written = HANDLE_EINTR(write(pipe_, out_bytes, amt_to_write)); 851 bytes_written = HANDLE_EINTR(write(pipe_, out_bytes, amt_to_write));
880 } else 852 } else
881 #endif 853 #endif // IPC_USES_READWRITE
882 { 854 {
883 bytes_written = HANDLE_EINTR(sendmsg(pipe_, &msgh, MSG_DONTWAIT)); 855 bytes_written = HANDLE_EINTR(sendmsg(pipe_, &msgh, MSG_DONTWAIT));
884 } 856 }
885 } 857 }
886 if (bytes_written > 0) 858 if (bytes_written > 0)
887 msg->file_descriptor_set()->CommitAll(); 859 msg->file_descriptor_set()->CommitAll();
888 860
889 if (bytes_written < 0 && !SocketWriteErrorIsRecoverable()) { 861 if (bytes_written < 0 && !SocketWriteErrorIsRecoverable()) {
890 #if defined(OS_MACOSX) 862 #if defined(OS_MACOSX)
891 // On OSX writing to a pipe with no listener returns EPERM. 863 // On OSX writing to a pipe with no listener returns EPERM.
(...skipping 41 matching lines...) Expand 10 before | Expand all | Expand 10 after
933 return true; 905 return true;
934 } 906 }
935 907
936 bool Channel::ChannelImpl::Send(Message* message) { 908 bool Channel::ChannelImpl::Send(Message* message) {
937 DVLOG(2) << "sending message @" << message << " on channel @" << this 909 DVLOG(2) << "sending message @" << message << " on channel @" << this
938 << " with type " << message->type() 910 << " with type " << message->type()
939 << " (" << output_queue_.size() << " in queue)"; 911 << " (" << output_queue_.size() << " in queue)";
940 912
941 #ifdef IPC_MESSAGE_LOG_ENABLED 913 #ifdef IPC_MESSAGE_LOG_ENABLED
942 Logging::GetInstance()->OnSendMessage(message, ""); 914 Logging::GetInstance()->OnSendMessage(message, "");
943 #endif 915 #endif // IPC_MESSAGE_LOG_ENABLED
944 916
945 output_queue_.push(message); 917 output_queue_.push(message);
946 if (!waiting_connect_) { 918 if (!is_blocked_on_write_ && !waiting_connect_) {
947 if (!is_blocked_on_write_) { 919 return ProcessOutgoingMessages();
948 if (!ProcessOutgoingMessages())
949 return false;
950 }
951 } 920 }
952 921
953 return true; 922 return true;
954 } 923 }
955 924
956 int Channel::ChannelImpl::GetClientFileDescriptor() const { 925 int Channel::ChannelImpl::GetClientFileDescriptor() const {
957 return client_pipe_; 926 return client_pipe_;
958 } 927 }
959 928
960 // Called by libevent when we can read from th pipe without blocking. 929 bool Channel::ChannelImpl::AcceptsConnections() const {
930 return server_listen_pipe_ != -1;
931 }
932
933 bool Channel::ChannelImpl::HasAcceptedConnection() const {
934 return AcceptsConnections() && pipe_ != -1;
935 }
936
937 void Channel::ChannelImpl::ResetToAcceptingConnectionState() {
938 // Unregister libevent for the unix domain socket and close it.
939 read_watcher_.StopWatchingFileDescriptor();
940 write_watcher_.StopWatchingFileDescriptor();
941 if (pipe_ != -1) {
942 if (HANDLE_EINTR(close(pipe_)) < 0)
943 PLOG(ERROR) << "close pipe_ " << pipe_name_;
944 pipe_ = -1;
945 }
946 #if defined(IPC_USES_READWRITE)
947 if (fd_pipe_ != -1) {
948 if (HANDLE_EINTR(close(fd_pipe_)) < 0)
949 PLOG(ERROR) << "close fd_pipe_ " << pipe_name_;
950 fd_pipe_ = -1;
951 }
952 if (remote_fd_pipe_ != -1) {
953 if (HANDLE_EINTR(close(remote_fd_pipe_)) < 0)
954 PLOG(ERROR) << "close remote_fd_pipe_ " << pipe_name_;
955 remote_fd_pipe_ = -1;
956 }
957 #endif // IPC_USES_READWRITE
958
959 while (!output_queue_.empty()) {
960 Message* m = output_queue_.front();
961 output_queue_.pop();
962 delete m;
963 }
964
965 // Close any outstanding, received file descriptors.
966 for (std::vector<int>::iterator
967 i = input_overflow_fds_.begin(); i != input_overflow_fds_.end(); ++i) {
968 if (HANDLE_EINTR(close(*i)) < 0)
969 PLOG(ERROR) << "close";
970 }
971 input_overflow_fds_.clear();
972 }
973
974 // Called by libevent when we can read from the pipe without blocking.
961 void Channel::ChannelImpl::OnFileCanReadWithoutBlocking(int fd) { 975 void Channel::ChannelImpl::OnFileCanReadWithoutBlocking(int fd) {
962 bool send_server_hello_msg = false; 976 bool send_server_hello_msg = false;
963 if (waiting_connect_ && mode_ == MODE_SERVER) { 977 if (fd == server_listen_pipe_) {
964 if (uses_fifo_) { 978 int new_pipe = 0;
965 if (!ServerAcceptFifoConnection(server_listen_pipe_, &pipe_)) { 979 if (!ServerAcceptConnection(server_listen_pipe_, &new_pipe)) {
966 Close(); 980 Close();
967 } 981 listener_->OnChannelListenError();
982 }
968 983
969 // No need to watch the listening socket any longer since only one client 984 if (pipe_ != -1) {
970 // can connect. So unregister with libevent. 985 // We already have a connection. We only handle one at a time.
971 server_listen_connection_watcher_.StopWatchingFileDescriptor(); 986 // close our new descriptor.
987 if (HANDLE_EINTR(shutdown(new_pipe, SHUT_RDWR)) < 0)
988 PLOG(ERROR) << "shutdown " << pipe_name_;
989 if (HANDLE_EINTR(close(new_pipe)) < 0)
990 PLOG(ERROR) << "close " << pipe_name_;
991 listener_->OnChannelDenied();
992 return;
993 }
994 pipe_ = new_pipe;
972 995
973 // Start watching our end of the socket. 996 if (!AcceptConnection()) {
974 MessageLoopForIO::current()->WatchFileDescriptor( 997 NOTREACHED() << "AcceptConnection should not fail on server";
975 pipe_, 998 }
976 true, 999 send_server_hello_msg = true;
977 MessageLoopForIO::WATCH_READ, 1000 waiting_connect_ = false;
978 &read_watcher_, 1001 } else if (fd == pipe_) {
979 this); 1002 if (waiting_connect_ && mode_ == MODE_SERVER) {
980 1003 send_server_hello_msg = true;
981 waiting_connect_ = false;
982 } else {
983 // In the case of a socketpair() the server starts listening on its end
984 // of the pipe in Connect().
985 waiting_connect_ = false; 1004 waiting_connect_ = false;
986 } 1005 }
987 send_server_hello_msg = true;
988 }
989
990 if (!waiting_connect_ && fd == pipe_) {
991 if (!ProcessIncomingMessages()) { 1006 if (!ProcessIncomingMessages()) {
992 Close(); 1007 ClosePipeOnError();
993 listener_->OnChannelError();
994 // The OnChannelError() call may delete this, so we need to exit now.
995 return;
996 } 1008 }
1009 } else {
1010 NOTREACHED() << "Unknown pipe " << fd;
997 } 1011 }
998 1012
999 // If we're a server and handshaking, then we want to make sure that we 1013 // If we're a server and handshaking, then we want to make sure that we
1000 // only send our handshake message after we've processed the client's. 1014 // only send our handshake message after we've processed the client's.
1001 // This gives us a chance to kill the client if the incoming handshake 1015 // This gives us a chance to kill the client if the incoming handshake
1002 // is invalid. 1016 // is invalid.
1003 if (send_server_hello_msg) { 1017 if (send_server_hello_msg) {
1004 ProcessOutgoingMessages(); 1018 ProcessOutgoingMessages();
1005 } 1019 }
1006 } 1020 }
1007 1021
1008 // Called by libevent when we can write to the pipe without blocking. 1022 // Called by libevent when we can write to the pipe without blocking.
1009 void Channel::ChannelImpl::OnFileCanWriteWithoutBlocking(int fd) { 1023 void Channel::ChannelImpl::OnFileCanWriteWithoutBlocking(int fd) {
1024 DCHECK(fd == pipe_);
1025 is_blocked_on_write_ = false;
1010 if (!ProcessOutgoingMessages()) { 1026 if (!ProcessOutgoingMessages()) {
1027 ClosePipeOnError();
1028 }
1029 }
1030
1031 bool Channel::ChannelImpl::AcceptConnection() {
1032 MessageLoopForIO::current()->WatchFileDescriptor(pipe_,
1033 true,
1034 MessageLoopForIO::WATCH_READ,
1035 &read_watcher_,
1036 this);
1037 QueueHelloMessage();
1038
1039 if (mode_ == MODE_CLIENT) {
1040 // If we are a client we want to send a hello message out immediately.
1041 // In server mode we will send a hello message when we receive one from a
1042 // client.
1043 waiting_connect_ = false;
1044 return ProcessOutgoingMessages();
1045 } else {
1046 waiting_connect_ = true;
1047 return true;
1048 }
1049 }
1050
1051 void Channel::ChannelImpl::ClosePipeOnError() {
1052 if (HasAcceptedConnection()) {
1053 ResetToAcceptingConnectionState();
1054 listener_->OnChannelError();
1055 } else {
1011 Close(); 1056 Close();
1012 listener_->OnChannelError(); 1057 if (AcceptsConnections()) {
1058 listener_->OnChannelListenError();
1059 } else {
1060 listener_->OnChannelError();
1061 }
1013 } 1062 }
1014 } 1063 }
1015 1064
1065 void Channel::ChannelImpl::QueueHelloMessage() {
1066 // Create the Hello message
1067 scoped_ptr<Message> msg(new Message(MSG_ROUTING_NONE,
1068 HELLO_MESSAGE_TYPE,
1069 IPC::Message::PRIORITY_NORMAL));
1070
1071 if (!msg->WriteInt(base::GetCurrentProcId())) {
1072 NOTREACHED() << "Unable to pickle hello message proc id";
1073 }
1074 #if defined(IPC_USES_READWRITE)
1075 scoped_ptr<Message> hello;
1076 if (remote_fd_pipe_ != -1) {
1077 if (!msg->WriteFileDescriptor(base::FileDescriptor(remote_fd_pipe_,
1078 false))) {
1079 NOTREACHED() << "Unable to pickle hello message file descriptors";
1080 }
1081 DCHECK_EQ(msg->file_descriptor_set()->size(), 1U);
1082 }
1083 #endif // IPC_USES_READWRITE
1084 output_queue_.push(msg.release());
1085 }
1086
1087 bool Channel::ChannelImpl::IsHelloMessage(const Message* m) const {
1088 return m->routing_id() == MSG_ROUTING_NONE && m->type() == HELLO_MESSAGE_TYPE;
1089 }
1090
1016 void Channel::ChannelImpl::Close() { 1091 void Channel::ChannelImpl::Close() {
1017 // Close can be called multiple time, so we need to make sure we're 1092 // Close can be called multiple time, so we need to make sure we're
1018 // idempotent. 1093 // idempotent.
1019 1094
1020 // Unregister libevent for the listening socket and close it. 1095 ResetToAcceptingConnectionState();
1021 server_listen_connection_watcher_.StopWatchingFileDescriptor();
1022 1096
1097 if (must_unlink_) {
1098 unlink(pipe_name_.c_str());
1099 must_unlink_ = false;
1100 }
1023 if (server_listen_pipe_ != -1) { 1101 if (server_listen_pipe_ != -1) {
1024 if (HANDLE_EINTR(close(server_listen_pipe_)) < 0) 1102 if (HANDLE_EINTR(close(server_listen_pipe_)) < 0)
1025 PLOG(ERROR) << "close " << server_listen_pipe_; 1103 PLOG(ERROR) << "close " << server_listen_pipe_;
1026 server_listen_pipe_ = -1; 1104 server_listen_pipe_ = -1;
1105 // Unregister libevent for the listening socket and close it.
1106 server_listen_connection_watcher_.StopWatchingFileDescriptor();
1027 } 1107 }
1028 1108
1029 // Unregister libevent for the FIFO and close it.
1030 read_watcher_.StopWatchingFileDescriptor();
1031 write_watcher_.StopWatchingFileDescriptor();
1032 if (pipe_ != -1) {
1033 if (HANDLE_EINTR(close(pipe_)) < 0)
1034 PLOG(ERROR) << "close " << pipe_;
1035 pipe_ = -1;
1036 }
1037 if (client_pipe_ != -1) { 1109 if (client_pipe_ != -1) {
1038 PipeMap::GetInstance()->RemoveAndClose(pipe_name_); 1110 PipeMap::GetInstance()->RemoveAndClose(pipe_name_);
1039 client_pipe_ = -1; 1111 client_pipe_ = -1;
1040 } 1112 }
1041 #if defined(IPC_USES_READWRITE)
1042 if (fd_pipe_ != -1) {
1043 if (HANDLE_EINTR(close(fd_pipe_)) < 0)
1044 PLOG(ERROR) << "close " << fd_pipe_;
1045 fd_pipe_ = -1;
1046 }
1047 if (remote_fd_pipe_ != -1) {
1048 if (HANDLE_EINTR(close(remote_fd_pipe_)) < 0)
1049 PLOG(ERROR) << "close " << remote_fd_pipe_;
1050 remote_fd_pipe_ = -1;
1051 }
1052 #endif
1053
1054 if (uses_fifo_) {
1055 // Unlink the FIFO
1056 unlink(pipe_name_.c_str());
1057 }
1058
1059 while (!output_queue_.empty()) {
1060 Message* m = output_queue_.front();
1061 output_queue_.pop();
1062 delete m;
1063 }
1064
1065 // Close any outstanding, received file descriptors
1066 for (std::vector<int>::iterator
1067 i = input_overflow_fds_.begin(); i != input_overflow_fds_.end(); ++i) {
1068 if (HANDLE_EINTR(close(*i)) < 0)
1069 PLOG(ERROR) << "close " << *i;
1070 }
1071 input_overflow_fds_.clear();
1072 } 1113 }
1073 1114
1074 //------------------------------------------------------------------------------ 1115 //------------------------------------------------------------------------------
1075 // Channel's methods simply call through to ChannelImpl. 1116 // Channel's methods simply call through to ChannelImpl.
1076 Channel::Channel(const IPC::ChannelHandle& channel_handle, Mode mode, 1117 Channel::Channel(const IPC::ChannelHandle& channel_handle, Mode mode,
1077 Listener* listener) 1118 Listener* listener)
1078 : channel_impl_(new ChannelImpl(channel_handle, mode, listener)) { 1119 : channel_impl_(new ChannelImpl(channel_handle, mode, listener)) {
1079 } 1120 }
1080 1121
1081 Channel::~Channel() { 1122 Channel::~Channel() {
(...skipping 13 matching lines...) Expand all
1095 } 1136 }
1096 1137
1097 bool Channel::Send(Message* message) { 1138 bool Channel::Send(Message* message) {
1098 return channel_impl_->Send(message); 1139 return channel_impl_->Send(message);
1099 } 1140 }
1100 1141
1101 int Channel::GetClientFileDescriptor() const { 1142 int Channel::GetClientFileDescriptor() const {
1102 return channel_impl_->GetClientFileDescriptor(); 1143 return channel_impl_->GetClientFileDescriptor();
1103 } 1144 }
1104 1145
1146 bool Channel::AcceptsConnections() const {
1147 return channel_impl_->AcceptsConnections();
1148 }
1149
1150 bool Channel::HasAcceptedConnection() const {
1151 return channel_impl_->HasAcceptedConnection();
1152 }
1153
1154 void Channel::ResetToAcceptingConnectionState() {
1155 channel_impl_->ResetToAcceptingConnectionState();
1156 }
1157
1105 } // namespace IPC 1158 } // namespace IPC
OLDNEW
« no previous file with comments | « ipc/ipc_channel_posix.h ('k') | ipc/ipc_channel_posix_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698