1 /*
2 * Copyright (C) 2011 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 <jni.h>
18 #include <stdio.h>
19 #include <cutils/log.h>
20 #include <asm/types.h>
21 #include <sys/socket.h>
22 #include <linux/netlink.h>
23 #include <errno.h>
24 #include "JNIHelp.h"
25
26 #include "android_net_cts_NetlinkSocket.h"
27
android_net_cts_NetlinkSocket_create(JNIEnv * env,jclass,jobject fileDescriptor)28 static void android_net_cts_NetlinkSocket_create(JNIEnv* env, jclass,
29 jobject fileDescriptor)
30 {
31 int sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
32 if (sock == -1) {
33 LOGE("Can't create socket %s", strerror(errno));
34 jclass SocketException = env->FindClass("java/net/SocketException");
35 env->ThrowNew(SocketException, "Can't create socket");
36 return;
37 }
38 jniSetFileDescriptorOfFD(env, fileDescriptor, sock);
39 }
40
android_net_cts_NetlinkSocket_sendmsg(JNIEnv * e,jclass,jobject fileDescriptor,jint pid,jbyteArray packet)41 static int android_net_cts_NetlinkSocket_sendmsg(JNIEnv *e, jclass,
42 jobject fileDescriptor, jint pid, jbyteArray packet)
43 {
44 void *bytes = (void *)e->GetByteArrayElements(packet, NULL);
45 uint32_t length = (uint32_t)e->GetArrayLength(packet);
46 struct sockaddr_nl snl;
47 struct iovec iov = {bytes, length};
48 struct msghdr msg = {&snl, sizeof(snl), &iov, 1, NULL, 0, 0};
49
50 memset(&snl, 0, sizeof(snl));
51 snl.nl_family = AF_NETLINK;
52 snl.nl_pid = pid;
53
54 int sock = jniGetFDFromFileDescriptor(e, fileDescriptor);
55 int retval = sendmsg(sock, &msg, 0);
56 e->ReleaseByteArrayElements(packet, (jbyte*)bytes, 0);
57 return retval;
58 }
59
60
61 static JNINativeMethod gMethods[] = {
62 { "sendmsg", "(Ljava/io/FileDescriptor;I[B)I", (void *) android_net_cts_NetlinkSocket_sendmsg },
63 { "create_native", "(Ljava/io/FileDescriptor;)V", (void *) android_net_cts_NetlinkSocket_create },
64 };
65
register_android_net_cts_NetlinkSocket(JNIEnv * env)66 int register_android_net_cts_NetlinkSocket(JNIEnv* env)
67 {
68 jclass clazz = env->FindClass("android/net/cts/NetlinkSocket");
69
70 return env->RegisterNatives(clazz, gMethods,
71 sizeof(gMethods) / sizeof(JNINativeMethod));
72 }
73