FwmarkClient.cpp revision 27aacc0d49dbc5c3721ae5ca6f6033be6537c4c3
1/* 2 * Copyright (C) 2014 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 "FwmarkClient.h" 18 19#include <errno.h> 20#include <stdlib.h> 21#include <sys/socket.h> 22#include <sys/un.h> 23#include <unistd.h> 24 25namespace { 26 27const sockaddr_un FWMARK_SERVER_PATH = {AF_UNIX, "/dev/socket/fwmarkd"}; 28 29} // namespace 30 31bool FwmarkClient::shouldSetFwmark(int family) { 32 return (family == AF_INET || family == AF_INET6) && !getenv("ANDROID_NO_USE_FWMARK_CLIENT"); 33} 34 35FwmarkClient::FwmarkClient() : mChannel(-1) { 36} 37 38FwmarkClient::~FwmarkClient() { 39 if (mChannel >= 0) { 40 close(mChannel); 41 } 42} 43 44int FwmarkClient::send(void* data, size_t len, int fd) { 45 mChannel = socket(AF_UNIX, SOCK_STREAM, 0); 46 if (mChannel == -1) { 47 return -errno; 48 } 49 50 if (TEMP_FAILURE_RETRY(connect(mChannel, reinterpret_cast<const sockaddr*>(&FWMARK_SERVER_PATH), 51 sizeof(FWMARK_SERVER_PATH))) == -1) { 52 // If we are unable to connect to the fwmark server, assume there's no error. This protects 53 // against future changes if the fwmark server goes away. 54 return 0; 55 } 56 57 iovec iov; 58 iov.iov_base = data; 59 iov.iov_len = len; 60 61 msghdr message; 62 memset(&message, 0, sizeof(message)); 63 message.msg_iov = &iov; 64 message.msg_iovlen = 1; 65 66 union { 67 cmsghdr cmh; 68 char cmsg[CMSG_SPACE(sizeof(fd))]; 69 } cmsgu; 70 71 memset(cmsgu.cmsg, 0, sizeof(cmsgu.cmsg)); 72 message.msg_control = cmsgu.cmsg; 73 message.msg_controllen = sizeof(cmsgu.cmsg); 74 75 cmsghdr* const cmsgh = CMSG_FIRSTHDR(&message); 76 cmsgh->cmsg_len = CMSG_LEN(sizeof(fd)); 77 cmsgh->cmsg_level = SOL_SOCKET; 78 cmsgh->cmsg_type = SCM_RIGHTS; 79 memcpy(CMSG_DATA(cmsgh), &fd, sizeof(fd)); 80 81 if (TEMP_FAILURE_RETRY(sendmsg(mChannel, &message, 0)) == -1) { 82 return -errno; 83 } 84 85 int error = 0; 86 87 if (TEMP_FAILURE_RETRY(recv(mChannel, &error, sizeof(error), 0)) == -1) { 88 return -errno; 89 } 90 91 return error; 92} 93