blob: 2e8390c8ef23da79fa9f3d337d66e8046a1e0174 [file] [log] [blame]
Sreeram Ramachandranf4cfad32014-05-21 08:54:07 -07001/*
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#include "FwmarkCommand.h"
19
20#include <sys/socket.h>
21#include <unistd.h>
22
23namespace {
24
25int closeFdAndRestoreErrno(int fd) {
26 int error = errno;
27 close(fd);
28 errno = error;
29 return -1;
30}
31
32typedef int (*ConnectFunctionType)(int, const sockaddr*, socklen_t);
33typedef int (*AcceptFunctionType)(int, sockaddr*, socklen_t*);
34
35ConnectFunctionType libcConnect = 0;
36AcceptFunctionType libcAccept = 0;
37
38int netdClientConnect(int sockfd, const sockaddr* addr, socklen_t addrlen) {
39 if (FwmarkClient::shouldSetFwmark(sockfd, addr)) {
40 char data[] = {FWMARK_COMMAND_ON_CONNECT};
41 if (!FwmarkClient().send(data, sizeof(data), sockfd)) {
42 return -1;
43 }
44 }
45 return libcConnect(sockfd, addr, addrlen);
46}
47
48int netdClientAccept(int sockfd, sockaddr* addr, socklen_t* addrlen) {
49 int acceptedSocket = libcAccept(sockfd, addr, addrlen);
50 if (acceptedSocket == -1) {
51 return -1;
52 }
53 sockaddr socketAddress;
54 if (!addr) {
55 socklen_t socketAddressLen = sizeof(socketAddress);
56 if (getsockname(acceptedSocket, &socketAddress, &socketAddressLen) == -1) {
57 return closeFdAndRestoreErrno(acceptedSocket);
58 }
59 addr = &socketAddress;
60 }
61 if (FwmarkClient::shouldSetFwmark(acceptedSocket, addr)) {
62 char data[] = {FWMARK_COMMAND_ON_ACCEPT};
63 if (!FwmarkClient().send(data, sizeof(data), acceptedSocket)) {
64 return closeFdAndRestoreErrno(acceptedSocket);
65 }
66 }
67 return acceptedSocket;
68}
69
70} // namespace
71
72extern "C" void netdClientInitConnect(ConnectFunctionType* function) {
73 if (function && *function) {
74 libcConnect = *function;
75 *function = netdClientConnect;
76 }
77}
78
79extern "C" void netdClientInitAccept(AcceptFunctionType* function) {
80 if (function && *function) {
81 libcAccept = *function;
82 *function = netdClientAccept;
83 }
84}