Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / ipc / ipc_channel_posix.cc
1 // Copyright (c) 2012 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/socket.h>
11 #include <sys/stat.h>
12 #include <sys/types.h>
13 #include <unistd.h>
14
15 #if defined(OS_OPENBSD)
16 #include <sys/uio.h>
17 #endif
18
19 #if !defined(OS_NACL_NONSFI)
20 #include <sys/un.h>
21 #endif
22
23 #include <map>
24 #include <string>
25
26 #include "base/command_line.h"
27 #include "base/files/file_path.h"
28 #include "base/files/file_util.h"
29 #include "base/location.h"
30 #include "base/logging.h"
31 #include "base/memory/scoped_ptr.h"
32 #include "base/memory/singleton.h"
33 #include "base/posix/eintr_wrapper.h"
34 #include "base/posix/global_descriptors.h"
35 #include "base/process/process_handle.h"
36 #include "base/rand_util.h"
37 #include "base/stl_util.h"
38 #include "base/strings/string_util.h"
39 #include "base/synchronization/lock.h"
40 #include "ipc/file_descriptor_set_posix.h"
41 #include "ipc/ipc_descriptors.h"
42 #include "ipc/ipc_listener.h"
43 #include "ipc/ipc_logging.h"
44 #include "ipc/ipc_message_utils.h"
45 #include "ipc/ipc_switches.h"
46 #include "ipc/unix_domain_socket_util.h"
47
48 namespace IPC {
49
50 // IPC channels on Windows use named pipes (CreateNamedPipe()) with
51 // channel ids as the pipe names.  Channels on POSIX use sockets as
52 // pipes  These don't quite line up.
53 //
54 // When creating a child subprocess we use a socket pair and the parent side of
55 // the fork arranges it such that the initial control channel ends up on the
56 // magic file descriptor kPrimaryIPCChannel in the child.  Future
57 // connections (file descriptors) can then be passed via that
58 // connection via sendmsg().
59 //
60 // A POSIX IPC channel can also be set up as a server for a bound UNIX domain
61 // socket, and will handle multiple connect and disconnect sequences.  Currently
62 // it is limited to one connection at a time.
63
64 //------------------------------------------------------------------------------
65 namespace {
66
67 // The PipeMap class works around this quirk related to unit tests:
68 //
69 // When running as a server, we install the client socket in a
70 // specific file descriptor number (@kPrimaryIPCChannel). However, we
71 // also have to support the case where we are running unittests in the
72 // same process.  (We do not support forking without execing.)
73 //
74 // Case 1: normal running
75 //   The IPC server object will install a mapping in PipeMap from the
76 //   name which it was given to the client pipe. When forking the client, the
77 //   GetClientFileDescriptorMapping will ensure that the socket is installed in
78 //   the magic slot (@kPrimaryIPCChannel). The client will search for the
79 //   mapping, but it won't find any since we are in a new process. Thus the
80 //   magic fd number is returned. Once the client connects, the server will
81 //   close its copy of the client socket and remove the mapping.
82 //
83 // Case 2: unittests - client and server in the same process
84 //   The IPC server will install a mapping as before. The client will search
85 //   for a mapping and find out. It duplicates the file descriptor and
86 //   connects. Once the client connects, the server will close the original
87 //   copy of the client socket and remove the mapping. Thus, when the client
88 //   object closes, it will close the only remaining copy of the client socket
89 //   in the fd table and the server will see EOF on its side.
90 //
91 // TODO(port): a client process cannot connect to multiple IPC channels with
92 // this scheme.
93
94 class PipeMap {
95  public:
96   static PipeMap* GetInstance() {
97     return Singleton<PipeMap>::get();
98   }
99
100   ~PipeMap() {
101     // Shouldn't have left over pipes.
102     DCHECK(map_.empty());
103   }
104
105   // Lookup a given channel id. Return -1 if not found.
106   int Lookup(const std::string& channel_id) {
107     base::AutoLock locked(lock_);
108
109     ChannelToFDMap::const_iterator i = map_.find(channel_id);
110     if (i == map_.end())
111       return -1;
112     return i->second;
113   }
114
115   // Remove the mapping for the given channel id. No error is signaled if the
116   // channel_id doesn't exist
117   void Remove(const std::string& channel_id) {
118     base::AutoLock locked(lock_);
119     map_.erase(channel_id);
120   }
121
122   // Insert a mapping from @channel_id to @fd. It's a fatal error to insert a
123   // mapping if one already exists for the given channel_id
124   void Insert(const std::string& channel_id, int fd) {
125     base::AutoLock locked(lock_);
126     DCHECK_NE(-1, fd);
127
128     ChannelToFDMap::const_iterator i = map_.find(channel_id);
129     CHECK(i == map_.end()) << "Creating second IPC server (fd " << fd << ") "
130                            << "for '" << channel_id << "' while first "
131                            << "(fd " << i->second << ") still exists";
132     map_[channel_id] = fd;
133   }
134
135  private:
136   base::Lock lock_;
137   typedef std::map<std::string, int> ChannelToFDMap;
138   ChannelToFDMap map_;
139
140   friend struct DefaultSingletonTraits<PipeMap>;
141 #if defined(OS_ANDROID)
142   friend void ::IPC::Channel::NotifyProcessForkedForTesting();
143 #endif
144 };
145
146 //------------------------------------------------------------------------------
147
148 bool SocketWriteErrorIsRecoverable() {
149 #if defined(OS_MACOSX)
150   // On OS X if sendmsg() is trying to send fds between processes and there
151   // isn't enough room in the output buffer to send the fd structure over
152   // atomically then EMSGSIZE is returned.
153   //
154   // EMSGSIZE presents a problem since the system APIs can only call us when
155   // there's room in the socket buffer and not when there is "enough" room.
156   //
157   // The current behavior is to return to the event loop when EMSGSIZE is
158   // received and hopefull service another FD.  This is however still
159   // technically a busy wait since the event loop will call us right back until
160   // the receiver has read enough data to allow passing the FD over atomically.
161   return errno == EAGAIN || errno == EMSGSIZE;
162 #else
163   return errno == EAGAIN;
164 #endif  // OS_MACOSX
165 }
166
167 }  // namespace
168
169 #if defined(OS_ANDROID)
170 // When we fork for simple tests on Android, we can't 'exec', so we need to
171 // reset these entries manually to get the expected testing behavior.
172 void Channel::NotifyProcessForkedForTesting() {
173   PipeMap::GetInstance()->map_.clear();
174 }
175 #endif
176
177 //------------------------------------------------------------------------------
178
179 #if defined(OS_LINUX)
180 int ChannelPosix::global_pid_ = 0;
181 #endif  // OS_LINUX
182
183 ChannelPosix::ChannelPosix(const IPC::ChannelHandle& channel_handle,
184                            Mode mode, Listener* listener)
185     : ChannelReader(listener),
186       mode_(mode),
187       peer_pid_(base::kNullProcessId),
188       is_blocked_on_write_(false),
189       waiting_connect_(true),
190       message_send_bytes_written_(0),
191       pipe_name_(channel_handle.name),
192       must_unlink_(false) {
193   memset(input_cmsg_buf_, 0, sizeof(input_cmsg_buf_));
194   if (!CreatePipe(channel_handle)) {
195     // The pipe may have been closed already.
196     const char *modestr = (mode_ & MODE_SERVER_FLAG) ? "server" : "client";
197     LOG(WARNING) << "Unable to create pipe named \"" << channel_handle.name
198                  << "\" in " << modestr << " mode";
199   }
200 }
201
202 ChannelPosix::~ChannelPosix() {
203   Close();
204 }
205
206 bool SocketPair(int* fd1, int* fd2) {
207   int pipe_fds[2];
208   if (socketpair(AF_UNIX, SOCK_STREAM, 0, pipe_fds) != 0) {
209     PLOG(ERROR) << "socketpair()";
210     return false;
211   }
212
213   // Set both ends to be non-blocking.
214   if (fcntl(pipe_fds[0], F_SETFL, O_NONBLOCK) == -1 ||
215       fcntl(pipe_fds[1], F_SETFL, O_NONBLOCK) == -1) {
216     PLOG(ERROR) << "fcntl(O_NONBLOCK)";
217     if (IGNORE_EINTR(close(pipe_fds[0])) < 0)
218       PLOG(ERROR) << "close";
219     if (IGNORE_EINTR(close(pipe_fds[1])) < 0)
220       PLOG(ERROR) << "close";
221     return false;
222   }
223
224   *fd1 = pipe_fds[0];
225   *fd2 = pipe_fds[1];
226
227   return true;
228 }
229
230 bool ChannelPosix::CreatePipe(
231     const IPC::ChannelHandle& channel_handle) {
232   DCHECK(!server_listen_pipe_.is_valid() && !pipe_.is_valid());
233
234   // Four possible cases:
235   // 1) It's a channel wrapping a pipe that is given to us.
236   // 2) It's for a named channel, so we create it.
237   // 3) It's for a client that we implement ourself. This is used
238   //    in single-process unittesting.
239   // 4) It's the initial IPC channel:
240   //   4a) Client side: Pull the pipe out of the GlobalDescriptors set.
241   //   4b) Server side: create the pipe.
242
243   base::ScopedFD local_pipe;
244   if (channel_handle.socket.fd != -1) {
245     // Case 1 from comment above.
246     local_pipe.reset(channel_handle.socket.fd);
247 #if defined(IPC_USES_READWRITE)
248     // Test the socket passed into us to make sure it is nonblocking.
249     // We don't want to call read/write on a blocking socket.
250     int value = fcntl(local_pipe.get(), F_GETFL);
251     if (value == -1) {
252       PLOG(ERROR) << "fcntl(F_GETFL) " << pipe_name_;
253       return false;
254     }
255     if (!(value & O_NONBLOCK)) {
256       LOG(ERROR) << "Socket " << pipe_name_ << " must be O_NONBLOCK";
257       return false;
258     }
259 #endif   // IPC_USES_READWRITE
260   } else if (mode_ & MODE_NAMED_FLAG) {
261 #if defined(OS_NACL_NONSFI)
262     LOG(FATAL)
263         << "IPC channels in nacl_helper_nonsfi should not be in NAMED mode.";
264 #else
265     // Case 2 from comment above.
266     int local_pipe_fd = -1;
267
268     if (mode_ & MODE_SERVER_FLAG) {
269       if (!CreateServerUnixDomainSocket(base::FilePath(pipe_name_),
270                                         &local_pipe_fd)) {
271         return false;
272       }
273
274       must_unlink_ = true;
275     } else if (mode_ & MODE_CLIENT_FLAG) {
276       if (!CreateClientUnixDomainSocket(base::FilePath(pipe_name_),
277                                         &local_pipe_fd)) {
278         return false;
279       }
280     } else {
281       LOG(ERROR) << "Bad mode: " << mode_;
282       return false;
283     }
284
285     local_pipe.reset(local_pipe_fd);
286 #endif  // !defined(OS_NACL_NONSFI)
287   } else {
288     local_pipe.reset(PipeMap::GetInstance()->Lookup(pipe_name_));
289     if (mode_ & MODE_CLIENT_FLAG) {
290       if (local_pipe.is_valid()) {
291         // Case 3 from comment above.
292         // We only allow one connection.
293         local_pipe.reset(HANDLE_EINTR(dup(local_pipe.release())));
294         PipeMap::GetInstance()->Remove(pipe_name_);
295       } else {
296         // Case 4a from comment above.
297         // Guard against inappropriate reuse of the initial IPC channel.  If
298         // an IPC channel closes and someone attempts to reuse it by name, the
299         // initial channel must not be recycled here.  http://crbug.com/26754.
300         static bool used_initial_channel = false;
301         if (used_initial_channel) {
302           LOG(FATAL) << "Denying attempt to reuse initial IPC channel for "
303                      << pipe_name_;
304           return false;
305         }
306         used_initial_channel = true;
307
308         local_pipe.reset(
309             base::GlobalDescriptors::GetInstance()->Get(kPrimaryIPCChannel));
310       }
311     } else if (mode_ & MODE_SERVER_FLAG) {
312       // Case 4b from comment above.
313       if (local_pipe.is_valid()) {
314         LOG(ERROR) << "Server already exists for " << pipe_name_;
315         // This is a client side pipe registered by other server and
316         // shouldn't be closed.
317         ignore_result(local_pipe.release());
318         return false;
319       }
320       base::AutoLock lock(client_pipe_lock_);
321       int local_pipe_fd = -1, client_pipe_fd = -1;
322       if (!SocketPair(&local_pipe_fd, &client_pipe_fd))
323         return false;
324       local_pipe.reset(local_pipe_fd);
325       client_pipe_.reset(client_pipe_fd);
326       PipeMap::GetInstance()->Insert(pipe_name_, client_pipe_fd);
327     } else {
328       LOG(ERROR) << "Bad mode: " << mode_;
329       return false;
330     }
331   }
332
333 #if defined(IPC_USES_READWRITE)
334   // Create a dedicated socketpair() for exchanging file descriptors.
335   // See comments for IPC_USES_READWRITE for details.
336   if (mode_ & MODE_CLIENT_FLAG) {
337     int fd_pipe_fd = 1, remote_fd_pipe_fd = -1;
338     if (!SocketPair(&fd_pipe_fd, &remote_fd_pipe_fd)) {
339       return false;
340     }
341
342     fd_pipe_.reset(fd_pipe_fd);
343     remote_fd_pipe_.reset(remote_fd_pipe_fd);
344   }
345 #endif  // IPC_USES_READWRITE
346
347   if ((mode_ & MODE_SERVER_FLAG) && (mode_ & MODE_NAMED_FLAG)) {
348 #if defined(OS_NACL_NONSFI)
349     LOG(FATAL) << "IPC channels in nacl_helper_nonsfi "
350                << "should not be in NAMED or SERVER mode.";
351 #else
352     server_listen_pipe_.reset(local_pipe.release());
353 #endif
354   } else {
355     pipe_.reset(local_pipe.release());
356   }
357   return true;
358 }
359
360 bool ChannelPosix::Connect() {
361   if (!server_listen_pipe_.is_valid() && !pipe_.is_valid()) {
362     DLOG(WARNING) << "Channel creation failed: " << pipe_name_;
363     return false;
364   }
365
366   bool did_connect = true;
367   if (server_listen_pipe_.is_valid()) {
368 #if defined(OS_NACL_NONSFI)
369     LOG(FATAL) << "IPC channels in nacl_helper_nonsfi "
370                << "should always be in client mode.";
371 #else
372     // Watch the pipe for connections, and turn any connections into
373     // active sockets.
374     base::MessageLoopForIO::current()->WatchFileDescriptor(
375         server_listen_pipe_.get(),
376         true,
377         base::MessageLoopForIO::WATCH_READ,
378         &server_listen_connection_watcher_,
379         this);
380 #endif
381   } else {
382     did_connect = AcceptConnection();
383   }
384   return did_connect;
385 }
386
387 void ChannelPosix::CloseFileDescriptors(Message* msg) {
388 #if defined(OS_MACOSX)
389   // There is a bug on OSX which makes it dangerous to close
390   // a file descriptor while it is in transit. So instead we
391   // store the file descriptor in a set and send a message to
392   // the recipient, which is queued AFTER the message that
393   // sent the FD. The recipient will reply to the message,
394   // letting us know that it is now safe to close the file
395   // descriptor. For more information, see:
396   // http://crbug.com/298276
397   std::vector<int> to_close;
398   msg->file_descriptor_set()->ReleaseFDsToClose(&to_close);
399   for (size_t i = 0; i < to_close.size(); i++) {
400     fds_to_close_.insert(to_close[i]);
401     QueueCloseFDMessage(to_close[i], 2);
402   }
403 #else
404   msg->file_descriptor_set()->CommitAll();
405 #endif
406 }
407
408 bool ChannelPosix::ProcessOutgoingMessages() {
409   DCHECK(!waiting_connect_);  // Why are we trying to send messages if there's
410                               // no connection?
411   if (output_queue_.empty())
412     return true;
413
414   if (!pipe_.is_valid())
415     return false;
416
417   // Write out all the messages we can till the write blocks or there are no
418   // more outgoing messages.
419   while (!output_queue_.empty()) {
420     Message* msg = output_queue_.front();
421
422     size_t amt_to_write = msg->size() - message_send_bytes_written_;
423     DCHECK_NE(0U, amt_to_write);
424     const char* out_bytes = reinterpret_cast<const char*>(msg->data()) +
425         message_send_bytes_written_;
426
427     struct msghdr msgh = {0};
428     struct iovec iov = {const_cast<char*>(out_bytes), amt_to_write};
429     msgh.msg_iov = &iov;
430     msgh.msg_iovlen = 1;
431     char buf[CMSG_SPACE(
432         sizeof(int) * FileDescriptorSet::kMaxDescriptorsPerMessage)];
433
434     ssize_t bytes_written = 1;
435     int fd_written = -1;
436
437     if (message_send_bytes_written_ == 0 &&
438         !msg->file_descriptor_set()->empty()) {
439       // This is the first chunk of a message which has descriptors to send
440       struct cmsghdr *cmsg;
441       const unsigned num_fds = msg->file_descriptor_set()->size();
442
443       DCHECK(num_fds <= FileDescriptorSet::kMaxDescriptorsPerMessage);
444       if (msg->file_descriptor_set()->ContainsDirectoryDescriptor()) {
445         LOG(FATAL) << "Panic: attempting to transport directory descriptor over"
446                       " IPC. Aborting to maintain sandbox isolation.";
447         // If you have hit this then something tried to send a file descriptor
448         // to a directory over an IPC channel. Since IPC channels span
449         // sandboxes this is very bad: the receiving process can use openat
450         // with ".." elements in the path in order to reach the real
451         // filesystem.
452       }
453
454       msgh.msg_control = buf;
455       msgh.msg_controllen = CMSG_SPACE(sizeof(int) * num_fds);
456       cmsg = CMSG_FIRSTHDR(&msgh);
457       cmsg->cmsg_level = SOL_SOCKET;
458       cmsg->cmsg_type = SCM_RIGHTS;
459       cmsg->cmsg_len = CMSG_LEN(sizeof(int) * num_fds);
460       msg->file_descriptor_set()->PeekDescriptors(
461           reinterpret_cast<int*>(CMSG_DATA(cmsg)));
462       msgh.msg_controllen = cmsg->cmsg_len;
463
464       // DCHECK_LE above already checks that
465       // num_fds < kMaxDescriptorsPerMessage so no danger of overflow.
466       msg->header()->num_fds = static_cast<uint16>(num_fds);
467
468 #if defined(IPC_USES_READWRITE)
469       if (!IsHelloMessage(*msg)) {
470         // Only the Hello message sends the file descriptor with the message.
471         // Subsequently, we can send file descriptors on the dedicated
472         // fd_pipe_ which makes Seccomp sandbox operation more efficient.
473         struct iovec fd_pipe_iov = { const_cast<char *>(""), 1 };
474         msgh.msg_iov = &fd_pipe_iov;
475         fd_written = fd_pipe_.get();
476         bytes_written =
477             HANDLE_EINTR(sendmsg(fd_pipe_.get(), &msgh, MSG_DONTWAIT));
478         msgh.msg_iov = &iov;
479         msgh.msg_controllen = 0;
480         if (bytes_written > 0) {
481           CloseFileDescriptors(msg);
482         }
483       }
484 #endif  // IPC_USES_READWRITE
485     }
486
487     if (bytes_written == 1) {
488       fd_written = pipe_.get();
489 #if defined(IPC_USES_READWRITE)
490       if ((mode_ & MODE_CLIENT_FLAG) && IsHelloMessage(*msg)) {
491         DCHECK_EQ(msg->file_descriptor_set()->size(), 1U);
492       }
493       if (!msgh.msg_controllen) {
494         bytes_written =
495             HANDLE_EINTR(write(pipe_.get(), out_bytes, amt_to_write));
496       } else
497 #endif  // IPC_USES_READWRITE
498       {
499         bytes_written = HANDLE_EINTR(sendmsg(pipe_.get(), &msgh, MSG_DONTWAIT));
500       }
501     }
502     if (bytes_written > 0)
503       CloseFileDescriptors(msg);
504
505     if (bytes_written < 0 && !SocketWriteErrorIsRecoverable()) {
506       // We can't close the pipe here, because calling OnChannelError
507       // may destroy this object, and that would be bad if we are
508       // called from Send(). Instead, we return false and hope the
509       // caller will close the pipe. If they do not, the pipe will
510       // still be closed next time OnFileCanReadWithoutBlocking is
511       // called.
512 #if defined(OS_MACOSX)
513       // On OSX writing to a pipe with no listener returns EPERM.
514       if (errno == EPERM) {
515         return false;
516       }
517 #endif  // OS_MACOSX
518       if (errno == EPIPE) {
519         return false;
520       }
521       PLOG(ERROR) << "pipe error on "
522                   << fd_written
523                   << " Currently writing message of size: "
524                   << msg->size();
525       return false;
526     }
527
528     if (static_cast<size_t>(bytes_written) != amt_to_write) {
529       if (bytes_written > 0) {
530         // If write() fails with EAGAIN then bytes_written will be -1.
531         message_send_bytes_written_ += bytes_written;
532       }
533
534       // Tell libevent to call us back once things are unblocked.
535       is_blocked_on_write_ = true;
536       base::MessageLoopForIO::current()->WatchFileDescriptor(
537           pipe_.get(),
538           false,  // One shot
539           base::MessageLoopForIO::WATCH_WRITE,
540           &write_watcher_,
541           this);
542       return true;
543     } else {
544       message_send_bytes_written_ = 0;
545
546       // Message sent OK!
547       DVLOG(2) << "sent message @" << msg << " on channel @" << this
548                << " with type " << msg->type() << " on fd " << pipe_.get();
549       delete output_queue_.front();
550       output_queue_.pop();
551     }
552   }
553   return true;
554 }
555
556 bool ChannelPosix::Send(Message* message) {
557   DVLOG(2) << "sending message @" << message << " on channel @" << this
558            << " with type " << message->type()
559            << " (" << output_queue_.size() << " in queue)";
560
561 #ifdef IPC_MESSAGE_LOG_ENABLED
562   Logging::GetInstance()->OnSendMessage(message, "");
563 #endif  // IPC_MESSAGE_LOG_ENABLED
564
565   message->TraceMessageBegin();
566   output_queue_.push(message);
567   if (!is_blocked_on_write_ && !waiting_connect_) {
568     return ProcessOutgoingMessages();
569   }
570
571   return true;
572 }
573
574 int ChannelPosix::GetClientFileDescriptor() const {
575   base::AutoLock lock(client_pipe_lock_);
576   return client_pipe_.get();
577 }
578
579 base::ScopedFD ChannelPosix::TakeClientFileDescriptor() {
580   base::AutoLock lock(client_pipe_lock_);
581   if (!client_pipe_.is_valid())
582     return base::ScopedFD();
583   PipeMap::GetInstance()->Remove(pipe_name_);
584   return client_pipe_.Pass();
585 }
586
587 void ChannelPosix::CloseClientFileDescriptor() {
588   base::AutoLock lock(client_pipe_lock_);
589   if (!client_pipe_.is_valid())
590     return;
591   PipeMap::GetInstance()->Remove(pipe_name_);
592   client_pipe_.reset();
593 }
594
595 bool ChannelPosix::AcceptsConnections() const {
596   return server_listen_pipe_.is_valid();
597 }
598
599 bool ChannelPosix::HasAcceptedConnection() const {
600   return AcceptsConnections() && pipe_.is_valid();
601 }
602
603 #if !defined(OS_NACL_NONSFI)
604 // GetPeerEuid is not supported in nacl_helper_nonsfi.
605 bool ChannelPosix::GetPeerEuid(uid_t* peer_euid) const {
606   DCHECK(!(mode_ & MODE_SERVER) || HasAcceptedConnection());
607   return IPC::GetPeerEuid(pipe_.get(), peer_euid);
608 }
609 #endif
610
611 void ChannelPosix::ResetToAcceptingConnectionState() {
612   // Unregister libevent for the unix domain socket and close it.
613   read_watcher_.StopWatchingFileDescriptor();
614   write_watcher_.StopWatchingFileDescriptor();
615   pipe_.reset();
616 #if defined(IPC_USES_READWRITE)
617   fd_pipe_.reset();
618   remote_fd_pipe_.reset();
619 #endif  // IPC_USES_READWRITE
620
621   while (!output_queue_.empty()) {
622     Message* m = output_queue_.front();
623     output_queue_.pop();
624     delete m;
625   }
626
627   // Close any outstanding, received file descriptors.
628   ClearInputFDs();
629
630 #if defined(OS_MACOSX)
631   // Clear any outstanding, sent file descriptors.
632   for (std::set<int>::iterator i = fds_to_close_.begin();
633        i != fds_to_close_.end();
634        ++i) {
635     if (IGNORE_EINTR(close(*i)) < 0)
636       PLOG(ERROR) << "close";
637   }
638   fds_to_close_.clear();
639 #endif
640 }
641
642 // static
643 bool ChannelPosix::IsNamedServerInitialized(
644     const std::string& channel_id) {
645   return base::PathExists(base::FilePath(channel_id));
646 }
647
648 #if defined(OS_LINUX)
649 // static
650 void ChannelPosix::SetGlobalPid(int pid) {
651   global_pid_ = pid;
652 }
653 #endif  // OS_LINUX
654
655 // Called by libevent when we can read from the pipe without blocking.
656 void ChannelPosix::OnFileCanReadWithoutBlocking(int fd) {
657   if (fd == server_listen_pipe_.get()) {
658 #if defined(OS_NACL_NONSFI)
659     LOG(FATAL)
660         << "IPC channels in nacl_helper_nonsfi should not be SERVER mode.";
661 #else
662     int new_pipe = 0;
663     if (!ServerAcceptConnection(server_listen_pipe_.get(), &new_pipe) ||
664         new_pipe < 0) {
665       Close();
666       listener()->OnChannelListenError();
667     }
668
669     if (pipe_.is_valid()) {
670       // We already have a connection. We only handle one at a time.
671       // close our new descriptor.
672       if (HANDLE_EINTR(shutdown(new_pipe, SHUT_RDWR)) < 0)
673         DPLOG(ERROR) << "shutdown " << pipe_name_;
674       if (IGNORE_EINTR(close(new_pipe)) < 0)
675         DPLOG(ERROR) << "close " << pipe_name_;
676       listener()->OnChannelDenied();
677       return;
678     }
679     pipe_.reset(new_pipe);
680
681     if ((mode_ & MODE_OPEN_ACCESS_FLAG) == 0) {
682       // Verify that the IPC channel peer is running as the same user.
683       uid_t client_euid;
684       if (!GetPeerEuid(&client_euid)) {
685         DLOG(ERROR) << "Unable to query client euid";
686         ResetToAcceptingConnectionState();
687         return;
688       }
689       if (client_euid != geteuid()) {
690         DLOG(WARNING) << "Client euid is not authorised";
691         ResetToAcceptingConnectionState();
692         return;
693       }
694     }
695
696     if (!AcceptConnection()) {
697       NOTREACHED() << "AcceptConnection should not fail on server";
698     }
699     waiting_connect_ = false;
700 #endif
701   } else if (fd == pipe_) {
702     if (waiting_connect_ && (mode_ & MODE_SERVER_FLAG)) {
703       waiting_connect_ = false;
704     }
705     if (!ProcessIncomingMessages()) {
706       // ClosePipeOnError may delete this object, so we mustn't call
707       // ProcessOutgoingMessages.
708       ClosePipeOnError();
709       return;
710     }
711   } else {
712     NOTREACHED() << "Unknown pipe " << fd;
713   }
714
715   // If we're a server and handshaking, then we want to make sure that we
716   // only send our handshake message after we've processed the client's.
717   // This gives us a chance to kill the client if the incoming handshake
718   // is invalid. This also flushes any closefd messages.
719   if (!is_blocked_on_write_) {
720     if (!ProcessOutgoingMessages()) {
721       ClosePipeOnError();
722     }
723   }
724 }
725
726 // Called by libevent when we can write to the pipe without blocking.
727 void ChannelPosix::OnFileCanWriteWithoutBlocking(int fd) {
728   DCHECK_EQ(pipe_.get(), fd);
729   is_blocked_on_write_ = false;
730   if (!ProcessOutgoingMessages()) {
731     ClosePipeOnError();
732   }
733 }
734
735 bool ChannelPosix::AcceptConnection() {
736   base::MessageLoopForIO::current()->WatchFileDescriptor(
737       pipe_.get(),
738       true,
739       base::MessageLoopForIO::WATCH_READ,
740       &read_watcher_,
741       this);
742   QueueHelloMessage();
743
744   if (mode_ & MODE_CLIENT_FLAG) {
745     // If we are a client we want to send a hello message out immediately.
746     // In server mode we will send a hello message when we receive one from a
747     // client.
748     waiting_connect_ = false;
749     return ProcessOutgoingMessages();
750   } else if (mode_ & MODE_SERVER_FLAG) {
751     waiting_connect_ = true;
752     return true;
753   } else {
754     NOTREACHED();
755     return false;
756   }
757 }
758
759 void ChannelPosix::ClosePipeOnError() {
760   if (HasAcceptedConnection()) {
761     ResetToAcceptingConnectionState();
762     listener()->OnChannelError();
763   } else {
764     Close();
765     if (AcceptsConnections()) {
766       listener()->OnChannelListenError();
767     } else {
768       listener()->OnChannelError();
769     }
770   }
771 }
772
773 int ChannelPosix::GetHelloMessageProcId() const {
774   int pid = base::GetCurrentProcId();
775 #if defined(OS_LINUX)
776   // Our process may be in a sandbox with a separate PID namespace.
777   if (global_pid_) {
778     pid = global_pid_;
779   }
780 #endif
781   return pid;
782 }
783
784 void ChannelPosix::QueueHelloMessage() {
785   // Create the Hello message
786   scoped_ptr<Message> msg(new Message(MSG_ROUTING_NONE,
787                                       HELLO_MESSAGE_TYPE,
788                                       IPC::Message::PRIORITY_NORMAL));
789   if (!msg->WriteInt(GetHelloMessageProcId())) {
790     NOTREACHED() << "Unable to pickle hello message proc id";
791   }
792 #if defined(IPC_USES_READWRITE)
793   scoped_ptr<Message> hello;
794   if (remote_fd_pipe_.is_valid()) {
795     if (!msg->WriteBorrowingFile(remote_fd_pipe_.get())) {
796       NOTREACHED() << "Unable to pickle hello message file descriptors";
797     }
798     DCHECK_EQ(msg->file_descriptor_set()->size(), 1U);
799   }
800 #endif  // IPC_USES_READWRITE
801   output_queue_.push(msg.release());
802 }
803
804 ChannelPosix::ReadState ChannelPosix::ReadData(
805     char* buffer,
806     int buffer_len,
807     int* bytes_read) {
808   if (!pipe_.is_valid())
809     return READ_FAILED;
810
811   struct msghdr msg = {0};
812
813   struct iovec iov = {buffer, static_cast<size_t>(buffer_len)};
814   msg.msg_iov = &iov;
815   msg.msg_iovlen = 1;
816
817   msg.msg_control = input_cmsg_buf_;
818
819   // recvmsg() returns 0 if the connection has closed or EAGAIN if no data
820   // is waiting on the pipe.
821 #if defined(IPC_USES_READWRITE)
822   if (fd_pipe_.is_valid()) {
823     *bytes_read = HANDLE_EINTR(read(pipe_.get(), buffer, buffer_len));
824     msg.msg_controllen = 0;
825   } else
826 #endif  // IPC_USES_READWRITE
827   {
828     msg.msg_controllen = sizeof(input_cmsg_buf_);
829     *bytes_read = HANDLE_EINTR(recvmsg(pipe_.get(), &msg, MSG_DONTWAIT));
830   }
831   if (*bytes_read < 0) {
832     if (errno == EAGAIN) {
833       return READ_PENDING;
834 #if defined(OS_MACOSX)
835     } else if (errno == EPERM) {
836       // On OSX, reading from a pipe with no listener returns EPERM
837       // treat this as a special case to prevent spurious error messages
838       // to the console.
839       return READ_FAILED;
840 #endif  // OS_MACOSX
841     } else if (errno == ECONNRESET || errno == EPIPE) {
842       return READ_FAILED;
843     } else {
844       PLOG(ERROR) << "pipe error (" << pipe_.get() << ")";
845       return READ_FAILED;
846     }
847   } else if (*bytes_read == 0) {
848     // The pipe has closed...
849     return READ_FAILED;
850   }
851   DCHECK(*bytes_read);
852
853   CloseClientFileDescriptor();
854
855   // Read any file descriptors from the message.
856   if (!ExtractFileDescriptorsFromMsghdr(&msg))
857     return READ_FAILED;
858   return READ_SUCCEEDED;
859 }
860
861 #if defined(IPC_USES_READWRITE)
862 bool ChannelPosix::ReadFileDescriptorsFromFDPipe() {
863   char dummy;
864   struct iovec fd_pipe_iov = { &dummy, 1 };
865
866   struct msghdr msg = { 0 };
867   msg.msg_iov = &fd_pipe_iov;
868   msg.msg_iovlen = 1;
869   msg.msg_control = input_cmsg_buf_;
870   msg.msg_controllen = sizeof(input_cmsg_buf_);
871   ssize_t bytes_received =
872       HANDLE_EINTR(recvmsg(fd_pipe_.get(), &msg, MSG_DONTWAIT));
873
874   if (bytes_received != 1)
875     return true;  // No message waiting.
876
877   if (!ExtractFileDescriptorsFromMsghdr(&msg))
878     return false;
879   return true;
880 }
881 #endif
882
883 // On Posix, we need to fix up the file descriptors before the input message
884 // is dispatched.
885 //
886 // This will read from the input_fds_ (READWRITE mode only) and read more
887 // handles from the FD pipe if necessary.
888 bool ChannelPosix::WillDispatchInputMessage(Message* msg) {
889   uint16 header_fds = msg->header()->num_fds;
890   if (!header_fds)
891     return true;  // Nothing to do.
892
893   // The message has file descriptors.
894   const char* error = NULL;
895   if (header_fds > input_fds_.size()) {
896     // The message has been completely received, but we didn't get
897     // enough file descriptors.
898 #if defined(IPC_USES_READWRITE)
899     if (!ReadFileDescriptorsFromFDPipe())
900       return false;
901     if (header_fds > input_fds_.size())
902 #endif  // IPC_USES_READWRITE
903       error = "Message needs unreceived descriptors";
904   }
905
906   if (header_fds > FileDescriptorSet::kMaxDescriptorsPerMessage)
907     error = "Message requires an excessive number of descriptors";
908
909   if (error) {
910     LOG(WARNING) << error
911                  << " channel:" << this
912                  << " message-type:" << msg->type()
913                  << " header()->num_fds:" << header_fds;
914     // Abort the connection.
915     ClearInputFDs();
916     return false;
917   }
918
919   // The shenaniganery below with &foo.front() requires input_fds_ to have
920   // contiguous underlying storage (such as a simple array or a std::vector).
921   // This is why the header warns not to make input_fds_ a deque<>.
922   msg->file_descriptor_set()->AddDescriptorsToOwn(&input_fds_.front(),
923                                                   header_fds);
924   input_fds_.erase(input_fds_.begin(), input_fds_.begin() + header_fds);
925   return true;
926 }
927
928 bool ChannelPosix::DidEmptyInputBuffers() {
929   // When the input data buffer is empty, the fds should be too. If this is
930   // not the case, we probably have a rogue renderer which is trying to fill
931   // our descriptor table.
932   return input_fds_.empty();
933 }
934
935 bool ChannelPosix::ExtractFileDescriptorsFromMsghdr(msghdr* msg) {
936   // Check that there are any control messages. On OSX, CMSG_FIRSTHDR will
937   // return an invalid non-NULL pointer in the case that controllen == 0.
938   if (msg->msg_controllen == 0)
939     return true;
940
941   for (cmsghdr* cmsg = CMSG_FIRSTHDR(msg);
942        cmsg;
943        cmsg = CMSG_NXTHDR(msg, cmsg)) {
944     if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
945       unsigned payload_len = cmsg->cmsg_len - CMSG_LEN(0);
946       DCHECK_EQ(0U, payload_len % sizeof(int));
947       const int* file_descriptors = reinterpret_cast<int*>(CMSG_DATA(cmsg));
948       unsigned num_file_descriptors = payload_len / 4;
949       input_fds_.insert(input_fds_.end(),
950                         file_descriptors,
951                         file_descriptors + num_file_descriptors);
952
953       // Check this after adding the FDs so we don't leak them.
954       if (msg->msg_flags & MSG_CTRUNC) {
955         ClearInputFDs();
956         return false;
957       }
958
959       return true;
960     }
961   }
962
963   // No file descriptors found, but that's OK.
964   return true;
965 }
966
967 void ChannelPosix::ClearInputFDs() {
968   for (size_t i = 0; i < input_fds_.size(); ++i) {
969     if (IGNORE_EINTR(close(input_fds_[i])) < 0)
970       PLOG(ERROR) << "close ";
971   }
972   input_fds_.clear();
973 }
974
975 void ChannelPosix::QueueCloseFDMessage(int fd, int hops) {
976   switch (hops) {
977     case 1:
978     case 2: {
979       // Create the message
980       scoped_ptr<Message> msg(new Message(MSG_ROUTING_NONE,
981                                           CLOSE_FD_MESSAGE_TYPE,
982                                           IPC::Message::PRIORITY_NORMAL));
983       if (!msg->WriteInt(hops - 1) || !msg->WriteInt(fd)) {
984         NOTREACHED() << "Unable to pickle close fd.";
985       }
986       // Send(msg.release());
987       output_queue_.push(msg.release());
988       break;
989     }
990
991     default:
992       NOTREACHED();
993       break;
994   }
995 }
996
997 void ChannelPosix::HandleInternalMessage(const Message& msg) {
998   // The Hello message contains only the process id.
999   PickleIterator iter(msg);
1000
1001   switch (msg.type()) {
1002     default:
1003       NOTREACHED();
1004       break;
1005
1006     case Channel::HELLO_MESSAGE_TYPE:
1007       int pid;
1008       if (!msg.ReadInt(&iter, &pid))
1009         NOTREACHED();
1010
1011 #if defined(IPC_USES_READWRITE)
1012       if (mode_ & MODE_SERVER_FLAG) {
1013         // With IPC_USES_READWRITE, the Hello message from the client to the
1014         // server also contains the fd_pipe_, which  will be used for all
1015         // subsequent file descriptor passing.
1016         DCHECK_EQ(msg.file_descriptor_set()->size(), 1U);
1017         base::ScopedFD descriptor;
1018         if (!msg.ReadFile(&iter, &descriptor)) {
1019           NOTREACHED();
1020         }
1021         fd_pipe_.reset(descriptor.release());
1022       }
1023 #endif  // IPC_USES_READWRITE
1024       peer_pid_ = pid;
1025       listener()->OnChannelConnected(pid);
1026       break;
1027
1028 #if defined(OS_MACOSX)
1029     case Channel::CLOSE_FD_MESSAGE_TYPE:
1030       int fd, hops;
1031       if (!msg.ReadInt(&iter, &hops))
1032         NOTREACHED();
1033       if (!msg.ReadInt(&iter, &fd))
1034         NOTREACHED();
1035       if (hops == 0) {
1036         if (fds_to_close_.erase(fd) > 0) {
1037           if (IGNORE_EINTR(close(fd)) < 0)
1038             PLOG(ERROR) << "close";
1039         } else {
1040           NOTREACHED();
1041         }
1042       } else {
1043         QueueCloseFDMessage(fd, hops);
1044       }
1045       break;
1046 #endif
1047   }
1048 }
1049
1050 void ChannelPosix::Close() {
1051   // Close can be called multiple time, so we need to make sure we're
1052   // idempotent.
1053
1054   ResetToAcceptingConnectionState();
1055
1056   if (must_unlink_) {
1057     unlink(pipe_name_.c_str());
1058     must_unlink_ = false;
1059   }
1060
1061   if (server_listen_pipe_.is_valid()) {
1062 #if defined(OS_NACL_NONSFI)
1063     LOG(FATAL)
1064         << "IPC channels in nacl_helper_nonsfi should not be SERVER mode.";
1065 #else
1066     server_listen_pipe_.reset();
1067     // Unregister libevent for the listening socket and close it.
1068     server_listen_connection_watcher_.StopWatchingFileDescriptor();
1069 #endif
1070   }
1071
1072   CloseClientFileDescriptor();
1073 }
1074
1075 base::ProcessId ChannelPosix::GetPeerPID() const {
1076   return peer_pid_;
1077 }
1078
1079 base::ProcessId ChannelPosix::GetSelfPID() const {
1080   return GetHelloMessageProcId();
1081 }
1082
1083 //------------------------------------------------------------------------------
1084 // Channel's methods
1085
1086 // static
1087 scoped_ptr<Channel> Channel::Create(
1088     const IPC::ChannelHandle &channel_handle, Mode mode, Listener* listener) {
1089   return make_scoped_ptr(new ChannelPosix(channel_handle, mode, listener));
1090 }
1091
1092 // static
1093 std::string Channel::GenerateVerifiedChannelID(const std::string& prefix) {
1094   // A random name is sufficient validation on posix systems, so we don't need
1095   // an additional shared secret.
1096
1097   std::string id = prefix;
1098   if (!id.empty())
1099     id.append(".");
1100
1101   return id.append(GenerateUniqueRandomChannelID());
1102 }
1103
1104
1105 bool Channel::IsNamedServerInitialized(
1106     const std::string& channel_id) {
1107   return ChannelPosix::IsNamedServerInitialized(channel_id);
1108 }
1109
1110 #if defined(OS_LINUX)
1111 // static
1112 void Channel::SetGlobalPid(int pid) {
1113   ChannelPosix::SetGlobalPid(pid);
1114 }
1115 #endif  // OS_LINUX
1116
1117 }  // namespace IPC