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

Side by Side Diff: ipc/ipc_channel_posix.cc

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