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