1 /* 2 * Copyright (C) 2022 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 package com.android.net.module.util; 17 18 import androidx.annotation.NonNull; 19 20 import java.io.IOException; 21 22 /** 23 * The classes and the methods for BPF utilization. 24 * 25 * {@hide} 26 */ 27 public class BpfUtils { 28 static { JniUtil.getJniLibraryName()29 System.loadLibrary(JniUtil.getJniLibraryName(BpfUtils.class.getPackage())); 30 } 31 32 // Defined in include/uapi/linux/bpf.h. Only adding the CGROUPS currently being used for now. 33 public static final int BPF_CGROUP_INET_INGRESS = 0; 34 public static final int BPF_CGROUP_INET_EGRESS = 1; 35 public static final int BPF_CGROUP_INET4_BIND = 8; 36 public static final int BPF_CGROUP_INET6_BIND = 9; 37 38 39 /** 40 * Attach BPF program to CGROUP 41 */ attachProgram(int type, @NonNull String programPath, @NonNull String cgroupPath, int flags)42 public static void attachProgram(int type, @NonNull String programPath, 43 @NonNull String cgroupPath, int flags) throws IOException { 44 native_attachProgramToCgroup(type, programPath, cgroupPath, flags); 45 } 46 47 /** 48 * Detach BPF program from CGROUP 49 */ detachProgram(int type, @NonNull String cgroupPath)50 public static void detachProgram(int type, @NonNull String cgroupPath) 51 throws IOException { 52 native_detachProgramFromCgroup(type, cgroupPath); 53 } 54 55 /** 56 * Detach single BPF program from CGROUP 57 */ detachSingleProgram(int type, @NonNull String programPath, @NonNull String cgroupPath)58 public static void detachSingleProgram(int type, @NonNull String programPath, 59 @NonNull String cgroupPath) throws IOException { 60 native_detachSingleProgramFromCgroup(type, programPath, cgroupPath); 61 } 62 native_attachProgramToCgroup(int type, String programPath, String cgroupPath, int flags)63 private static native boolean native_attachProgramToCgroup(int type, String programPath, 64 String cgroupPath, int flags) throws IOException; native_detachProgramFromCgroup(int type, String cgroupPath)65 private static native boolean native_detachProgramFromCgroup(int type, String cgroupPath) 66 throws IOException; native_detachSingleProgramFromCgroup(int type, String programPath, String cgroupPath)67 private static native boolean native_detachSingleProgramFromCgroup(int type, 68 String programPath, String cgroupPath) throws IOException; 69 } 70