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 #ifndef BASE_POSIX_UNIX_DOMAIN_SOCKET_LINUX_H_ 6 #define BASE_POSIX_UNIX_DOMAIN_SOCKET_LINUX_H_ 7 8 #include <stdint.h> 9 #include <sys/types.h> 10 #include <vector> 11 12 #include "base/base_export.h" 13 14 class Pickle; 15 16 class BASE_EXPORT UnixDomainSocket { 17 public: 18 // Maximum number of file descriptors that can be read by RecvMsg(). 19 static const size_t kMaxFileDescriptors; 20 21 // Use sendmsg to write the given msg and include a vector of file 22 // descriptors. Returns true if successful. 23 static bool SendMsg(int fd, 24 const void* msg, 25 size_t length, 26 const std::vector<int>& fds); 27 28 // Use recvmsg to read a message and an array of file descriptors. Returns 29 // -1 on failure. Note: will read, at most, |kMaxFileDescriptors| descriptors. 30 static ssize_t RecvMsg(int fd, 31 void* msg, 32 size_t length, 33 std::vector<int>* fds); 34 35 // Perform a sendmsg/recvmsg pair. 36 // 1. This process creates a UNIX SEQPACKET socketpair. Using 37 // connection-oriented sockets (SEQPACKET or STREAM) is critical here, 38 // because if one of the ends closes the other one must be notified. 39 // 2. This process writes a request to |fd| with an SCM_RIGHTS control 40 // message containing on end of the fresh socket pair. 41 // 3. This process blocks reading from the other end of the fresh 42 // socketpair. 43 // 4. The target process receives the request, processes it and writes the 44 // reply to the end of the socketpair contained in the request. 45 // 5. This process wakes up and continues. 46 // 47 // fd: descriptor to send the request on 48 // reply: buffer for the reply 49 // reply_len: size of |reply| 50 // result_fd: (may be NULL) the file descriptor returned in the reply 51 // (if any) 52 // request: the bytes to send in the request 53 static ssize_t SendRecvMsg(int fd, 54 uint8_t* reply, 55 unsigned reply_len, 56 int* result_fd, 57 const Pickle& request); 58 59 // Similar to SendRecvMsg(), but |recvmsg_flags| allows to control the flags 60 // of the recvmsg(2) call. 61 static ssize_t SendRecvMsgWithFlags(int fd, 62 uint8_t* reply, 63 unsigned reply_len, 64 int recvmsg_flags, 65 int* result_fd, 66 const Pickle& request); 67 private: 68 // Similar to RecvMsg, but allows to specify |flags| for recvmsg(2). 69 static ssize_t RecvMsgWithFlags(int fd, 70 void* msg, 71 size_t length, 72 int flags, 73 std::vector<int>* fds); 74 }; 75 76 #endif // BASE_POSIX_UNIX_DOMAIN_SOCKET_LINUX_H_ 77