• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2010, 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 "AsynchronousSocketCloseMonitor.h"
18 #include "JNIHelp.h"
19 #include "JniException.h"
20 #include "JniConstants.h"
21 #include "NetFd.h"
22 #include "NetworkUtilities.h"
23 #include "ScopedUtfChars.h"
24 #include "ScopedPrimitiveArray.h"
25 
26 #include "jni.h"
27 
28 #include <sys/types.h>
29 #include <sys/socket.h>
30 #include <linux/rtnetlink.h>
31 #include <net/if.h>
32 #include <linux/if_ether.h>
33 #include <linux/if_packet.h>
34 #include <arpa/inet.h>
35 #include <errno.h>
36 #include <fcntl.h>
37 #include <poll.h>
38 #include <netinet/ip.h>
39 #include <linux/udp.h>
40 
41 union GCC_HIDDEN sockunion {
42     sockaddr sa;
43     sockaddr_ll sll;
44 } su;
45 
46 /*
47  * Creates a socket suitable for raw socket operations.  The socket is
48  * bound to the interface specified by the supplied name.  The socket
49  * value is placed into the supplied FileDescriptor instance.
50  *
51  * TODO(chesnutt): consider breaking this into pieces: create a
52  * variety of constructors for different socket types, then a generic
53  * setBlocking() method followed by polymorphic bind().
54  */
RawSocket_create(JNIEnv * env,jclass,jobject fileDescriptor,jshort protocolType,jstring interfaceName)55 static void RawSocket_create(JNIEnv* env, jclass, jobject fileDescriptor,
56     jshort protocolType, jstring interfaceName)
57 {
58 
59   ScopedUtfChars ifname(env, interfaceName);
60   if (ifname.c_str() == NULL) {
61     return;
62   }
63 
64   memset(&su, 0, sizeof(su));
65   su.sll.sll_family = PF_PACKET;
66   su.sll.sll_protocol = htons(protocolType);
67   su.sll.sll_ifindex = if_nametoindex(ifname.c_str());
68   int sock = socket(PF_PACKET, SOCK_DGRAM, htons(protocolType));
69 
70   if (sock == -1) {
71     ALOGE("Can't create socket %s", strerror(errno));
72     jniThrowSocketException(env, errno);
73     return;
74   }
75 
76   jniSetFileDescriptorOfFD(env, fileDescriptor, sock);
77   if (!setBlocking(sock, false)) {
78     ALOGE("Can't set non-blocking mode on socket %s", strerror(errno));
79     jniThrowSocketException(env, errno);
80     return;
81   }
82 
83   int err = bind(sock, &su.sa, sizeof(su));
84   if (err != 0) {
85     ALOGE("Socket bind error %s", strerror(errno));
86     jniThrowSocketException(env, errno);
87     return;
88   }
89 }
90 
91 /*
92  * Writes the L3 (IP) packet to the raw socket supplied in the
93  * FileDescriptor instance.
94  *
95  * Assumes that the caller has validated the offset & byteCount values.
96  */
RawSocket_sendPacket(JNIEnv * env,jclass,jobject fileDescriptor,jstring interfaceName,jshort protocolType,jbyteArray destMac,jbyteArray packet,jint offset,jint byteCount)97 static int RawSocket_sendPacket(JNIEnv* env, jclass, jobject fileDescriptor,
98     jstring interfaceName, jshort protocolType, jbyteArray destMac,
99     jbyteArray packet, jint offset, jint byteCount)
100 {
101   NetFd fd(env, fileDescriptor);
102 
103   if (fd.isClosed()) {
104     return 0;
105   }
106 
107   ScopedUtfChars ifname(env, interfaceName);
108   if (ifname.c_str() == NULL) {
109     return 0;
110   }
111 
112   ScopedByteArrayRO byteArray(env, packet);
113   if (byteArray.get() == NULL) {
114     return 0;
115   }
116 
117   ScopedByteArrayRO mac(env, destMac);
118   if (mac.get() == NULL) {
119     return 0;
120   }
121 
122   memset(&su, 0, sizeof(su));
123   su.sll.sll_hatype = htons(1); // ARPHRD_ETHER
124   su.sll.sll_halen = mac.size();
125   memcpy(&su.sll.sll_addr, mac.get(), mac.size());
126   su.sll.sll_family = AF_PACKET;
127   su.sll.sll_protocol = htons(protocolType);
128   su.sll.sll_ifindex = if_nametoindex(ifname.c_str());
129 
130   int err;
131   {
132     int intFd = fd.get();
133     AsynchronousSocketCloseMonitor monitor(intFd);
134     err = NET_FAILURE_RETRY(fd, sendto(intFd, byteArray.get() + offset,
135         byteCount, 0, &su.sa, sizeof(su)));
136   }
137 
138   return err;
139 }
140 
141 /*
142  * Reads a network packet into the user-supplied buffer.  Return the
143  * length of the packet, or a 0 if there was a timeout or an
144  * unacceptable packet was acquired.
145  *
146  * Assumes that the caller has validated the offset & byteCount values.
147  */
RawSocket_recvPacket(JNIEnv * env,jclass,jobject fileDescriptor,jbyteArray packet,jint offset,jint byteCount,jint port,jint timeout_millis)148 static jint RawSocket_recvPacket(JNIEnv* env, jclass, jobject fileDescriptor,
149     jbyteArray packet, jint offset, jint byteCount, jint port,
150     jint timeout_millis)
151 {
152   NetFd fd(env, fileDescriptor);
153   if (fd.isClosed()) {
154     return 0;
155   }
156 
157   ScopedByteArrayRW body(env, packet);
158   jbyte* packetData = body.get();
159   if (packetData == NULL) {
160     return 0;
161   }
162 
163   packetData += offset;
164 
165   pollfd fds[1];
166   fds[0].fd = fd.get();
167   fds[0].events = POLLIN;
168   int retval = poll(fds, 1, timeout_millis);
169   if (retval <= 0) {
170     return 0;
171   }
172 
173   unsigned int size = 0;
174   {
175     int packetSize = byteCount;
176     int intFd = fd.get();
177     AsynchronousSocketCloseMonitor monitor(intFd);
178     size = NET_FAILURE_RETRY(fd, read(intFd, packetData, packetSize));
179   }
180 
181   if (env->ExceptionOccurred()) {
182     return 0;
183   }
184 
185   if (port != -1) {
186     // quick check for UDP type & UDP port
187     // the packet is an IP header, UDP header, and UDP payload
188     if ((size < (sizeof(struct iphdr) + sizeof(struct udphdr)))) {
189       return 0;  // runt packet
190     }
191 
192     u_int8_t ip_proto = ((iphdr *) packetData)->protocol;
193     if (ip_proto != IPPROTO_UDP) {
194       return 0;  // something other than UDP
195     }
196 
197     __be16 destPort = htons((reinterpret_cast<udphdr*>(packetData + sizeof(iphdr)))->dest);
198     if (destPort != port) {
199       return 0; // something other than requested port
200     }
201   }
202 
203   return size;
204 }
205 
206 static JNINativeMethod gRawMethods[] = {
207   NATIVE_METHOD(RawSocket, create, "(Ljava/io/FileDescriptor;SLjava/lang/String;)V"),
208   NATIVE_METHOD(RawSocket, sendPacket, "(Ljava/io/FileDescriptor;Ljava/lang/String;S[B[BII)I"),
209   NATIVE_METHOD(RawSocket, recvPacket, "(Ljava/io/FileDescriptor;[BIIII)I"),
210 };
211 
register_libcore_net_RawSocket(JNIEnv * env)212 void register_libcore_net_RawSocket(JNIEnv* env) {
213   jniRegisterNativeMethods(env, "libcore/net/RawSocket", gRawMethods, NELEM(gRawMethods));
214 }
215