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

Side by Side Diff: ipc/ipc_channel_posix.cc

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