Debian Codegraph @

src/main/java/jnr/netdb/NativeServicesDB.java

raw
1 /*
2 * Copyright (C) 2010 Wayne Meissner
3 *
4 * This file is part of jnr.
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19 package jnr.netdb;
20
21 import jnr.ffi.*;
22 import jnr.ffi.Runtime;
23 import jnr.ffi.annotations.Direct;
24 import jnr.ffi.annotations.Out;
25
26 import java.nio.ByteOrder;
27 import java.util.ArrayList;
28 import java.util.Collection;
29 import java.util.Collections;
30 import java.util.HashMap;
31 import java.util.List;
32 import java.util.Map;
33 import java.util.logging.Level;
34 import java.util.logging.Logger;
35
36 import static jnr.ffi.Platform.OS.*;
37
38 /**
39 *
40 */
41 abstract class NativeServicesDB implements ServicesDB {
42
43 protected final LibServices lib;
44
45 public NativeServicesDB(LibServices lib) {
46 this.lib = lib;
47 }
48
49 public static final NativeServicesDB getInstance() {
50 return SingletonHolder.INSTANCE;
51 }
52
53 private static final class SingletonHolder {
54 public static final NativeServicesDB INSTANCE = load();
55 }
56
57 static final NativeServicesDB load() {
58 try {
59 Platform.OS os = Platform.getNativePlatform().getOS();
60
61 // The ServiceEntry struct is only known to match on Windows, MacOSX, Linux, Solaris.
62 // We assume FreeBSD and NetBSD also match.
63 if (!(os.equals(DARWIN) || (os.equals(WINDOWS) && Platform.getNativePlatform().getCPU() == Platform.CPU.I386)
64 || os.equals(LINUX) || os.equals(SOLARIS)
65 || os.equals(FREEBSD) || os.equals(NETBSD))) {
66 return null;
67 }
68
69 LibServices lib;
70 if (os.equals(WINDOWS)) {
71 Map<LibraryOption, Object> options = new HashMap<LibraryOption, Object>();
72 options.put(LibraryOption.CallingConvention, CallingConvention.STDCALL);
73 lib = Library.loadLibrary(LibServices.class, options, "Ws2_32");
74
75 } else {
76 String[] libnames = os.equals(SOLARIS)
77 ? new String[] { "socket", "nsl", "c" }
78 : new String[] { "c" };
79
80 if (os.equals(LINUX)) {
81 lib = Library.loadLibrary(LinuxLibServices.class, libnames);
82 } else {
83 lib = Library.loadLibrary(LibServices.class, libnames);
84 }
85 }
86
87 NativeServicesDB services = os.equals(LINUX)
88 ? new LinuxServicesDB(lib)
89 : new DefaultNativeServicesDB(lib);
90 // Try to lookup a service to make sure the library loaded and found the functions
91 if (services.getServiceByName("comsat", "udp") == null) {
92 return null;
93 }
94 services.getServiceByName("bootps", "udp");
95 services.getServiceByPort(67, "udp");
96
97 return services;
98
99 } catch (Throwable t) {
100 Logger.getLogger(NativeServicesDB.class.getName()).log(Level.WARNING, "Failed to load native services db", t);
101 return null;
102 }
103 }
104
105 public static class UnixServent extends jnr.ffi.Struct {
106 public final String name = new UTF8StringRef();
107 public final Pointer aliases = new Pointer();
108 public final Signed32 port = new Signed32();
109 public final String proto = new UTF8StringRef();
110
111 public UnixServent(jnr.ffi.Runtime runtime) {
112 super(runtime);
113 }
114 }
115
116 public static class LinuxServent extends UnixServent {
117 public static final int BUFLEN = 4096;
118 public final jnr.ffi.Pointer buf;
119
120 public LinuxServent(jnr.ffi.Runtime runtime) {
121 super(runtime);
122 this.buf = Memory.allocateDirect(runtime, BUFLEN, true);
123 }
124 }
125
126 public static interface LibServices {
127 UnixServent getservbyname(String name, String proto);
128 UnixServent getservbyport(Integer port, String proto);
129 UnixServent getservent();
130 void endservent();
131 }
132
133 public static interface LinuxLibServices extends LibServices {
134 int getservbyname_r(String name, String proto, @Direct UnixServent servent,
135 Pointer buf, NativeLong buflen, @Out Pointer result);
136 int getservbyport_r(Integer port, String proto, @Direct UnixServent servent,
137 Pointer buf, NativeLong buflen, @Out Pointer result);
138 int getservent_r(@Direct UnixServent servent,
139 Pointer buf, NativeLong buflen, Pointer result);
140 }
141
142 static int ntohs(int value) {
143 int hostValue = ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN) ? Short.reverseBytes((short) value) : value;
144 if (hostValue < 0) {
145 // The byte flipping above will return numbers >= 32768 as a negative value,
146 // so they need to be converted back to a unsigned 16 bit value.
147 hostValue = ((hostValue & 0x7FFF) + 0x8000);
148 }
149
150 return hostValue;
151 }
152
153 static int htons(int value) {
154 return ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN) ? Short.reverseBytes((short) value) : value;
155 }
156
157 static Service serviceFromNative(UnixServent s) {
158 if (s == null) {
159 return null;
160 }
161
162 List<String> emptyAliases = Collections.emptyList();
163 Pointer ptr;
164 final Collection<String> aliases = ((ptr = s.aliases.get()) != null)
165 ? StringUtil.getNullTerminatedStringArray(ptr) : emptyAliases;
166
167 return new Service(s.name.get(), ntohs(s.port.get()), s.proto.get(), aliases);
168 }
169
170 static final class DefaultNativeServicesDB extends NativeServicesDB {
171 DefaultNativeServicesDB(LibServices lib) {
172 super(lib);
173 }
174
175 public Collection<Service> getAllServices() {
176 UnixServent s;
177 List<Service> allServices = new ArrayList<Service>();
178
179 try {
180 while ((s = lib.getservent()) != null) {
181 allServices.add(serviceFromNative(s));
182 }
183 } finally {
184 lib.endservent();
185 }
186
187 return allServices;
188 }
189
190
191 public Service getServiceByName(String name, String proto) {
192 return serviceFromNative(lib.getservbyname(name, proto));
193 }
194
195 public Service getServiceByPort(Integer port, String proto) {
196 return serviceFromNative(lib.getservbyport(htons(port), proto));
197 }
198 }
199
200 static final class LinuxServicesDB extends NativeServicesDB {
201 private static final int BUFLEN = 4096;
202 private final LinuxLibServices lib;
203 private final Runtime runtime;
204 private final Pointer buf;
205
206 LinuxServicesDB(LibServices lib) {
207 super(lib);
208 this.lib = (LinuxLibServices) lib;
209 this.runtime = Library.getRuntime(lib);
210 this.buf = Memory.allocateDirect(runtime, BUFLEN);
211 }
212
213 public synchronized Service getServiceByName(String name, String proto) {
214 UnixServent servent = new UnixServent(runtime);
215 Pointer result = Memory.allocateDirect(runtime, runtime.addressSize());
216 if (lib.getservbyname_r(name, proto, servent, buf, new NativeLong(BUFLEN), result) == 0) {
217 return result.getPointer(0) != null ? serviceFromNative(servent) : null;
218 }
219
220 throw new RuntimeException("getservbyname_r failed");
221 }
222
223 public synchronized Service getServiceByPort(Integer port, String proto) {
224 UnixServent servent = new UnixServent(runtime);
225 Pointer result = Memory.allocateDirect(runtime, runtime.addressSize());
226 if (lib.getservbyport_r(htons(port), proto, servent, buf, new NativeLong(BUFLEN), result) == 0) {
227 return result.getPointer(0) != null ? serviceFromNative(servent) : null;
228 }
229
230 throw new RuntimeException("getservbyport_r failed");
231 }
232
233 public synchronized Collection<Service> getAllServices() {
234 UnixServent s = new UnixServent(runtime);
235 List<Service> allServices = new ArrayList<Service>();
236 Pointer result = Memory.allocateDirect(runtime, runtime.addressSize());
237 NativeLong buflen = new NativeLong(BUFLEN);
238
239 try {
240 while (lib.getservent_r(s, buf, buflen, result) == 0 && result.getPointer(0) != null) {
241 allServices.add(serviceFromNative(s));
242 }
243 } finally {
244 lib.endservent();
245 }
246
247 return allServices;
248 }
249 }
250
251 }