Debian Codegraph @

src/java/org/astrogrid/samp/Platform.java

raw
1 package org.astrogrid.samp;
2
3 import java.io.File;
4 import java.io.IOException;
5 import java.io.InputStream;
6 import java.lang.reflect.InvocationTargetException;
7 import java.lang.reflect.Method;
8 import java.util.Arrays;
9 import java.util.logging.Logger;
10
11 /**
12 * Platform-dependent features required by the SAMP implementation.
13 *
14 * @author Mark Taylor
15 * @since 14 Jul 2008
16 */
17 public abstract class Platform {
18
19 private static Platform instance_;
20 private final String name_;
21 private static final Logger logger_ =
22 Logger.getLogger( Platform.class.getName() );
23
24 /**
25 * Constructor.
26 *
27 * @param name platform name
28 */
29 protected Platform( String name ) {
30 name_ = name;
31 }
32
33 /**
34 * Returns SAMP's definition of the "home" directory.
35 *
36 * @return directory containing SAMP lockfile
37 */
38 public abstract File getHomeDirectory();
39
40 /**
41 * Returns the value of an environment variable.
42 * If it can't be done, null is returned.
43 *
44 * @param varname name of environment variable
45 * @return value of environment variable
46 */
47 public String getEnv( String varname ) {
48 try {
49 return System.getenv( varname );
50 }
51
52 // System.getenv is unimplemented at 1.4, and throws an Error.
53 catch ( Throwable e ) {
54 String[] argv = getGetenvArgs( varname );
55 if ( argv == null ) {
56 return null;
57 }
58 else {
59 try {
60 String cmdout = exec( argv );
61 return cmdout.trim();
62 }
63 catch ( Throwable e2 ) {
64 return null;
65 }
66 }
67 }
68 }
69
70 /**
71 * Sets file permissions on a given file so that it cannot be read by
72 * anyone other than its owner.
73 *
74 * @param file file whose permissions are to be altered
75 * @throws IOException if permissions cannot be changed
76 */
77 public void setPrivateRead( File file ) throws IOException {
78 if ( setPrivateReadReflect( file ) ) {
79 return;
80 }
81 else {
82 String[] privateReadArgs = getPrivateReadArgs( file );
83 if ( privateReadArgs != null ) {
84 exec( privateReadArgs );
85 }
86 else {
87 logger_.info( "No known way to set user-only read permissions"
88 + "; possible security implications"
89 + " on multi-user systems" );
90 }
91 }
92 }
93
94 /**
95 * Returns an array of words to pass to
96 * {@link java.lang.Runtime#exec(java.lang.String[])} in order
97 * to read an environment variable name.
98 * If null is returned, no way is known to do this with a system command.
99 *
100 * @param varname environment variable name to read
101 * @return exec args
102 */
103 protected abstract String[] getGetenvArgs( String varname );
104
105 /**
106 * Returns an array of words to pass to
107 * {@link java.lang.Runtime#exec(java.lang.String[])} in order
108 * to set permissions on a given file so that it cannot be read by
109 * anyone other than its owner.
110 * If null is returned, no way is known to do this with a system command.
111 *
112 * @param file file to alter
113 * @return exec args
114 */
115 protected abstract String[] getPrivateReadArgs( File file )
116 throws IOException;
117
118 /**
119 * Attempt to use the <code>File.setReadable()</code> method to set
120 * permissions on a file so that it cannot be read by anyone other
121 * than its owner.
122 *
123 * @param file file to alter
124 * @return true if the attempt succeeded, false if it failed because
125 * we are running the wrong version of java
126 * @throws IOException if there was some I/O failure
127 */
128 private static boolean setPrivateReadReflect( File file )
129 throws IOException {
130 try {
131 Method setReadableMethod =
132 File.class.getMethod( "setReadable",
133 new Class[] { boolean.class,
134 boolean.class, } );
135 boolean success =
136 ( setReadableMethod.invoke( file,
137 new Object[] { Boolean.FALSE,
138 Boolean.FALSE } )
139 .equals( Boolean.TRUE ) ) &&
140 ( setReadableMethod.invoke( file,
141 new Object[] { Boolean.TRUE,
142 Boolean.TRUE } )
143 .equals( Boolean.TRUE ) );
144 return success;
145 }
146 catch ( InvocationTargetException e1 ) {
147 Throwable e2 = e1.getCause();
148 if ( e2 instanceof IOException ) {
149 throw (IOException) e2;
150 }
151 else if ( e2 instanceof RuntimeException ) {
152 throw (RuntimeException) e2;
153 }
154 else {
155 throw (IOException) new IOException( e2.getMessage() )
156 .initCause( e2 );
157 }
158 }
159 catch ( NoSuchMethodException e ) {
160 // method only available at java 1.6+
161 return false;
162 }
163 catch ( IllegalAccessException e ) {
164 // not likely.
165 return false;
166 }
167 }
168
169 /**
170 * Attempts a {@java.lang.Runtime#exec(java.lang.String[])} with a given
171 * list of arguments. The output from stdout is returned as a string;
172 * in the case of error an IOException is thrown with a message giving
173 * the output from stderr.
174 *
175 * <p><strong>Note:</strong> do not use this for cases in which the
176 * output from stdout or stderr might be more than a few characters -
177 * blocking or deadlock is possible (see {@link java.lang.Process}).
178 *
179 * @param args array of words to pass to <code>exec</code>
180 * @return output from standard output
181 * @throws IOException with text from standard error if there is an error
182 */
183 private static String exec( String[] args ) throws IOException {
184 String argv = Arrays.asList( args ).toString();
185 logger_.info( "System exec: " + argv );
186 final Process process;
187 final StreamReader outReader;
188 final StreamReader errReader;
189 try {
190 process = Runtime.getRuntime().exec( args );
191 outReader = new StreamReader( process.getInputStream() );
192 errReader = new StreamReader( process.getErrorStream() );
193 outReader.start();
194 errReader.start();
195 process.waitFor();
196 }
197 catch ( InterruptedException e ) {
198 throw new IOException( "Exec failed: " + argv );
199 }
200 catch ( IOException e ) {
201 throw (IOException)
202 new IOException( "Exec failed: " + argv ).initCause( e );
203 }
204 return process.exitValue() == 0 ? outReader.getContent()
205 : errReader.getContent();
206 }
207
208 /**
209 * Returns a <code>Platform</code> instance for the current system.
210 *
211 * @return platform instance
212 */
213 public static Platform getPlatform() {
214 if ( instance_ == null ) {
215 instance_ = createPlatform();
216 }
217 return instance_;
218 }
219
220 /**
221 * Constructs a Platform for the current system.
222 *
223 * @return new platform
224 */
225 private static Platform createPlatform() {
226
227 // Is this reliable?
228 String osname = System.getProperty( "os.name" );
229 if ( osname.toLowerCase().startsWith( "windows" ) ||
230 osname.toLowerCase().indexOf( "microsoft" ) >= 0 ) {
231 return new WindowsPlatform();
232 }
233 else {
234 return new UnixPlatform();
235 }
236 }
237
238 /**
239 * Thread which reads the contents of a stream into a string buffer.
240 */
241 private static class StreamReader extends Thread {
242 private final InputStream in_;
243 private final StringBuffer sbuf_;
244
245 /**
246 * Constructor.
247 *
248 * @param in input stream
249 */
250 StreamReader( InputStream in ) {
251 super( "StreamReader" );
252 in_ = in;
253 sbuf_ = new StringBuffer();
254 setDaemon( true );
255 }
256
257 public void run() {
258 try {
259 for ( int c; ( c = in_.read() ) >= 0; ) {
260 sbuf_.append( (char) c );
261 }
262 in_.close();
263 }
264 catch ( IOException e ) {
265 }
266 }
267
268 /**
269 * Returns the content of the stream.
270 *
271 * @return content
272 */
273 public String getContent() {
274 return sbuf_.toString();
275 }
276 }
277
278 /**
279 * Platform implementation for Un*x-like systems.
280 */
281 private static class UnixPlatform extends Platform {
282
283 /**
284 * Constructor.
285 */
286 UnixPlatform() {
287 super( "Un*x" );
288 }
289
290 public File getHomeDirectory() {
291 return new File( System.getProperty( "user.home" ) );
292 }
293
294 protected String[] getGetenvArgs( String varname ) {
295 return new String[] { "printenv", varname, };
296 }
297
298 protected String[] getPrivateReadArgs( File file ) {
299 return new String[] { "chmod", "600", file.toString(), };
300 }
301 }
302
303 /**
304 * Platform implementation for Microsoft Windows-like systems.
305 */
306 private static class WindowsPlatform extends Platform {
307
308 /**
309 * Constructor.
310 */
311 WindowsPlatform() {
312 super( "MS Windows" );
313 }
314
315 protected String[] getPrivateReadArgs( File file ) throws IOException {
316
317 // No good way known. For a while I was using "attrib -R file",
318 // but this wasn't doing what was wanted. Bruno Rino has
319 // suggested "CALCS file /G %USERNAME%:F". Sounds kind of
320 // sensible, but requires user input (doable, but fiddly),
321 // and from my experiments on NTFS doesn't seem to have any
322 // discernable effect. As I understand it, it's unlikely to do
323 // anything on FAT (no ACLs). Given my general ignorance of
324 // MS OSes and file systems, I'm inclined to leave this for
325 // fear of inadvertently doing something bad.
326 return null;
327 }
328
329 public File getHomeDirectory() {
330 String userprofile = getEnv( "USERPROFILE" );
331 if ( userprofile != null && userprofile.trim().length() > 0 ) {
332 return new File( userprofile );
333 }
334 else {
335 return new File( System.getProperty( "user.home" ) );
336 }
337 }
338
339 public String[] getGetenvArgs( String varname ) {
340 return new String[] { "cmd", "/c", "echo", "%" + varname + "%", };
341 }
342 }
343 }