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

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: Cleaned up some style nits 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
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>
(...skipping 12 matching lines...) Expand all
23 #include "base/process_util.h" 23 #include "base/process_util.h"
24 #include "base/scoped_ptr.h" 24 #include "base/scoped_ptr.h"
25 #include "base/singleton.h" 25 #include "base/singleton.h"
26 #include "base/string_util.h" 26 #include "base/string_util.h"
27 #include "ipc/ipc_descriptors.h" 27 #include "ipc/ipc_descriptors.h"
28 #include "ipc/ipc_switches.h" 28 #include "ipc/ipc_switches.h"
29 #include "ipc/file_descriptor_set_posix.h" 29 #include "ipc/file_descriptor_set_posix.h"
30 #include "ipc/ipc_logging.h" 30 #include "ipc/ipc_logging.h"
31 #include "ipc/ipc_message_utils.h" 31 #include "ipc/ipc_message_utils.h"
32 32
33 #if defined (OS_MACOSX)
34 #include <poll.h>
35 #endif // defined (OS_MACOSX)
jeremy 2010/12/12 14:59:29 // OS_MACOSX
dmac 2010/12/13 18:32:29 Done.
36
33 namespace IPC { 37 namespace IPC {
34 38
35 // IPC channels on Windows use named pipes (CreateNamedPipe()) with 39 // IPC channels on Windows use named pipes (CreateNamedPipe()) with
36 // channel ids as the pipe names. Channels on POSIX use anonymous 40 // channel ids as the pipe names. Channels on POSIX use sockets as
37 // Unix domain sockets created via socketpair() as pipes. These don't 41 // pipes These don't quite line up.
38 // quite line up.
39 // 42 //
40 // When creating a child subprocess, the parent side of the fork 43 // 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 44 // the fork arranges it such that the initial control channel ends up on the
42 // magic file descriptor kPrimaryIPCChannel in the child. Future 45 // magic file descriptor kPrimaryIPCChannel in the child. Future
43 // connections (file descriptors) can then be passed via that 46 // connections (file descriptors) can then be passed via that
44 // connection via sendmsg(). 47 // connection via sendmsg().
48 //
49 // A POSIX IPC channel can also be set up as a server for a bound UNIX domain
50 // socket, and will handle multiple connect and disconnect sequences. Currently
51 // it is limited to one connection at a time.
45 52
46 //------------------------------------------------------------------------------ 53 //------------------------------------------------------------------------------
47 namespace { 54 namespace {
48 55
49 // The PipeMap class works around this quirk related to unit tests: 56 // The PipeMap class works around this quirk related to unit tests:
50 // 57 //
51 // When running as a server, we install the client socket in a 58 // When running as a server, we install the client socket in a
52 // specific file descriptor number (@kPrimaryIPCChannel). However, we 59 // specific file descriptor number (@kPrimaryIPCChannel). However, we
53 // also have to support the case where we are running unittests in the 60 // also have to support the case where we are running unittests in the
54 // same process. (We do not support forking without execing.) 61 // same process. (We do not support forking without execing.)
(...skipping 66 matching lines...) Expand 10 before | Expand all | Expand 10 after
121 } 128 }
122 129
123 private: 130 private:
124 Lock lock_; 131 Lock lock_;
125 typedef std::map<std::string, int> ChannelToFDMap; 132 typedef std::map<std::string, int> ChannelToFDMap;
126 ChannelToFDMap map_; 133 ChannelToFDMap map_;
127 134
128 friend struct DefaultSingletonTraits<PipeMap>; 135 friend struct DefaultSingletonTraits<PipeMap>;
129 }; 136 };
130 137
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 //------------------------------------------------------------------------------ 138 //------------------------------------------------------------------------------
148 // The standard size on linux is 108, mac is 104. To maintain consistency 139 // The standard size on linux is 108, mac is 104. To maintain consistency
149 // across platforms we standardize on the smaller value. 140 // across platforms we standardize on the smaller value.
150 const size_t kMaxPipeNameLength = 104; 141 const size_t kMaxPipeNameLength = 104;
151 COMPILE_ASSERT(sizeof(((sockaddr_un*)0)->sun_path) >= kMaxPipeNameLength, 142 COMPILE_ASSERT(sizeof(((sockaddr_un*)0)->sun_path) >= kMaxPipeNameLength,
152 BAD_SUN_PATH_LENGTH); 143 BAD_SUN_PATH_LENGTH);
153 144
154 // Creates a Fifo with the specified name ready to listen on. 145 // 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) { 146 // for connections.
147 bool CreateServerUnixDomainSocket(const std::string& pipe_name,
148 int* server_listen_fd) {
156 DCHECK(server_listen_fd); 149 DCHECK(server_listen_fd);
157 DCHECK_GT(pipe_name.length(), 0u); 150 DCHECK_GT(pipe_name.length(), 0u);
158 DCHECK_LT(pipe_name.length(), kMaxPipeNameLength); 151 DCHECK_LT(pipe_name.length(), kMaxPipeNameLength);
159 152
160 if (pipe_name.length() == 0 || pipe_name.length() >= kMaxPipeNameLength) { 153 if (pipe_name.length() == 0 || pipe_name.length() >= kMaxPipeNameLength) {
161 return false; 154 return false;
162 } 155 }
163 156
164 // Create socket. 157 // Create socket.
165 int fd = socket(AF_UNIX, SOCK_STREAM, 0); 158 int fd = socket(AF_UNIX, SOCK_STREAM, 0);
166 if (fd < 0) { 159 if (fd < 0) {
167 return false; 160 return false;
168 } 161 }
169 162
170 // Make socket non-blocking 163 // Make socket non-blocking
171 if (fcntl(fd, F_SETFL, O_NONBLOCK) == -1) { 164 if (fcntl(fd, F_SETFL, O_NONBLOCK) == -1) {
172 PLOG(ERROR) << "fcntl " << pipe_name; 165 PLOG(ERROR) << "fcntl(O_NONBLOCK) " << pipe_name;
173 if (HANDLE_EINTR(close(fd)) < 0) 166 if (HANDLE_EINTR(close(fd)) < 0)
174 PLOG(ERROR) << "close " << pipe_name; 167 PLOG(ERROR) << "close " << pipe_name;
175 return false; 168 return false;
176 } 169 }
177 170
178 // Delete any old FS instances. 171 // Delete any old FS instances.
179 unlink(pipe_name.c_str()); 172 unlink(pipe_name.c_str());
180 173
181 // Create unix_addr structure 174 // Create unix_addr structure
182 struct sockaddr_un unix_addr; 175 struct sockaddr_un unix_addr;
(...skipping 18 matching lines...) Expand all
201 PLOG(ERROR) << "listen " << pipe_name; 194 PLOG(ERROR) << "listen " << pipe_name;
202 if (HANDLE_EINTR(close(fd)) < 0) 195 if (HANDLE_EINTR(close(fd)) < 0)
203 PLOG(ERROR) << "close " << pipe_name; 196 PLOG(ERROR) << "close " << pipe_name;
204 return false; 197 return false;
205 } 198 }
206 199
207 *server_listen_fd = fd; 200 *server_listen_fd = fd;
208 return true; 201 return true;
209 } 202 }
210 203
211 // Accept a connection on a fifo. 204 // Accept a connection on a socket we are listening to.
212 bool ServerAcceptFifoConnection(int server_listen_fd, int* server_socket) { 205 bool ServerAcceptConnection(int server_listen_fd, int* server_socket) {
213 DCHECK(server_socket); 206 DCHECK(server_socket);
214 207
215 int accept_fd = HANDLE_EINTR(accept(server_listen_fd, NULL, 0)); 208 int accept_fd = HANDLE_EINTR(accept(server_listen_fd, NULL, 0));
216 if (accept_fd < 0) 209 if (accept_fd < 0)
217 return false; 210 return false;
218 if (fcntl(accept_fd, F_SETFL, O_NONBLOCK) == -1) { 211 if (fcntl(accept_fd, F_SETFL, O_NONBLOCK) == -1) {
219 PLOG(ERROR) << "fcntl " << accept_fd; 212 PLOG(ERROR) << "fcntl(O_NONBLOCK) " << accept_fd;
220 if (HANDLE_EINTR(close(accept_fd)) < 0) 213 if (HANDLE_EINTR(close(accept_fd)) < 0)
221 PLOG(ERROR) << "close " << accept_fd; 214 PLOG(ERROR) << "close " << accept_fd;
222 return false; 215 return false;
223 } 216 }
224 217
225 *server_socket = accept_fd; 218 *server_socket = accept_fd;
226 return true; 219 return true;
227 } 220 }
228 221
229 bool ClientConnectToFifo(const std::string &pipe_name, int* client_socket) { 222 bool CreateClientUnixDomainSocket(const std::string& pipe_name,
223 int* client_socket) {
230 DCHECK(client_socket); 224 DCHECK(client_socket);
231 DCHECK_GT(pipe_name.length(), 0u); 225 DCHECK_GT(pipe_name.length(), 0u);
232 DCHECK_LT(pipe_name.length(), kMaxPipeNameLength); 226 DCHECK_LT(pipe_name.length(), kMaxPipeNameLength);
233 227
234 if (pipe_name.length() == 0 || pipe_name.length() >= kMaxPipeNameLength) { 228 if (pipe_name.length() == 0 || pipe_name.length() >= kMaxPipeNameLength) {
235 return false; 229 return false;
236 } 230 }
237 231
238 // Create socket. 232 // Create socket.
239 int fd = socket(AF_UNIX, SOCK_STREAM, 0); 233 int fd = socket(AF_UNIX, SOCK_STREAM, 0);
240 if (fd < 0) { 234 if (fd < 0) {
241 PLOG(ERROR) << "socket " << pipe_name; 235 PLOG(ERROR) << "socket " << pipe_name;
242 return false; 236 return false;
243 } 237 }
244 238
245 // Make socket non-blocking 239 // Make socket non-blocking
246 if (fcntl(fd, F_SETFL, O_NONBLOCK) == -1) { 240 if (fcntl(fd, F_SETFL, O_NONBLOCK) == -1) {
247 PLOG(ERROR) << "fcntl " << pipe_name; 241 PLOG(ERROR) << "fcntl(O_NONBLOCK) " << pipe_name;
248 if (HANDLE_EINTR(close(fd)) < 0) 242 if (HANDLE_EINTR(close(fd)) < 0)
249 PLOG(ERROR) << "close " << pipe_name; 243 PLOG(ERROR) << "close " << pipe_name;
250 return false; 244 return false;
251 } 245 }
252 246
253 // Create server side of socket. 247 // Create server side of socket.
254 struct sockaddr_un server_unix_addr; 248 struct sockaddr_un server_unix_addr;
255 memset(&server_unix_addr, 0, sizeof(server_unix_addr)); 249 memset(&server_unix_addr, 0, sizeof(server_unix_addr));
256 server_unix_addr.sun_family = AF_UNIX; 250 server_unix_addr.sun_family = AF_UNIX;
257 snprintf(server_unix_addr.sun_path, kMaxPipeNameLength, "%s", 251 snprintf(server_unix_addr.sun_path, kMaxPipeNameLength, "%s",
(...skipping 32 matching lines...) Expand 10 before | Expand all | Expand 10 after
290 #endif 284 #endif
291 } 285 }
292 286
293 } // namespace 287 } // namespace
294 //------------------------------------------------------------------------------ 288 //------------------------------------------------------------------------------
295 289
296 Channel::ChannelImpl::ChannelImpl(const IPC::ChannelHandle& channel_handle, 290 Channel::ChannelImpl::ChannelImpl(const IPC::ChannelHandle& channel_handle,
297 Mode mode, Listener* listener) 291 Mode mode, Listener* listener)
298 : mode_(mode), 292 : mode_(mode),
299 is_blocked_on_write_(false), 293 is_blocked_on_write_(false),
294 waiting_connect_(true),
300 message_send_bytes_written_(0), 295 message_send_bytes_written_(0),
301 uses_fifo_(
302 CommandLine::ForCurrentProcess()->HasSwitch(switches::kIPCUseFIFO) ||
303 mode == MODE_NAMED_SERVER || mode == MODE_NAMED_CLIENT),
304 server_listen_pipe_(-1), 296 server_listen_pipe_(-1),
305 pipe_(-1), 297 pipe_(-1),
306 client_pipe_(-1), 298 client_pipe_(-1),
307 #if defined(IPC_USES_READWRITE) 299 #if defined(IPC_USES_READWRITE)
308 fd_pipe_(-1), 300 fd_pipe_(-1),
309 remote_fd_pipe_(-1), 301 remote_fd_pipe_(-1),
310 #endif 302 #endif
303 pipe_name_(channel_handle.name),
311 listener_(listener), 304 listener_(listener),
312 waiting_connect_(true),
313 factory_(this) { 305 factory_(this) {
314 if (mode_ == MODE_NAMED_SERVER)
315 mode_ = MODE_SERVER;
316 if (mode_ == MODE_NAMED_CLIENT)
317 mode_ = MODE_CLIENT;
318
319 if (!CreatePipe(channel_handle, mode_)) { 306 if (!CreatePipe(channel_handle, mode_)) {
320 // The pipe may have been closed already. 307 // The pipe may have been closed already.
308 const char *modestr = (mode_ == MODE_SERVER
309 || mode_ == MODE_NAMED_SERVER) ? "server" : "client";
310 // The pipe may have been closed already.
321 LOG(WARNING) << "Unable to create pipe named \"" << channel_handle.name 311 LOG(WARNING) << "Unable to create pipe named \"" << channel_handle.name
322 << "\" in " << (mode_ == MODE_SERVER ? "server" : "client") 312 << "\" in " << modestr << " mode";
323 << " mode";
324 } 313 }
325 } 314 }
326 315
327 Channel::ChannelImpl::~ChannelImpl() { 316 Channel::ChannelImpl::~ChannelImpl() {
328 Close(); 317 Close();
329 } 318 }
330 319
331 // static
332 void AddChannelSocket(const std::string& name, int socket) {
333 PipeMap::GetInstance()->Insert(name, socket);
334 }
335
336 // static
337 void RemoveAndCloseChannelSocket(const std::string& name) {
338 PipeMap::GetInstance()->RemoveAndClose(name);
339 }
340
341 // static
342 bool ChannelSocketExists(const std::string& name) {
343 return PipeMap::GetInstance()->Lookup(name) != -1;
344 }
345
346 // static
347 bool SocketPair(int* fd1, int* fd2) { 320 bool SocketPair(int* fd1, int* fd2) {
348 int pipe_fds[2]; 321 int pipe_fds[2];
349 if (socketpair(AF_UNIX, SOCK_STREAM, 0, pipe_fds) != 0) { 322 if (socketpair(AF_UNIX, SOCK_STREAM, 0, pipe_fds) != 0) {
350 PLOG(ERROR) << "socketpair()"; 323 PLOG(ERROR) << "socketpair()";
351 return false; 324 return false;
352 } 325 }
353 326
354 // Set both ends to be non-blocking. 327 // Set both ends to be non-blocking.
355 if (fcntl(pipe_fds[0], F_SETFL, O_NONBLOCK) == -1 || 328 if (fcntl(pipe_fds[0], F_SETFL, O_NONBLOCK) == -1 ||
356 fcntl(pipe_fds[1], F_SETFL, O_NONBLOCK) == -1) { 329 fcntl(pipe_fds[1], F_SETFL, O_NONBLOCK) == -1) {
357 PLOG(ERROR) << "fcntl(O_NONBLOCK)"; 330 PLOG(ERROR) << "fcntl(O_NONBLOCK)";
358 if (HANDLE_EINTR(close(pipe_fds[0])) < 0) 331 if (HANDLE_EINTR(close(pipe_fds[0])) < 0)
359 PLOG(ERROR) << "close"; 332 PLOG(ERROR) << "close";
360 if (HANDLE_EINTR(close(pipe_fds[1])) < 0) 333 if (HANDLE_EINTR(close(pipe_fds[1])) < 0)
361 PLOG(ERROR) << "close"; 334 PLOG(ERROR) << "close";
362 return false; 335 return false;
363 } 336 }
364 337
365 *fd1 = pipe_fds[0]; 338 *fd1 = pipe_fds[0];
366 *fd2 = pipe_fds[1]; 339 *fd2 = pipe_fds[1];
367 340
368 return true; 341 return true;
369 } 342 }
370 343
371 bool Channel::ChannelImpl::CreatePipe(const IPC::ChannelHandle &channel_handle, 344 bool Channel::ChannelImpl::CreatePipe(const IPC::ChannelHandle& channel_handle,
372 Mode mode) { 345 Mode mode) {
Nico 2010/12/10 18:08:03 do you need the |mode| parameter?
dmac 2010/12/13 18:32:29 Done.
373 DCHECK(server_listen_pipe_ == -1 && pipe_ == -1); 346 DCHECK(server_listen_pipe_ == -1 && pipe_ == -1);
374 pipe_name_ = channel_handle.name; 347
375 pipe_ = channel_handle.socket.fd; 348 // Four possible cases:
376 if (uses_fifo_) { 349 // 1) It's a channel wrapping a pipe that is given to us.
377 // This only happens in unit tests; see the comment above PipeMap. 350 // 2) It's for a named channel, so we create it.
378 // TODO(playmobil): We shouldn't need to create fifos on disk. 351 // 3) It's for a client that we implement ourself. This is used
379 // TODO(playmobil): If we do, they should be in the user data directory. 352 // in unittesting.
380 // TODO(playmobil): Cleanup any stale fifos. 353 // 4) It's the initial IPC channel:
381 if (mode == MODE_SERVER) { 354 // 4a) Client side: Pull the pipe out of the GlobalDescriptors set.
382 if (!CreateServerFifo(pipe_name_, &server_listen_pipe_)) { 355 // 4b) Server side: create the pipe.
356
357 // Check to see if we want to implement using domain sockets.
358 bool uses_domain_socket = false;
Nico 2010/12/10 18:08:03 = mode_ == MODE_NAMED_SERVER || mode_ == MODE_NAME
359 if (mode_ == MODE_NAMED_SERVER) {
360 uses_domain_socket = true;
361 mode_ = MODE_SERVER;
Nico 2010/12/10 18:08:03 |mode_| changing somewhere in the middle of this c
dmac 2010/12/13 18:32:29 Done.
362 } else if (mode_ == MODE_NAMED_CLIENT) {
363 uses_domain_socket = true;
364 mode_ = MODE_CLIENT;
365 }
366
367 if (channel_handle.socket.fd != -1) {
368 // Case 1
jeremy 2010/12/12 14:59:29 Could you add a bit of descriptive text to these r
dmac 2010/12/13 18:32:29 Done. Mapped them to the comment above to avoid du
369 pipe_ = channel_handle.socket.fd;
370 #if defined(IPC_USES_READWRITE)
371 // Test the socket passed into us to make sure it is nonblocking.
372 // We don't want to call read/write on a blocking socket.
373 int value = fcntl(pipe_, F_GETFL);
374 if (value == -1) {
375 PLOG(ERROR) << "fcntl(F_GETFL) " << pipe_name_;
376 return false;
377 }
378 if (!(value & O_NONBLOCK)) {
379 LOG(ERROR) << "Socket " << pipe_name_ << " must be O_NONBLOCK";
380 return false;
381 }
382 #endif // defined(IPC_USES_READWRITE)
jeremy 2010/12/12 14:59:29 // IPC_USES_READWRITE
dmac 2010/12/13 18:32:29 Done.
383 } else if (uses_domain_socket) {
384 // Case 2
385 must_unlink_ = true;
386 if (mode_ == MODE_SERVER) {
387 if (!CreateServerUnixDomainSocket(pipe_name_, &pipe_)) {
383 return false; 388 return false;
384 } 389 }
385 } else { 390 } else if (mode_ == MODE_CLIENT) {
386 if (!ClientConnectToFifo(pipe_name_, &pipe_)) { 391 if (!CreateClientUnixDomainSocket(pipe_name_, &pipe_)) {
387 return false; 392 return false;
388 } 393 }
389 waiting_connect_ = false;
390 } 394 }
391 } else { 395 } else {
392 // This is the normal (non-unit-test) case, where we're using sockets. 396 pipe_ = Singleton<PipeMap>()->Lookup(pipe_name_);
393 // Three possible cases: 397 if (mode_ == MODE_CLIENT) {
394 // 1) It's for a channel we already have a pipe for; reuse it. 398 if (pipe_ != -1) {
395 // 2) It's the initial IPC channel: 399 // Case 3
396 // 2a) Server side: create the pipe. 400 // We only allow one connection.
397 // 2b) Client side: Pull the pipe out of the GlobalDescriptors set. 401 pipe_ = dup(pipe_);
jeremy 2010/12/12 14:59:29 HANDLE_EINTR(dup(pipe_));
dmac 2010/12/13 18:32:29 Done.
398 if (pipe_ < 0) { 402 Singleton<PipeMap>()->RemoveAndClose(pipe_name_);
399 pipe_ = ChannelNameToFD(pipe_name_);
400 }
401 if (pipe_ < 0) {
402 // Initial IPC channel.
403 if (mode == MODE_SERVER) {
404 if (!SocketPair(&pipe_, &client_pipe_))
405 return false;
406 AddChannelSocket(pipe_name_, client_pipe_);
407 } else { 403 } else {
404 // Case 4a
408 // Guard against inappropriate reuse of the initial IPC channel. If 405 // Guard against inappropriate reuse of the initial IPC channel. If
409 // an IPC channel closes and someone attempts to reuse it by name, the 406 // an IPC channel closes and someone attempts to reuse it by name, the
410 // initial channel must not be recycled here. http://crbug.com/26754. 407 // initial channel must not be recycled here. http://crbug.com/26754.
411 static bool used_initial_channel = false; 408 static bool used_initial_channel = false;
412 if (used_initial_channel) { 409 if (used_initial_channel) {
413 LOG(FATAL) << "Denying attempt to reuse initial IPC channel for " 410 LOG(FATAL) << "Denying attempt to reuse initial IPC channel for "
414 << pipe_name_; 411 << pipe_name_;
415 return false; 412 return false;
416 } 413 }
417 used_initial_channel = true; 414 used_initial_channel = true;
418 415
419 pipe_ = base::GlobalDescriptors::GetInstance()->Get(kPrimaryIPCChannel); 416 pipe_ = base::GlobalDescriptors::GetInstance()->Get(kPrimaryIPCChannel);
420 } 417 }
418 } else if (mode_ == MODE_SERVER) {
419 // Case 4b
420 if (pipe_ != -1) {
421 LOG(ERROR) << "Server already exists for " << pipe_name_;
422 return false;
423 }
424 if (!SocketPair(&pipe_, &client_pipe_))
425 return false;
426 Singleton<PipeMap>()->Insert(pipe_name_, client_pipe_);
421 } else { 427 } else {
422 waiting_connect_ = mode == MODE_SERVER; 428 LOG(FATAL) << "Unknown mode " << mode_;
429 return false;
423 } 430 }
424 } 431 }
425 432
426 // Create the Hello message to be sent when Connect is called 433 if (mode_ == MODE_SERVER) {
427 scoped_ptr<Message> msg(new Message(MSG_ROUTING_NONE, 434 int listening = 0;
428 HELLO_MESSAGE_TYPE, 435 // We support sockets that we are connected to and listening to.
429 IPC::Message::PRIORITY_NORMAL)); 436 // Currently we only support one connection per socket that we are
430 #if defined(IPC_USES_READWRITE) 437 // listening to.
431 if (!uses_fifo_) { 438 // Check to see if the socket is one that we are connected to
432 // Create a dedicated socketpair() for exchanging file descriptors. 439 // or one that we are listening to for connections.
433 // See comments for IPC_USES_READWRITE for details. 440 #if !defined(OS_MACOSX)
434 if (mode == MODE_SERVER) { 441 socklen_t len = sizeof(listening);
435 fd_pipe_ = -1; 442 if (getsockopt(pipe_, SOL_SOCKET, SO_ACCEPTCONN,
436 } else if (remote_fd_pipe_ == -1) { 443 &listening, &len) < 0) {
437 if (!SocketPair(&fd_pipe_, &remote_fd_pipe_)) { 444 PLOG(ERROR) << "Unable to get socket options for " << pipe_name_;
438 return false; 445 return false;
439 } 446 }
447 #else
448 // Darwin <= Mac OS X 10.6.4 does not support SO_ACCEPTCONN.
449 // The poor man's version is to call poll and check to see if the socket
450 // in question supports writing. If it doesn't support writing, it is
451 // assumed that it is listening for connections.
452 struct pollfd pfd = { pipe_, POLLOUT, 0};
453 int count = poll(&pfd, 1, 0);
454 if (count < 0) {
455 PLOG(ERROR) << "Unable to poll " << pipe_name_;
456 return false;
457 }
458 listening = count > 0 ? 0 : 1;
Nico 2010/12/10 18:48:07 drop | ? 0 : 1|
dmac 2010/12/13 18:32:29 Done.
459 #endif
jeremy 2010/12/12 14:59:29 // OS_MACOSX
dmac 2010/12/13 18:32:29 Done.
460 if (listening) {
461 server_listen_pipe_ = pipe_;
462 pipe_ = -1;
440 } 463 }
441 } 464 }
442 #endif 465
443 if (!msg->WriteInt(base::GetCurrentProcId())) { 466 #if defined(IPC_USES_READWRITE)
444 Close(); 467 // Create a dedicated socketpair() for exchanging file descriptors.
445 return false; 468 // See comments for IPC_USES_READWRITE for details.
469 if (mode_ == MODE_CLIENT) {
470 if (!SocketPair(&fd_pipe_, &remote_fd_pipe_)) {
471 return false;
472 }
446 } 473 }
474 #endif
jeremy 2010/12/12 14:59:29 // IPC_USES_READWRITE
dmac 2010/12/13 18:32:29 Done.
447 475
448 output_queue_.push(msg.release());
449 return true; 476 return true;
450 } 477 }
451 478
452 bool Channel::ChannelImpl::Connect() { 479 bool Channel::ChannelImpl::Connect() {
453 if (mode_ == MODE_SERVER && uses_fifo_) { 480 if (server_listen_pipe_ == -1 && pipe_ == -1) {
454 if (server_listen_pipe_ == -1) { 481 NOTREACHED() << "Must call create on a channel before calling connect";
455 return false; 482 return false;
456 } 483 }
484
485 bool did_connect = true;
486 if (server_listen_pipe_ != -1) {
487 // Watch the pipe for connections, and turn any connections into
488 // active sockets.
457 MessageLoopForIO::current()->WatchFileDescriptor( 489 MessageLoopForIO::current()->WatchFileDescriptor(
458 server_listen_pipe_, 490 server_listen_pipe_,
459 true, 491 true,
460 MessageLoopForIO::WATCH_READ, 492 MessageLoopForIO::WATCH_READ,
461 &server_listen_connection_watcher_, 493 &server_listen_connection_watcher_,
462 this); 494 this);
463 } else { 495 } else {
464 if (pipe_ == -1) { 496 did_connect = AcceptConnection();
465 return false;
466 }
467 MessageLoopForIO::current()->WatchFileDescriptor(
468 pipe_,
469 true,
470 MessageLoopForIO::WATCH_READ,
471 &read_watcher_,
472 this);
473 waiting_connect_ = mode_ == MODE_SERVER;
474 } 497 }
475 498 return did_connect;
476 if (!waiting_connect_)
477 return ProcessOutgoingMessages();
478 return true;
479 } 499 }
480 500
481 bool Channel::ChannelImpl::ProcessIncomingMessages() { 501 bool Channel::ChannelImpl::ProcessIncomingMessages() {
482 ssize_t bytes_read = 0; 502 ssize_t bytes_read = 0;
483 503
484 struct msghdr msg = {0}; 504 struct msghdr msg = {0};
485 struct iovec iov = {input_buf_, Channel::kReadBufferSize}; 505 struct iovec iov = {input_buf_, Channel::kReadBufferSize};
486 506
487 msg.msg_iovlen = 1; 507 msg.msg_iovlen = 1;
488 msg.msg_control = input_cmsg_buf_; 508 msg.msg_control = input_cmsg_buf_;
(...skipping 76 matching lines...) Expand 10 before | Expand all | Expand 10 after
565 DCHECK(payload_len % sizeof(int) == 0); 585 DCHECK(payload_len % sizeof(int) == 0);
566 wire_fds = reinterpret_cast<int*>(CMSG_DATA(cmsg)); 586 wire_fds = reinterpret_cast<int*>(CMSG_DATA(cmsg));
567 num_wire_fds = payload_len / 4; 587 num_wire_fds = payload_len / 4;
568 588
569 if (msg.msg_flags & MSG_CTRUNC) { 589 if (msg.msg_flags & MSG_CTRUNC) {
570 LOG(ERROR) << "SCM_RIGHTS message was truncated" 590 LOG(ERROR) << "SCM_RIGHTS message was truncated"
571 << " cmsg_len:" << cmsg->cmsg_len 591 << " cmsg_len:" << cmsg->cmsg_len
572 << " fd:" << pipe_; 592 << " fd:" << pipe_;
573 for (unsigned i = 0; i < num_wire_fds; ++i) 593 for (unsigned i = 0; i < num_wire_fds; ++i)
574 if (HANDLE_EINTR(close(wire_fds[i])) < 0) 594 if (HANDLE_EINTR(close(wire_fds[i])) < 0)
575 PLOG(ERROR) << "close" << i; 595 PLOG(ERROR) << "close " << i;
576 return false; 596 return false;
577 } 597 }
578 break; 598 break;
579 } 599 }
580 } 600 }
581 } 601 }
582 602
583 // Process messages from input buffer. 603 // Process messages from input buffer.
584 const char *p; 604 const char *p;
585 const char *end; 605 const char *end;
(...skipping 38 matching lines...) Expand 10 before | Expand all | Expand 10 after
624 int len = static_cast<int>(message_tail - p); 644 int len = static_cast<int>(message_tail - p);
625 Message m(p, len); 645 Message m(p, len);
626 const uint16 header_fds = m.header()->num_fds; 646 const uint16 header_fds = m.header()->num_fds;
627 if (header_fds) { 647 if (header_fds) {
628 // the message has file descriptors 648 // the message has file descriptors
629 const char* error = NULL; 649 const char* error = NULL;
630 if (header_fds > num_fds - fds_i) { 650 if (header_fds > num_fds - fds_i) {
631 // the message has been completely received, but we didn't get 651 // the message has been completely received, but we didn't get
632 // enough file descriptors. 652 // enough file descriptors.
633 #if defined(IPC_USES_READWRITE) 653 #if defined(IPC_USES_READWRITE)
634 if (!uses_fifo_) { 654 char dummy;
635 char dummy; 655 struct iovec fd_pipe_iov = { &dummy, 1 };
636 struct iovec fd_pipe_iov = { &dummy, 1 }; 656 msg.msg_iov = &fd_pipe_iov;
637 msg.msg_iov = &fd_pipe_iov; 657 msg.msg_controllen = sizeof(input_cmsg_buf_);
638 msg.msg_controllen = sizeof(input_cmsg_buf_); 658 ssize_t n = HANDLE_EINTR(recvmsg(fd_pipe_, &msg, MSG_DONTWAIT));
639 ssize_t n = HANDLE_EINTR(recvmsg(fd_pipe_, &msg, MSG_DONTWAIT)); 659 if (n == 1 && msg.msg_controllen > 0) {
640 if (n == 1 && msg.msg_controllen > 0) { 660 for (struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg); cmsg;
641 for (struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg); cmsg; 661 cmsg = CMSG_NXTHDR(&msg, cmsg)) {
642 cmsg = CMSG_NXTHDR(&msg, cmsg)) { 662 if (cmsg->cmsg_level == SOL_SOCKET &&
643 if (cmsg->cmsg_level == SOL_SOCKET && 663 cmsg->cmsg_type == SCM_RIGHTS) {
644 cmsg->cmsg_type == SCM_RIGHTS) { 664 const unsigned payload_len = cmsg->cmsg_len - CMSG_LEN(0);
645 const unsigned payload_len = cmsg->cmsg_len - CMSG_LEN(0); 665 DCHECK(payload_len % sizeof(int) == 0);
646 DCHECK(payload_len % sizeof(int) == 0); 666 wire_fds = reinterpret_cast<int*>(CMSG_DATA(cmsg));
647 wire_fds = reinterpret_cast<int*>(CMSG_DATA(cmsg)); 667 num_wire_fds = payload_len / 4;
648 num_wire_fds = payload_len / 4;
649 668
650 if (msg.msg_flags & MSG_CTRUNC) { 669 if (msg.msg_flags & MSG_CTRUNC) {
651 LOG(ERROR) << "SCM_RIGHTS message was truncated" 670 LOG(ERROR) << "SCM_RIGHTS message was truncated"
652 << " cmsg_len:" << cmsg->cmsg_len 671 << " cmsg_len:" << cmsg->cmsg_len
653 << " fd:" << pipe_; 672 << " fd:" << pipe_;
654 for (unsigned i = 0; i < num_wire_fds; ++i) 673 for (unsigned i = 0; i < num_wire_fds; ++i)
655 if (HANDLE_EINTR(close(wire_fds[i])) < 0) 674 if (HANDLE_EINTR(close(wire_fds[i])) < 0)
656 PLOG(ERROR) << "close" << i; 675 PLOG(ERROR) << "close " << i;
657 return false; 676 return false;
658 }
659 break;
660 } 677 }
678 break;
661 } 679 }
662 if (input_overflow_fds_.empty()) { 680 }
663 fds = wire_fds; 681 if (input_overflow_fds_.empty()) {
664 num_fds = num_wire_fds; 682 fds = wire_fds;
665 } else { 683 num_fds = num_wire_fds;
666 if (num_wire_fds > 0) { 684 } else {
667 const size_t prev_size = input_overflow_fds_.size(); 685 if (num_wire_fds > 0) {
668 input_overflow_fds_.resize(prev_size + num_wire_fds); 686 const size_t prev_size = input_overflow_fds_.size();
669 memcpy(&input_overflow_fds_[prev_size], wire_fds, 687 input_overflow_fds_.resize(prev_size + num_wire_fds);
670 num_wire_fds * sizeof(int)); 688 memcpy(&input_overflow_fds_[prev_size], wire_fds,
671 } 689 num_wire_fds * sizeof(int));
672 fds = &input_overflow_fds_[0];
673 num_fds = input_overflow_fds_.size();
674 } 690 }
691 fds = &input_overflow_fds_[0];
692 num_fds = input_overflow_fds_.size();
675 } 693 }
676 } 694 }
677 if (header_fds > num_fds - fds_i) 695 if (header_fds > num_fds - fds_i)
678 #endif 696 #endif
679 error = "Message needs unreceived descriptors"; 697 error = "Message needs unreceived descriptors";
680 } 698 }
681 699
682 if (header_fds > 700 if (header_fds >
683 FileDescriptorSet::MAX_DESCRIPTORS_PER_MESSAGE) { 701 FileDescriptorSet::MAX_DESCRIPTORS_PER_MESSAGE) {
684 // There are too many descriptors in this message 702 // There are too many descriptors in this message
685 error = "Message requires an excessive number of descriptors"; 703 error = "Message requires an excessive number of descriptors";
686 } 704 }
687 705
688 if (error) { 706 if (error) {
689 LOG(WARNING) << error 707 LOG(WARNING) << error
690 << " channel:" << this 708 << " channel:" << this
691 << " message-type:" << m.type() 709 << " message-type:" << m.type()
692 << " header()->num_fds:" << header_fds 710 << " header()->num_fds:" << header_fds
693 << " num_fds:" << num_fds 711 << " num_fds:" << num_fds
694 << " fds_i:" << fds_i; 712 << " fds_i:" << fds_i;
695 #if defined(CHROMIUM_SELINUX) 713 #if defined(CHROMIUM_SELINUX)
696 LOG(WARNING) << "In the case of SELinux this can be caused when " 714 LOG(WARNING) << "In the case of SELinux this can be caused when "
697 "using a --user-data-dir to which the default " 715 "using a --user-data-dir to which the default "
698 "policy doesn't give the renderer access to. "; 716 "policy doesn't give the renderer access to. ";
699 #endif 717 #endif
700 // close the existing file descriptors so that we don't leak them 718 // close the existing file descriptors so that we don't leak them
701 for (unsigned i = fds_i; i < num_fds; ++i) 719 for (unsigned i = fds_i; i < num_fds; ++i)
702 if (HANDLE_EINTR(close(fds[i])) < 0) 720 if (HANDLE_EINTR(close(fds[i])) < 0)
703 PLOG(ERROR) << "close" << i; 721 PLOG(ERROR) << "close " << i;
704 input_overflow_fds_.clear(); 722 input_overflow_fds_.clear();
705 // abort the connection 723 // abort the connection
706 return false; 724 return false;
707 } 725 }
708 726
709 m.file_descriptor_set()->SetDescriptors( 727 m.file_descriptor_set()->SetDescriptors(
710 &fds[fds_i], header_fds); 728 &fds[fds_i], header_fds);
711 fds_i += header_fds; 729 fds_i += header_fds;
712 } 730 }
713 DVLOG(2) << "received message on channel @" << this 731 DVLOG(2) << "received message on channel @" << this
714 << " with type " << m.type() << " on fd " << pipe_; 732 << " with type " << m.type() << " on fd " << pipe_;
715 if (m.routing_id() == MSG_ROUTING_NONE && 733 if (IsHelloMessage(&m)) {
716 m.type() == HELLO_MESSAGE_TYPE) {
717 // The Hello message contains only the process id. 734 // The Hello message contains only the process id.
718 void *iter = NULL; 735 void *iter = NULL;
719 int pid; 736 int pid;
720 if (!m.ReadInt(&iter, &pid)) { 737 if (!m.ReadInt(&iter, &pid)) {
721 NOTREACHED(); 738 NOTREACHED();
722 } 739 }
723 #if defined(IPC_USES_READWRITE) 740 #if defined(IPC_USES_READWRITE)
724 if (mode_ == MODE_SERVER && !uses_fifo_) { 741 if (mode_ == MODE_SERVER) {
725 // On non-Mac, the Hello message from the client to the server 742 // With IPC_USES_READWRITE, the Hello message from the client to the
726 // also contains the fd_pipe_, which will be used for all 743 // server also contains the fd_pipe_, which will be used for all
727 // subsequent file descriptor passing. 744 // subsequent file descriptor passing.
728 DCHECK_EQ(m.file_descriptor_set()->size(), 1U); 745 DCHECK_EQ(m.file_descriptor_set()->size(), 1U);
729 base::FileDescriptor descriptor; 746 base::FileDescriptor descriptor;
730 if (!m.ReadFileDescriptor(&iter, &descriptor)) { 747 if (!m.ReadFileDescriptor(&iter, &descriptor)) {
731 NOTREACHED(); 748 NOTREACHED();
732 } 749 }
733 fd_pipe_ = descriptor.fd; 750 fd_pipe_ = descriptor.fd;
734 CHECK(descriptor.auto_close); 751 CHECK(descriptor.auto_close);
735 } 752 }
736 #endif 753 #endif
(...skipping 17 matching lines...) Expand all
754 // When the input data buffer is empty, the overflow fds should be too. If 771 // When the input data buffer is empty, the overflow fds should be too. If
755 // this is not the case, we probably have a rogue renderer which is trying 772 // this is not the case, we probably have a rogue renderer which is trying
756 // to fill our descriptor table. 773 // to fill our descriptor table.
757 if (input_overflow_buf_.empty() && !input_overflow_fds_.empty()) { 774 if (input_overflow_buf_.empty() && !input_overflow_fds_.empty()) {
758 // We close these descriptors in Close() 775 // We close these descriptors in Close()
759 return false; 776 return false;
760 } 777 }
761 778
762 bytes_read = 0; // Get more data. 779 bytes_read = 0; // Get more data.
763 } 780 }
764
765 return true;
jeremy 2010/12/12 14:59:29 You sure it's ok to remove this?
dmac 2010/12/13 18:32:29 Yep, it compiles cleanly without it.
766 } 781 }
767 782
768 bool Channel::ChannelImpl::ProcessOutgoingMessages() { 783 bool Channel::ChannelImpl::ProcessOutgoingMessages() {
769 DCHECK(!waiting_connect_); // Why are we trying to send messages if there's 784 DCHECK(!waiting_connect_); // Why are we trying to send messages if there's
770 // no connection? 785 // no connection?
771 is_blocked_on_write_ = false; 786 if (output_queue_.empty())
787 return true;
772 788
773 if (output_queue_.empty()) { 789 if (pipe_ == -1)
774 return true;
775 }
776
777 if (pipe_ == -1) {
778 return false; 790 return false;
779 }
780 791
781 // Write out all the messages we can till the write blocks or there are no 792 // Write out all the messages we can till the write blocks or there are no
782 // more outgoing messages. 793 // more outgoing messages.
783 while (!output_queue_.empty()) { 794 while (!output_queue_.empty()) {
784 Message* msg = output_queue_.front(); 795 Message* msg = output_queue_.front();
785 796
786 #if defined(IPC_USES_READWRITE)
787 scoped_ptr<Message> hello;
788 if (remote_fd_pipe_ != -1 &&
789 msg->routing_id() == MSG_ROUTING_NONE &&
790 msg->type() == HELLO_MESSAGE_TYPE) {
791 hello.reset(new Message(MSG_ROUTING_NONE,
792 HELLO_MESSAGE_TYPE,
793 IPC::Message::PRIORITY_NORMAL));
794 void* iter = NULL;
795 int pid;
796 if (!msg->ReadInt(&iter, &pid) ||
797 !hello->WriteInt(pid)) {
798 NOTREACHED();
799 }
800 DCHECK_EQ(hello->size(), msg->size());
801 if (!hello->WriteFileDescriptor(base::FileDescriptor(remote_fd_pipe_,
802 false))) {
803 NOTREACHED();
804 }
805 msg = hello.get();
806 DCHECK_EQ(msg->file_descriptor_set()->size(), 1U);
807 }
808 #endif
809
810 size_t amt_to_write = msg->size() - message_send_bytes_written_; 797 size_t amt_to_write = msg->size() - message_send_bytes_written_;
811 DCHECK(amt_to_write != 0); 798 DCHECK(amt_to_write != 0);
812 const char* out_bytes = reinterpret_cast<const char*>(msg->data()) + 799 const char* out_bytes = reinterpret_cast<const char*>(msg->data()) +
813 message_send_bytes_written_; 800 message_send_bytes_written_;
814 801
815 struct msghdr msgh = {0}; 802 struct msghdr msgh = {0};
816 struct iovec iov = {const_cast<char*>(out_bytes), amt_to_write}; 803 struct iovec iov = {const_cast<char*>(out_bytes), amt_to_write};
817 msgh.msg_iov = &iov; 804 msgh.msg_iov = &iov;
818 msgh.msg_iovlen = 1; 805 msgh.msg_iovlen = 1;
819 char buf[CMSG_SPACE( 806 char buf[CMSG_SPACE(
(...skipping 27 matching lines...) Expand all
847 cmsg->cmsg_len = CMSG_LEN(sizeof(int) * num_fds); 834 cmsg->cmsg_len = CMSG_LEN(sizeof(int) * num_fds);
848 msg->file_descriptor_set()->GetDescriptors( 835 msg->file_descriptor_set()->GetDescriptors(
849 reinterpret_cast<int*>(CMSG_DATA(cmsg))); 836 reinterpret_cast<int*>(CMSG_DATA(cmsg)));
850 msgh.msg_controllen = cmsg->cmsg_len; 837 msgh.msg_controllen = cmsg->cmsg_len;
851 838
852 // DCHECK_LE above already checks that 839 // DCHECK_LE above already checks that
853 // num_fds < MAX_DESCRIPTORS_PER_MESSAGE so no danger of overflow. 840 // num_fds < MAX_DESCRIPTORS_PER_MESSAGE so no danger of overflow.
854 msg->header()->num_fds = static_cast<uint16>(num_fds); 841 msg->header()->num_fds = static_cast<uint16>(num_fds);
855 842
856 #if defined(IPC_USES_READWRITE) 843 #if defined(IPC_USES_READWRITE)
857 if (!uses_fifo_ && 844 if (!IsHelloMessage(msg)) {
858 (msg->routing_id() != MSG_ROUTING_NONE ||
859 msg->type() != HELLO_MESSAGE_TYPE)) {
860 // Only the Hello message sends the file descriptor with the message. 845 // Only the Hello message sends the file descriptor with the message.
861 // Subsequently, we can send file descriptors on the dedicated 846 // Subsequently, we can send file descriptors on the dedicated
862 // fd_pipe_ which makes Seccomp sandbox operation more efficient. 847 // fd_pipe_ which makes Seccomp sandbox operation more efficient.
863 struct iovec fd_pipe_iov = { const_cast<char *>(""), 1 }; 848 struct iovec fd_pipe_iov = { const_cast<char *>(""), 1 };
864 msgh.msg_iov = &fd_pipe_iov; 849 msgh.msg_iov = &fd_pipe_iov;
865 fd_written = fd_pipe_; 850 fd_written = fd_pipe_;
866 bytes_written = HANDLE_EINTR(sendmsg(fd_pipe_, &msgh, MSG_DONTWAIT)); 851 bytes_written = HANDLE_EINTR(sendmsg(fd_pipe_, &msgh, MSG_DONTWAIT));
867 msgh.msg_iov = &iov; 852 msgh.msg_iov = &iov;
868 msgh.msg_controllen = 0; 853 msgh.msg_controllen = 0;
869 if (bytes_written > 0) { 854 if (bytes_written > 0) {
870 msg->file_descriptor_set()->CommitAll(); 855 msg->file_descriptor_set()->CommitAll();
871 } 856 }
872 } 857 }
873 #endif 858 #endif
874 } 859 }
875 860
876 if (bytes_written == 1) { 861 if (bytes_written == 1) {
877 fd_written = pipe_; 862 fd_written = pipe_;
878 #if defined(IPC_USES_READWRITE) 863 #if defined(IPC_USES_READWRITE)
879 if (mode_ != MODE_SERVER && !uses_fifo_ && 864 if (mode_ != MODE_SERVER && IsHelloMessage(msg)) {
880 msg->routing_id() == MSG_ROUTING_NONE &&
881 msg->type() == HELLO_MESSAGE_TYPE) {
882 DCHECK_EQ(msg->file_descriptor_set()->size(), 1U); 865 DCHECK_EQ(msg->file_descriptor_set()->size(), 1U);
883 } 866 }
884 if (!uses_fifo_ && !msgh.msg_controllen) { 867 if (!msgh.msg_controllen) {
885 bytes_written = HANDLE_EINTR(write(pipe_, out_bytes, amt_to_write)); 868 bytes_written = HANDLE_EINTR(write(pipe_, out_bytes, amt_to_write));
886 } else 869 } else
887 #endif 870 #endif
888 { 871 {
889 bytes_written = HANDLE_EINTR(sendmsg(pipe_, &msgh, MSG_DONTWAIT)); 872 bytes_written = HANDLE_EINTR(sendmsg(pipe_, &msgh, MSG_DONTWAIT));
890 } 873 }
891 } 874 }
892 if (bytes_written > 0) 875 if (bytes_written > 0)
893 msg->file_descriptor_set()->CommitAll(); 876 msg->file_descriptor_set()->CommitAll();
894 877
(...skipping 47 matching lines...) Expand 10 before | Expand all | Expand 10 after
942 bool Channel::ChannelImpl::Send(Message* message) { 925 bool Channel::ChannelImpl::Send(Message* message) {
943 DVLOG(2) << "sending message @" << message << " on channel @" << this 926 DVLOG(2) << "sending message @" << message << " on channel @" << this
944 << " with type " << message->type() 927 << " with type " << message->type()
945 << " (" << output_queue_.size() << " in queue)"; 928 << " (" << output_queue_.size() << " in queue)";
946 929
947 #ifdef IPC_MESSAGE_LOG_ENABLED 930 #ifdef IPC_MESSAGE_LOG_ENABLED
948 Logging::current()->OnSendMessage(message, ""); 931 Logging::current()->OnSendMessage(message, "");
949 #endif 932 #endif
950 933
951 output_queue_.push(message); 934 output_queue_.push(message);
952 if (!waiting_connect_) { 935 if (!is_blocked_on_write_ && !waiting_connect_) {
953 if (!is_blocked_on_write_) { 936 return ProcessOutgoingMessages();
954 if (!ProcessOutgoingMessages())
955 return false;
956 }
957 } 937 }
958 938
959 return true; 939 return true;
960 } 940 }
961 941
962 int Channel::ChannelImpl::GetClientFileDescriptor() const { 942 int Channel::ChannelImpl::GetClientFileDescriptor() const {
963 return client_pipe_; 943 return client_pipe_;
964 } 944 }
965 945
966 // Called by libevent when we can read from th pipe without blocking. 946 bool Channel::ChannelImpl::AcceptsConnections() const {
947 return server_listen_pipe_ != -1;
948 }
949
950 bool Channel::ChannelImpl::HasAcceptedConnection() const {
951 return AcceptsConnections() && pipe_ != -1;
952 }
953
954 void Channel::ChannelImpl::ResetToAcceptingConnectionState() {
955 if (pipe_ == -1)
956 return;
957
958 // Unregister libevent for the unix domain socket and close it.
959 read_watcher_.StopWatchingFileDescriptor();
960 write_watcher_.StopWatchingFileDescriptor();
961 if (HANDLE_EINTR(close(pipe_)) < 0)
962 PLOG(ERROR) << "close pipe_ " << pipe_name_;
963 pipe_ = -1;
964 #if defined(IPC_USES_READWRITE)
965 if (fd_pipe_ != -1) {
966 if (HANDLE_EINTR(close(fd_pipe_)) < 0)
967 PLOG(ERROR) << "close fd_pipe_ " << pipe_name_;
968 fd_pipe_ = -1;
969 }
970 if (remote_fd_pipe_ != -1) {
971 if (HANDLE_EINTR(close(remote_fd_pipe_)) < 0)
972 PLOG(ERROR) << "close remote_fd_pipe_ " << pipe_name_;
973 remote_fd_pipe_ = -1;
974 }
975 #endif
976
977 while (!output_queue_.empty()) {
978 Message* m = output_queue_.front();
979 output_queue_.pop();
980 delete m;
981 }
982
983 // Close any outstanding, received file descriptors
jeremy 2010/12/12 14:59:29 .
dmac 2010/12/13 18:32:29 Done.
984 for (std::vector<int>::iterator
985 i = input_overflow_fds_.begin(); i != input_overflow_fds_.end(); ++i) {
986 if (HANDLE_EINTR(close(*i)) < 0)
987 PLOG(ERROR) << "close";
988 }
989 input_overflow_fds_.clear();
990 }
991
992 // Called by libevent when we can read from the pipe without blocking.
967 void Channel::ChannelImpl::OnFileCanReadWithoutBlocking(int fd) { 993 void Channel::ChannelImpl::OnFileCanReadWithoutBlocking(int fd) {
968 bool send_server_hello_msg = false; 994 bool send_server_hello_msg = false;
969 if (waiting_connect_ && mode_ == MODE_SERVER) { 995 if (fd == server_listen_pipe_) {
970 if (uses_fifo_) { 996 int new_pipe = 0;
971 if (!ServerAcceptFifoConnection(server_listen_pipe_, &pipe_)) { 997 if (!ServerAcceptConnection(server_listen_pipe_, &new_pipe)) {
972 Close(); 998 Close();
973 } 999 listener_->OnChannelListenError();
1000 }
974 1001
975 // No need to watch the listening socket any longer since only one client 1002 if (pipe_ != -1) {
976 // can connect. So unregister with libevent. 1003 // We already have a connection. We only handle one at a time.
977 server_listen_connection_watcher_.StopWatchingFileDescriptor(); 1004 // close our new descriptor.
1005 if (HANDLE_EINTR(shutdown(new_pipe, SHUT_RDWR)) < 0)
1006 PLOG(ERROR) << "shutdown " << pipe_name_;
1007 if (HANDLE_EINTR(close(new_pipe)) < 0)
1008 PLOG(ERROR) << "close " << pipe_name_;
1009 listener_->OnChannelDenied();
1010 return;
1011 }
1012 pipe_ = new_pipe;
978 1013
979 // Start watching our end of the socket. 1014 if (!AcceptConnection()) {
980 MessageLoopForIO::current()->WatchFileDescriptor( 1015 NOTREACHED() << "AcceptConnection should not fail on server";
981 pipe_, 1016 }
982 true, 1017 send_server_hello_msg = true;
983 MessageLoopForIO::WATCH_READ, 1018 waiting_connect_ = false;
984 &read_watcher_, 1019 } else if (fd == pipe_) {
985 this); 1020 if (waiting_connect_ && mode_ == MODE_SERVER) {
986 1021 send_server_hello_msg = true;
987 waiting_connect_ = false;
988 } else {
989 // In the case of a socketpair() the server starts listening on its end
990 // of the pipe in Connect().
991 waiting_connect_ = false; 1022 waiting_connect_ = false;
992 } 1023 }
993 send_server_hello_msg = true;
994 }
995
996 if (!waiting_connect_ && fd == pipe_) {
997 if (!ProcessIncomingMessages()) { 1024 if (!ProcessIncomingMessages()) {
998 Close(); 1025 ClosePipeOnError();
999 listener_->OnChannelError();
1000 // The OnChannelError() call may delete this, so we need to exit now.
1001 return;
1002 } 1026 }
1027 } else {
1028 NOTREACHED() << "Unknown pipe " << fd;
1003 } 1029 }
1004 1030
1005 // If we're a server and handshaking, then we want to make sure that we 1031 // If we're a server and handshaking, then we want to make sure that we
1006 // only send our handshake message after we've processed the client's. 1032 // only send our handshake message after we've processed the client's.
1007 // This gives us a chance to kill the client if the incoming handshake 1033 // This gives us a chance to kill the client if the incoming handshake
1008 // is invalid. 1034 // is invalid.
1009 if (send_server_hello_msg) { 1035 if (send_server_hello_msg) {
1010 ProcessOutgoingMessages(); 1036 ProcessOutgoingMessages();
1011 } 1037 }
1012 } 1038 }
1013 1039
1014 // Called by libevent when we can write to the pipe without blocking. 1040 // Called by libevent when we can write to the pipe without blocking.
1015 void Channel::ChannelImpl::OnFileCanWriteWithoutBlocking(int fd) { 1041 void Channel::ChannelImpl::OnFileCanWriteWithoutBlocking(int fd) {
1042 DCHECK(fd == pipe_);
1043 is_blocked_on_write_ = false;
1016 if (!ProcessOutgoingMessages()) { 1044 if (!ProcessOutgoingMessages()) {
1045 ClosePipeOnError();
1046 }
1047 }
1048
1049 bool Channel::ChannelImpl::AcceptConnection() {
1050 MessageLoopForIO::current()->WatchFileDescriptor(pipe_,
1051 true,
1052 MessageLoopForIO::WATCH_READ,
1053 &read_watcher_,
1054 this);
1055 QueueHelloMessage();
1056
1057 if (mode_ == MODE_CLIENT) {
1058 // If we are a client we want to send a hello message out immediately.
1059 // In server mode we will send a hello message when we receive one from a
1060 // client.
1061 waiting_connect_ = false;
1062 return ProcessOutgoingMessages();
1063 } else {
1064 waiting_connect_ = true;
1065 return true;
1066 }
1067 }
1068
1069 void Channel::ChannelImpl::ClosePipeOnError() {
1070 if (HasAcceptedConnection()) {
1071 ResetToAcceptingConnectionState();
1072 listener_->OnChannelError();
1073 } else {
1017 Close(); 1074 Close();
1018 listener_->OnChannelError(); 1075 if (AcceptsConnections()) {
1076 listener_->OnChannelListenError();
1077 } else {
1078 listener_->OnChannelError();
1079 }
1019 } 1080 }
1020 } 1081 }
1021 1082
1083 void Channel::ChannelImpl::QueueHelloMessage() {
1084 // Create the Hello message
1085 scoped_ptr<Message> msg(new Message(MSG_ROUTING_NONE,
1086 HELLO_MESSAGE_TYPE,
1087 IPC::Message::PRIORITY_NORMAL));
1088
1089 if (!msg->WriteInt(base::GetCurrentProcId())) {
1090 NOTREACHED() << "Unable to pickle hello message proc id";
1091 }
1092 #if defined(IPC_USES_READWRITE)
1093 scoped_ptr<Message> hello;
1094 if (remote_fd_pipe_ != -1) {
1095 if (!msg->WriteFileDescriptor(base::FileDescriptor(remote_fd_pipe_,
1096 false))) {
1097 NOTREACHED() << "Unable to pickle hello message file descriptors";
1098 }
1099 DCHECK_EQ(msg->file_descriptor_set()->size(), 1U);
1100 }
1101 #endif
1102 output_queue_.push(msg.release());
1103 }
1104
1105 bool Channel::ChannelImpl::IsHelloMessage(const Message* m) const {
1106 return m->routing_id() == MSG_ROUTING_NONE && m->type() == HELLO_MESSAGE_TYPE;
1107 }
1108
1022 void Channel::ChannelImpl::Close() { 1109 void Channel::ChannelImpl::Close() {
1023 // Close can be called multiple time, so we need to make sure we're 1110 // Close can be called multiple time, so we need to make sure we're
1024 // idempotent. 1111 // idempotent.
1025 1112
1026 // Unregister libevent for the listening socket and close it. 1113 ResetToAcceptingConnectionState();
1027 server_listen_connection_watcher_.StopWatchingFileDescriptor();
1028 1114
1115 if (must_unlink_) {
1116 unlink(pipe_name_.c_str());
Nico 2010/12/10 18:48:07 Do you need to set must_link_ to false here? See c
dmac 2010/12/13 18:32:29 Done.
1117 }
1029 if (server_listen_pipe_ != -1) { 1118 if (server_listen_pipe_ != -1) {
1030 if (HANDLE_EINTR(close(server_listen_pipe_)) < 0) 1119 if (HANDLE_EINTR(close(server_listen_pipe_)) < 0)
1031 PLOG(ERROR) << "close " << server_listen_pipe_; 1120 PLOG(ERROR) << "close " << server_listen_pipe_;
1032 server_listen_pipe_ = -1; 1121 server_listen_pipe_ = -1;
1122 // Unregister libevent for the listening socket and close it.
1123 server_listen_connection_watcher_.StopWatchingFileDescriptor();
1033 } 1124 }
1034 1125
1035 // Unregister libevent for the FIFO and close it.
1036 read_watcher_.StopWatchingFileDescriptor();
1037 write_watcher_.StopWatchingFileDescriptor();
1038 if (pipe_ != -1) {
1039 if (HANDLE_EINTR(close(pipe_)) < 0)
1040 PLOG(ERROR) << "close " << pipe_;
1041 pipe_ = -1;
1042 }
1043 if (client_pipe_ != -1) { 1126 if (client_pipe_ != -1) {
1044 PipeMap::GetInstance()->RemoveAndClose(pipe_name_); 1127 PipeMap::GetInstance()->RemoveAndClose(pipe_name_);
1045 client_pipe_ = -1; 1128 client_pipe_ = -1;
1046 } 1129 }
1047 #if defined(IPC_USES_READWRITE)
1048 if (fd_pipe_ != -1) {
1049 if (HANDLE_EINTR(close(fd_pipe_)) < 0)
1050 PLOG(ERROR) << "close " << fd_pipe_;
1051 fd_pipe_ = -1;
1052 }
1053 if (remote_fd_pipe_ != -1) {
1054 if (HANDLE_EINTR(close(remote_fd_pipe_)) < 0)
1055 PLOG(ERROR) << "close " << remote_fd_pipe_;
1056 remote_fd_pipe_ = -1;
1057 }
1058 #endif
1059
1060 if (uses_fifo_) {
1061 // Unlink the FIFO
1062 unlink(pipe_name_.c_str());
1063 }
1064
1065 while (!output_queue_.empty()) {
1066 Message* m = output_queue_.front();
1067 output_queue_.pop();
1068 delete m;
1069 }
1070
1071 // Close any outstanding, received file descriptors
1072 for (std::vector<int>::iterator
1073 i = input_overflow_fds_.begin(); i != input_overflow_fds_.end(); ++i) {
1074 if (HANDLE_EINTR(close(*i)) < 0)
1075 PLOG(ERROR) << "close " << *i;
1076 }
1077 input_overflow_fds_.clear();
1078 } 1130 }
1079 1131
1080 //------------------------------------------------------------------------------ 1132 //------------------------------------------------------------------------------
1081 // Channel's methods simply call through to ChannelImpl. 1133 // Channel's methods simply call through to ChannelImpl.
1082 Channel::Channel(const IPC::ChannelHandle& channel_handle, Mode mode, 1134 Channel::Channel(const IPC::ChannelHandle& channel_handle, Mode mode,
1083 Listener* listener) 1135 Listener* listener)
1084 : channel_impl_(new ChannelImpl(channel_handle, mode, listener)) { 1136 : channel_impl_(new ChannelImpl(channel_handle, mode, listener)) {
1085 } 1137 }
1086 1138
1087 Channel::~Channel() { 1139 Channel::~Channel() {
(...skipping 13 matching lines...) Expand all
1101 } 1153 }
1102 1154
1103 bool Channel::Send(Message* message) { 1155 bool Channel::Send(Message* message) {
1104 return channel_impl_->Send(message); 1156 return channel_impl_->Send(message);
1105 } 1157 }
1106 1158
1107 int Channel::GetClientFileDescriptor() const { 1159 int Channel::GetClientFileDescriptor() const {
1108 return channel_impl_->GetClientFileDescriptor(); 1160 return channel_impl_->GetClientFileDescriptor();
1109 } 1161 }
1110 1162
1163 bool Channel::AcceptsConnections() const {
1164 return channel_impl_->AcceptsConnections();
1165 }
1166
1167 bool Channel::HasAcceptedConnection() const {
1168 return channel_impl_->HasAcceptedConnection();
1169 }
1170
1171 void Channel::ResetToAcceptingConnectionState() {
1172 channel_impl_->ResetToAcceptingConnectionState();
1173 }
1174
1111 } // namespace IPC 1175 } // namespace IPC
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698