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

Side by Side Diff: ipc/ipc_channel_posix.cc

Issue 155905: Separates ipc code from common (http://crbug.com/16829) (Closed)
Patch Set: Fixes reference to 'common_message_traits' it's actually 'common_param_traits' Created 11 years, 5 months 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
« no previous file with comments | « ipc/ipc_channel_posix.h ('k') | ipc/ipc_channel_proxy.h » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 // Copyright (c) 2008 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "ipc/ipc_channel_posix.h"
6
7 #include <errno.h>
8 #include <fcntl.h>
9 #include <stddef.h>
10 #include <sys/types.h>
11 #include <sys/socket.h>
12 #include <sys/stat.h>
13 #include <sys/un.h>
14
15 #include <string>
16 #include <map>
17
18 #include "base/command_line.h"
19 #include "base/eintr_wrapper.h"
20 #include "base/global_descriptors_posix.h"
21 #include "base/lock.h"
22 #include "base/logging.h"
23 #include "base/process_util.h"
24 #include "base/scoped_ptr.h"
25 #include "base/singleton.h"
26 #include "base/stats_counters.h"
27 #include "base/string_util.h"
28 #include "ipc/ipc_descriptors.h"
29 #include "ipc/ipc_switches.h"
30 #include "ipc/file_descriptor_set_posix.h"
31 #include "ipc/ipc_logging.h"
32 #include "ipc/ipc_message_utils.h"
33
34 namespace IPC {
35
36 // IPC channels on Windows use named pipes (CreateNamedPipe()) with
37 // channel ids as the pipe names. Channels on POSIX use anonymous
38 // Unix domain sockets created via socketpair() as pipes. These don't
39 // quite line up.
40 //
41 // When creating a child subprocess, the parent side of the fork
42 // arranges it such that the initial control channel ends up on the
43 // magic file descriptor kPrimaryIPCChannel in the child. Future
44 // connections (file descriptors) can then be passed via that
45 // connection via sendmsg().
46
47 //------------------------------------------------------------------------------
48 namespace {
49
50 // The PipeMap class works around this quirk related to unit tests:
51 //
52 // When running as a server, we install the client socket in a
53 // specific file descriptor number (@kPrimaryIPCChannel). However, we
54 // also have to support the case where we are running unittests in the
55 // same process. (We do not support forking without execing.)
56 //
57 // Case 1: normal running
58 // The IPC server object will install a mapping in PipeMap from the
59 // name which it was given to the client pipe. When forking the client, the
60 // GetClientFileDescriptorMapping will ensure that the socket is installed in
61 // the magic slot (@kPrimaryIPCChannel). The client will search for the
62 // mapping, but it won't find any since we are in a new process. Thus the
63 // magic fd number is returned. Once the client connects, the server will
64 // close its copy of the client socket and remove the mapping.
65 //
66 // Case 2: unittests - client and server in the same process
67 // The IPC server will install a mapping as before. The client will search
68 // for a mapping and find out. It duplicates the file descriptor and
69 // connects. Once the client connects, the server will close the original
70 // copy of the client socket and remove the mapping. Thus, when the client
71 // object closes, it will close the only remaining copy of the client socket
72 // in the fd table and the server will see EOF on its side.
73 //
74 // TODO(port): a client process cannot connect to multiple IPC channels with
75 // this scheme.
76
77 class PipeMap {
78 public:
79 // Lookup a given channel id. Return -1 if not found.
80 int Lookup(const std::string& channel_id) {
81 AutoLock locked(lock_);
82
83 ChannelToFDMap::const_iterator i = map_.find(channel_id);
84 if (i == map_.end())
85 return -1;
86 return i->second;
87 }
88
89 // Remove the mapping for the given channel id. No error is signaled if the
90 // channel_id doesn't exist
91 void RemoveAndClose(const std::string& channel_id) {
92 AutoLock locked(lock_);
93
94 ChannelToFDMap::iterator i = map_.find(channel_id);
95 if (i != map_.end()) {
96 HANDLE_EINTR(close(i->second));
97 map_.erase(i);
98 }
99 }
100
101 // Insert a mapping from @channel_id to @fd. It's a fatal error to insert a
102 // mapping if one already exists for the given channel_id
103 void Insert(const std::string& channel_id, int fd) {
104 AutoLock locked(lock_);
105 DCHECK(fd != -1);
106
107 ChannelToFDMap::const_iterator i = map_.find(channel_id);
108 CHECK(i == map_.end()) << "Creating second IPC server (fd " << fd << ") "
109 << "for '" << channel_id << "' while first "
110 << "(fd " << i->second << ") still exists";
111 map_[channel_id] = fd;
112 }
113
114 private:
115 Lock lock_;
116 typedef std::map<std::string, int> ChannelToFDMap;
117 ChannelToFDMap map_;
118 };
119
120 // Used to map a channel name to the equivalent FD # in the current process.
121 // Returns -1 if the channel is unknown.
122 int ChannelNameToFD(const std::string& channel_id) {
123 // See the large block comment above PipeMap for the reasoning here.
124 const int fd = Singleton<PipeMap>()->Lookup(channel_id);
125
126 if (fd != -1) {
127 int dup_fd = dup(fd);
128 if (dup_fd < 0)
129 LOG(FATAL) << "dup(" << fd << "): " << strerror(errno);
130 return dup_fd;
131 }
132
133 return fd;
134 }
135
136 //------------------------------------------------------------------------------
137 sockaddr_un sizecheck;
138 const size_t kMaxPipeNameLength = sizeof(sizecheck.sun_path);
139
140 // Creates a Fifo with the specified name ready to listen on.
141 bool CreateServerFifo(const std::string& pipe_name, int* server_listen_fd) {
142 DCHECK(server_listen_fd);
143 DCHECK_GT(pipe_name.length(), 0u);
144 DCHECK_LT(pipe_name.length(), kMaxPipeNameLength);
145
146 if (pipe_name.length() == 0 || pipe_name.length() >= kMaxPipeNameLength) {
147 return false;
148 }
149
150 // Create socket.
151 int fd = socket(AF_UNIX, SOCK_STREAM, 0);
152 if (fd < 0) {
153 return false;
154 }
155
156 // Make socket non-blocking
157 if (fcntl(fd, F_SETFL, O_NONBLOCK) == -1) {
158 HANDLE_EINTR(close(fd));
159 return false;
160 }
161
162 // Delete any old FS instances.
163 unlink(pipe_name.c_str());
164
165 // Create unix_addr structure
166 struct sockaddr_un unix_addr;
167 memset(&unix_addr, 0, sizeof(unix_addr));
168 unix_addr.sun_family = AF_UNIX;
169 snprintf(unix_addr.sun_path, kMaxPipeNameLength, "%s", pipe_name.c_str());
170 size_t unix_addr_len = offsetof(struct sockaddr_un, sun_path) +
171 strlen(unix_addr.sun_path) + 1;
172
173 // Bind the socket.
174 if (bind(fd, reinterpret_cast<const sockaddr*>(&unix_addr),
175 unix_addr_len) != 0) {
176 HANDLE_EINTR(close(fd));
177 return false;
178 }
179
180 // Start listening on the socket.
181 const int listen_queue_length = 1;
182 if (listen(fd, listen_queue_length) != 0) {
183 HANDLE_EINTR(close(fd));
184 return false;
185 }
186
187 *server_listen_fd = fd;
188 return true;
189 }
190
191 // Accept a connection on a fifo.
192 bool ServerAcceptFifoConnection(int server_listen_fd, int* server_socket) {
193 DCHECK(server_socket);
194
195 int accept_fd = HANDLE_EINTR(accept(server_listen_fd, NULL, 0));
196 if (accept_fd < 0)
197 return false;
198 if (fcntl(accept_fd, F_SETFL, O_NONBLOCK) == -1) {
199 HANDLE_EINTR(close(accept_fd));
200 return false;
201 }
202
203 *server_socket = accept_fd;
204 return true;
205 }
206
207 bool ClientConnectToFifo(const std::string &pipe_name, int* client_socket) {
208 DCHECK(client_socket);
209 DCHECK_LT(pipe_name.length(), kMaxPipeNameLength);
210
211 // Create socket.
212 int fd = socket(AF_UNIX, SOCK_STREAM, 0);
213 if (fd < 0) {
214 LOG(ERROR) << "fd is invalid";
215 return false;
216 }
217
218 // Make socket non-blocking
219 if (fcntl(fd, F_SETFL, O_NONBLOCK) == -1) {
220 LOG(ERROR) << "fcntl failed";
221 HANDLE_EINTR(close(fd));
222 return false;
223 }
224
225 // Create server side of socket.
226 struct sockaddr_un server_unix_addr;
227 memset(&server_unix_addr, 0, sizeof(server_unix_addr));
228 server_unix_addr.sun_family = AF_UNIX;
229 snprintf(server_unix_addr.sun_path, kMaxPipeNameLength, "%s",
230 pipe_name.c_str());
231 size_t server_unix_addr_len = offsetof(struct sockaddr_un, sun_path) +
232 strlen(server_unix_addr.sun_path) + 1;
233
234 if (HANDLE_EINTR(connect(fd, reinterpret_cast<sockaddr*>(&server_unix_addr),
235 server_unix_addr_len)) != 0) {
236 HANDLE_EINTR(close(fd));
237 return false;
238 }
239
240 *client_socket = fd;
241 return true;
242 }
243
244 } // namespace
245 //------------------------------------------------------------------------------
246
247 Channel::ChannelImpl::ChannelImpl(const std::string& channel_id, Mode mode,
248 Listener* listener)
249 : mode_(mode),
250 is_blocked_on_write_(false),
251 message_send_bytes_written_(0),
252 uses_fifo_(CommandLine::ForCurrentProcess()->HasSwitch(
253 switches::kIPCUseFIFO)),
254 server_listen_pipe_(-1),
255 pipe_(-1),
256 client_pipe_(-1),
257 listener_(listener),
258 waiting_connect_(true),
259 processing_incoming_(false),
260 factory_(this) {
261 if (!CreatePipe(channel_id, mode)) {
262 // The pipe may have been closed already.
263 LOG(WARNING) << "Unable to create pipe named \"" << channel_id <<
264 "\" in " << (mode == MODE_SERVER ? "server" : "client") <<
265 " mode error(" << strerror(errno) << ").";
266 }
267 }
268
269 // static
270 void AddChannelSocket(const std::string& name, int socket) {
271 Singleton<PipeMap>()->Insert(name, socket);
272 }
273
274 // static
275 void RemoveAndCloseChannelSocket(const std::string& name) {
276 Singleton<PipeMap>()->RemoveAndClose(name);
277 }
278
279 // static
280 bool SocketPair(int* fd1, int* fd2) {
281 int pipe_fds[2];
282 if (socketpair(AF_UNIX, SOCK_STREAM, 0, pipe_fds) != 0) {
283 LOG(ERROR) << "socketpair(): " << strerror(errno);
284 return false;
285 }
286
287 // Set both ends to be non-blocking.
288 if (fcntl(pipe_fds[0], F_SETFL, O_NONBLOCK) == -1 ||
289 fcntl(pipe_fds[1], F_SETFL, O_NONBLOCK) == -1) {
290 LOG(ERROR) << "fcntl(O_NONBLOCK): " << strerror(errno);
291 HANDLE_EINTR(close(pipe_fds[0]));
292 HANDLE_EINTR(close(pipe_fds[1]));
293 return false;
294 }
295
296 *fd1 = pipe_fds[0];
297 *fd2 = pipe_fds[1];
298
299 return true;
300 }
301
302 bool Channel::ChannelImpl::CreatePipe(const std::string& channel_id,
303 Mode mode) {
304 DCHECK(server_listen_pipe_ == -1 && pipe_ == -1);
305
306 if (uses_fifo_) {
307 // This only happens in unit tests; see the comment above PipeMap.
308 // TODO(playmobil): We shouldn't need to create fifos on disk.
309 // TODO(playmobil): If we do, they should be in the user data directory.
310 // TODO(playmobil): Cleanup any stale fifos.
311 pipe_name_ = "/var/tmp/chrome_" + channel_id;
312 if (mode == MODE_SERVER) {
313 if (!CreateServerFifo(pipe_name_, &server_listen_pipe_)) {
314 return false;
315 }
316 } else {
317 if (!ClientConnectToFifo(pipe_name_, &pipe_)) {
318 return false;
319 }
320 waiting_connect_ = false;
321 }
322 } else {
323 // This is the normal (non-unit-test) case, where we're using sockets.
324 // Three possible cases:
325 // 1) It's for a channel we already have a pipe for; reuse it.
326 // 2) It's the initial IPC channel:
327 // 2a) Server side: create the pipe.
328 // 2b) Client side: Pull the pipe out of the GlobalDescriptors set.
329 pipe_name_ = channel_id;
330 pipe_ = ChannelNameToFD(pipe_name_);
331 if (pipe_ < 0) {
332 // Initial IPC channel.
333 if (mode == MODE_SERVER) {
334 if (!SocketPair(&pipe_, &client_pipe_))
335 return false;
336 AddChannelSocket(pipe_name_, client_pipe_);
337 } else {
338 pipe_ = Singleton<base::GlobalDescriptors>()->Get(kPrimaryIPCChannel);
339 }
340 } else {
341 waiting_connect_ = false;
342 }
343 }
344
345 // Create the Hello message to be sent when Connect is called
346 scoped_ptr<Message> msg(new Message(MSG_ROUTING_NONE,
347 HELLO_MESSAGE_TYPE,
348 IPC::Message::PRIORITY_NORMAL));
349 if (!msg->WriteInt(base::GetCurrentProcId())) {
350 Close();
351 return false;
352 }
353
354 output_queue_.push(msg.release());
355 return true;
356 }
357
358 bool Channel::ChannelImpl::Connect() {
359 if (mode_ == MODE_SERVER && uses_fifo_) {
360 if (server_listen_pipe_ == -1) {
361 return false;
362 }
363 MessageLoopForIO::current()->WatchFileDescriptor(
364 server_listen_pipe_,
365 true,
366 MessageLoopForIO::WATCH_READ,
367 &server_listen_connection_watcher_,
368 this);
369 } else {
370 if (pipe_ == -1) {
371 return false;
372 }
373 MessageLoopForIO::current()->WatchFileDescriptor(
374 pipe_,
375 true,
376 MessageLoopForIO::WATCH_READ,
377 &read_watcher_,
378 this);
379 waiting_connect_ = false;
380 }
381
382 if (!waiting_connect_)
383 return ProcessOutgoingMessages();
384 return true;
385 }
386
387 bool Channel::ChannelImpl::ProcessIncomingMessages() {
388 ssize_t bytes_read = 0;
389
390 struct msghdr msg = {0};
391 struct iovec iov = {input_buf_, Channel::kReadBufferSize};
392
393 msg.msg_iov = &iov;
394 msg.msg_iovlen = 1;
395 msg.msg_control = input_cmsg_buf_;
396
397 for (;;) {
398 msg.msg_controllen = sizeof(input_cmsg_buf_);
399
400 if (bytes_read == 0) {
401 if (pipe_ == -1)
402 return false;
403
404 // Read from pipe.
405 // recvmsg() returns 0 if the connection has closed or EAGAIN if no data
406 // is waiting on the pipe.
407 bytes_read = HANDLE_EINTR(recvmsg(pipe_, &msg, MSG_DONTWAIT));
408
409 if (bytes_read < 0) {
410 if (errno == EAGAIN) {
411 return true;
412 #if defined(OS_MACOSX)
413 } else if (errno == EPERM) {
414 // On OSX, reading from a pipe with no listener returns EPERM
415 // treat this as a special case to prevent spurious error messages
416 // to the console.
417 return false;
418 #endif // defined(OS_MACOSX)
419 } else {
420 LOG(ERROR) << "pipe error (" << pipe_ << "): " << strerror(errno);
421 return false;
422 }
423 } else if (bytes_read == 0) {
424 // The pipe has closed...
425 Close();
426 return false;
427 }
428 }
429 DCHECK(bytes_read);
430
431 if (client_pipe_ != -1) {
432 Singleton<PipeMap>()->RemoveAndClose(pipe_name_);
433 client_pipe_ = -1;
434 }
435
436 // a pointer to an array of |num_wire_fds| file descriptors from the read
437 const int* wire_fds = NULL;
438 unsigned num_wire_fds = 0;
439
440 // walk the list of control messages and, if we find an array of file
441 // descriptors, save a pointer to the array
442
443 // This next if statement is to work around an OSX issue where
444 // CMSG_FIRSTHDR will return non-NULL in the case that controllen == 0.
445 // Here's a test case:
446 //
447 // int main() {
448 // struct msghdr msg;
449 // msg.msg_control = &msg;
450 // msg.msg_controllen = 0;
451 // if (CMSG_FIRSTHDR(&msg))
452 // printf("Bug found!\n");
453 // }
454 if (msg.msg_controllen > 0) {
455 // On OSX, CMSG_FIRSTHDR doesn't handle the case where controllen is 0
456 // and will return a pointer into nowhere.
457 for (struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg); cmsg;
458 cmsg = CMSG_NXTHDR(&msg, cmsg)) {
459 if (cmsg->cmsg_level == SOL_SOCKET &&
460 cmsg->cmsg_type == SCM_RIGHTS) {
461 const unsigned payload_len = cmsg->cmsg_len - CMSG_LEN(0);
462 DCHECK(payload_len % sizeof(int) == 0);
463 wire_fds = reinterpret_cast<int*>(CMSG_DATA(cmsg));
464 num_wire_fds = payload_len / 4;
465
466 if (msg.msg_flags & MSG_CTRUNC) {
467 LOG(ERROR) << "SCM_RIGHTS message was truncated"
468 << " cmsg_len:" << cmsg->cmsg_len
469 << " fd:" << pipe_;
470 for (unsigned i = 0; i < num_wire_fds; ++i)
471 HANDLE_EINTR(close(wire_fds[i]));
472 return false;
473 }
474 break;
475 }
476 }
477 }
478
479 // Process messages from input buffer.
480 const char *p;
481 const char *end;
482 if (input_overflow_buf_.empty()) {
483 p = input_buf_;
484 end = p + bytes_read;
485 } else {
486 if (input_overflow_buf_.size() >
487 static_cast<size_t>(kMaximumMessageSize - bytes_read)) {
488 input_overflow_buf_.clear();
489 LOG(ERROR) << "IPC message is too big";
490 return false;
491 }
492 input_overflow_buf_.append(input_buf_, bytes_read);
493 p = input_overflow_buf_.data();
494 end = p + input_overflow_buf_.size();
495 }
496
497 // A pointer to an array of |num_fds| file descriptors which includes any
498 // fds that have spilled over from a previous read.
499 const int* fds;
500 unsigned num_fds;
501 unsigned fds_i = 0; // the index of the first unused descriptor
502
503 if (input_overflow_fds_.empty()) {
504 fds = wire_fds;
505 num_fds = num_wire_fds;
506 } else {
507 const size_t prev_size = input_overflow_fds_.size();
508 input_overflow_fds_.resize(prev_size + num_wire_fds);
509 memcpy(&input_overflow_fds_[prev_size], wire_fds,
510 num_wire_fds * sizeof(int));
511 fds = &input_overflow_fds_[0];
512 num_fds = input_overflow_fds_.size();
513 }
514
515 while (p < end) {
516 const char* message_tail = Message::FindNext(p, end);
517 if (message_tail) {
518 int len = static_cast<int>(message_tail - p);
519 Message m(p, len);
520 if (m.header()->num_fds) {
521 // the message has file descriptors
522 const char* error = NULL;
523 if (m.header()->num_fds > num_fds - fds_i) {
524 // the message has been completely received, but we didn't get
525 // enough file descriptors.
526 error = "Message needs unreceived descriptors";
527 }
528
529 if (m.header()->num_fds >
530 FileDescriptorSet::MAX_DESCRIPTORS_PER_MESSAGE) {
531 // There are too many descriptors in this message
532 error = "Message requires an excessive number of descriptors";
533 }
534
535 if (error) {
536 LOG(WARNING) << error
537 << " channel:" << this
538 << " message-type:" << m.type()
539 << " header()->num_fds:" << m.header()->num_fds
540 << " num_fds:" << num_fds
541 << " fds_i:" << fds_i;
542 // close the existing file descriptors so that we don't leak them
543 for (unsigned i = fds_i; i < num_fds; ++i)
544 HANDLE_EINTR(close(fds[i]));
545 input_overflow_fds_.clear();
546 // abort the connection
547 return false;
548 }
549
550 m.file_descriptor_set()->SetDescriptors(
551 &fds[fds_i], m.header()->num_fds);
552 fds_i += m.header()->num_fds;
553 }
554 #ifdef IPC_MESSAGE_DEBUG_EXTRA
555 DLOG(INFO) << "received message on channel @" << this <<
556 " with type " << m.type();
557 #endif
558 if (m.routing_id() == MSG_ROUTING_NONE &&
559 m.type() == HELLO_MESSAGE_TYPE) {
560 // The Hello message contains only the process id.
561 listener_->OnChannelConnected(MessageIterator(m).NextInt());
562 } else {
563 listener_->OnMessageReceived(m);
564 }
565 p = message_tail;
566 } else {
567 // Last message is partial.
568 break;
569 }
570 }
571 input_overflow_buf_.assign(p, end - p);
572 input_overflow_fds_ = std::vector<int>(&fds[fds_i], &fds[num_fds]);
573
574 // When the input data buffer is empty, the overflow fds should be too. If
575 // this is not the case, we probably have a rogue renderer which is trying
576 // to fill our descriptor table.
577 if (input_overflow_buf_.empty() && !input_overflow_fds_.empty()) {
578 // We close these descriptors in Close()
579 return false;
580 }
581
582 bytes_read = 0; // Get more data.
583 }
584
585 return true;
586 }
587
588 bool Channel::ChannelImpl::ProcessOutgoingMessages() {
589 DCHECK(!waiting_connect_); // Why are we trying to send messages if there's
590 // no connection?
591 is_blocked_on_write_ = false;
592
593 if (output_queue_.empty())
594 return true;
595
596 if (pipe_ == -1)
597 return false;
598
599 // Write out all the messages we can till the write blocks or there are no
600 // more outgoing messages.
601 while (!output_queue_.empty()) {
602 Message* msg = output_queue_.front();
603
604 size_t amt_to_write = msg->size() - message_send_bytes_written_;
605 DCHECK(amt_to_write != 0);
606 const char *out_bytes = reinterpret_cast<const char*>(msg->data()) +
607 message_send_bytes_written_;
608
609 struct msghdr msgh = {0};
610 struct iovec iov = {const_cast<char*>(out_bytes), amt_to_write};
611 msgh.msg_iov = &iov;
612 msgh.msg_iovlen = 1;
613 char buf[CMSG_SPACE(
614 sizeof(int[FileDescriptorSet::MAX_DESCRIPTORS_PER_MESSAGE]))];
615
616 if (message_send_bytes_written_ == 0 &&
617 !msg->file_descriptor_set()->empty()) {
618 // This is the first chunk of a message which has descriptors to send
619 struct cmsghdr *cmsg;
620 const unsigned num_fds = msg->file_descriptor_set()->size();
621
622 DCHECK_LE(num_fds, FileDescriptorSet::MAX_DESCRIPTORS_PER_MESSAGE);
623
624 msgh.msg_control = buf;
625 msgh.msg_controllen = CMSG_SPACE(sizeof(int) * num_fds);
626 cmsg = CMSG_FIRSTHDR(&msgh);
627 cmsg->cmsg_level = SOL_SOCKET;
628 cmsg->cmsg_type = SCM_RIGHTS;
629 cmsg->cmsg_len = CMSG_LEN(sizeof(int) * num_fds);
630 msg->file_descriptor_set()->GetDescriptors(
631 reinterpret_cast<int*>(CMSG_DATA(cmsg)));
632 msgh.msg_controllen = cmsg->cmsg_len;
633
634 msg->header()->num_fds = num_fds;
635 }
636
637 ssize_t bytes_written = HANDLE_EINTR(sendmsg(pipe_, &msgh, MSG_DONTWAIT));
638 if (bytes_written > 0)
639 msg->file_descriptor_set()->CommitAll();
640
641 if (bytes_written < 0 && errno != EAGAIN) {
642 #if defined(OS_MACOSX)
643 // On OSX writing to a pipe with no listener returns EPERM.
644 if (errno == EPERM) {
645 Close();
646 return false;
647 }
648 #endif // OS_MACOSX
649 LOG(ERROR) << "pipe error on " << pipe_ << ": " << strerror(errno);
650 return false;
651 }
652
653 if (static_cast<size_t>(bytes_written) != amt_to_write) {
654 if (bytes_written > 0) {
655 // If write() fails with EAGAIN then bytes_written will be -1.
656 message_send_bytes_written_ += bytes_written;
657 }
658
659 // Tell libevent to call us back once things are unblocked.
660 is_blocked_on_write_ = true;
661 MessageLoopForIO::current()->WatchFileDescriptor(
662 pipe_,
663 false, // One shot
664 MessageLoopForIO::WATCH_WRITE,
665 &write_watcher_,
666 this);
667 return true;
668 } else {
669 message_send_bytes_written_ = 0;
670
671 // Message sent OK!
672 #ifdef IPC_MESSAGE_DEBUG_EXTRA
673 DLOG(INFO) << "sent message @" << msg << " on channel @" << this <<
674 " with type " << msg->type();
675 #endif
676 output_queue_.pop();
677 delete msg;
678 }
679 }
680 return true;
681 }
682
683 bool Channel::ChannelImpl::Send(Message* message) {
684 #ifdef IPC_MESSAGE_DEBUG_EXTRA
685 DLOG(INFO) << "sending message @" << message << " on channel @" << this
686 << " with type " << message->type()
687 << " (" << output_queue_.size() << " in queue)";
688 #endif
689
690 #ifdef IPC_MESSAGE_LOG_ENABLED
691 Logging::current()->OnSendMessage(message, "");
692 #endif
693
694 output_queue_.push(message);
695 if (!waiting_connect_) {
696 if (!is_blocked_on_write_) {
697 if (!ProcessOutgoingMessages())
698 return false;
699 }
700 }
701
702 return true;
703 }
704
705 int Channel::ChannelImpl::GetClientFileDescriptor() const {
706 return client_pipe_;
707 }
708
709 // Called by libevent when we can read from th pipe without blocking.
710 void Channel::ChannelImpl::OnFileCanReadWithoutBlocking(int fd) {
711 bool send_server_hello_msg = false;
712 if (waiting_connect_ && mode_ == MODE_SERVER) {
713 // In the case of a socketpair() the server starts listening on its end
714 // of the pipe in Connect().
715 DCHECK(uses_fifo_);
716
717 if (!ServerAcceptFifoConnection(server_listen_pipe_, &pipe_)) {
718 Close();
719 }
720
721 // No need to watch the listening socket any longer since only one client
722 // can connect. So unregister with libevent.
723 server_listen_connection_watcher_.StopWatchingFileDescriptor();
724
725 // Start watching our end of the socket.
726 MessageLoopForIO::current()->WatchFileDescriptor(
727 pipe_,
728 true,
729 MessageLoopForIO::WATCH_READ,
730 &read_watcher_,
731 this);
732
733 waiting_connect_ = false;
734 send_server_hello_msg = true;
735 }
736
737 if (!waiting_connect_ && fd == pipe_) {
738 if (!ProcessIncomingMessages()) {
739 Close();
740 listener_->OnChannelError();
741 }
742 }
743
744 // If we're a server and handshaking, then we want to make sure that we
745 // only send our handshake message after we've processed the client's.
746 // This gives us a chance to kill the client if the incoming handshake
747 // is invalid.
748 if (send_server_hello_msg) {
749 // This should be our first write so there's no chance we can block here...
750 DCHECK(is_blocked_on_write_ == false);
751 ProcessOutgoingMessages();
752 }
753 }
754
755 // Called by libevent when we can write to the pipe without blocking.
756 void Channel::ChannelImpl::OnFileCanWriteWithoutBlocking(int fd) {
757 if (!ProcessOutgoingMessages()) {
758 Close();
759 listener_->OnChannelError();
760 }
761 }
762
763 void Channel::ChannelImpl::Close() {
764 // Close can be called multiple time, so we need to make sure we're
765 // idempotent.
766
767 // Unregister libevent for the listening socket and close it.
768 server_listen_connection_watcher_.StopWatchingFileDescriptor();
769
770 if (server_listen_pipe_ != -1) {
771 HANDLE_EINTR(close(server_listen_pipe_));
772 server_listen_pipe_ = -1;
773 }
774
775 // Unregister libevent for the FIFO and close it.
776 read_watcher_.StopWatchingFileDescriptor();
777 write_watcher_.StopWatchingFileDescriptor();
778 if (pipe_ != -1) {
779 HANDLE_EINTR(close(pipe_));
780 pipe_ = -1;
781 }
782 if (client_pipe_ != -1) {
783 Singleton<PipeMap>()->RemoveAndClose(pipe_name_);
784 client_pipe_ = -1;
785 }
786
787 if (uses_fifo_) {
788 // Unlink the FIFO
789 unlink(pipe_name_.c_str());
790 }
791
792 while (!output_queue_.empty()) {
793 Message* m = output_queue_.front();
794 output_queue_.pop();
795 delete m;
796 }
797
798 // Close any outstanding, received file descriptors
799 for (std::vector<int>::iterator
800 i = input_overflow_fds_.begin(); i != input_overflow_fds_.end(); ++i) {
801 HANDLE_EINTR(close(*i));
802 }
803 input_overflow_fds_.clear();
804 }
805
806 //------------------------------------------------------------------------------
807 // Channel's methods simply call through to ChannelImpl.
808 Channel::Channel(const std::string& channel_id, Mode mode,
809 Listener* listener)
810 : channel_impl_(new ChannelImpl(channel_id, mode, listener)) {
811 }
812
813 Channel::~Channel() {
814 delete channel_impl_;
815 }
816
817 bool Channel::Connect() {
818 return channel_impl_->Connect();
819 }
820
821 void Channel::Close() {
822 channel_impl_->Close();
823 }
824
825 void Channel::set_listener(Listener* listener) {
826 channel_impl_->set_listener(listener);
827 }
828
829 bool Channel::Send(Message* message) {
830 return channel_impl_->Send(message);
831 }
832
833 int Channel::GetClientFileDescriptor() const {
834 return channel_impl_->GetClientFileDescriptor();
835 }
836
837 } // namespace IPC
OLDNEW
« no previous file with comments | « ipc/ipc_channel_posix.h ('k') | ipc/ipc_channel_proxy.h » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698