1 /* 2 * Copyright (C) 2016 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #include <errno.h> 18 #include <string.h> 19 20 #include "LeakPipe.h" 21 22 #include "log.h" 23 24 bool LeakPipe::SendFd(int sock, int fd) { 25 struct msghdr hdr{}; 26 struct iovec iov{}; 27 unsigned int data = 0xfdfdfdfd; 28 alignas(struct cmsghdr) char cmsgbuf[CMSG_SPACE(sizeof(int))]; 29 30 hdr.msg_iov = &iov; 31 hdr.msg_iovlen = 1; 32 iov.iov_base = &data; 33 iov.iov_len = sizeof(data); 34 35 hdr.msg_control = cmsgbuf; 36 hdr.msg_controllen = CMSG_LEN(sizeof(int)); 37 38 struct cmsghdr* cmsg = CMSG_FIRSTHDR(&hdr); 39 cmsg->cmsg_len = CMSG_LEN(sizeof(int)); 40 cmsg->cmsg_level = SOL_SOCKET; 41 cmsg->cmsg_type = SCM_RIGHTS; 42 43 *(int*)CMSG_DATA(cmsg) = fd; 44 45 int ret = sendmsg(sock, &hdr, 0); 46 if (ret < 0) { 47 ALOGE("failed to send fd: %s", strerror(errno)); 48 return false; 49 } 50 if (ret == 0) { 51 ALOGE("eof when sending fd"); 52 return false; 53 } 54 55 return true; 56 } 57 58 int LeakPipe::ReceiveFd(int sock) { 59 struct msghdr hdr{}; 60 struct iovec iov{}; 61 unsigned int data; 62 alignas(struct cmsghdr) char cmsgbuf[CMSG_SPACE(sizeof(int))]; 63 64 hdr.msg_iov = &iov; 65 hdr.msg_iovlen = 1; 66 iov.iov_base = &data; 67 iov.iov_len = sizeof(data); 68 69 hdr.msg_control = cmsgbuf; 70 hdr.msg_controllen = CMSG_LEN(sizeof(int)); 71 72 int ret = recvmsg(sock, &hdr, 0); 73 if (ret < 0) { 74 ALOGE("failed to receive fd: %s", strerror(errno)); 75 return -1; 76 } 77 if (ret == 0) { 78 ALOGE("eof when receiving fd"); 79 return -1; 80 } 81 82 struct cmsghdr* cmsg = CMSG_FIRSTHDR(&hdr); 83 if (cmsg == NULL || cmsg->cmsg_level != SOL_SOCKET || cmsg->cmsg_type != SCM_RIGHTS) { 84 ALOGE("missing fd while receiving fd"); 85 return -1; 86 } 87 88 return *(int*)CMSG_DATA(cmsg); 89 } 90