Security Checks on I/O
Security Checks on I O
One of the original fears about downloading executable content like applets from the Internet was that a hostile applet could erase your hard disk or read your Quicken files. Nothing has happened to change that since Java was introduced. This is why Java applets run under the control of a security manager that checks each operation an applet performs to prevent potentially hostile acts.
The security manager is particularly careful about I/O operations. For the most part, the checks are related to these questions:
- Can the program read a particular file?
- Can the program write a particular file?
- Can the program delete a particular file?
- Can the program determine whether a particular file exists?
- Can the program make a network connection to a particular host?
- Can the program accept an incoming connection from a particular host?
The short answer to all these questions when the program is an applet is "No, it cannot." A slightly more elaborate answer would specify a few exceptions. Applets can make network connections to the host they came from; applets can read a few very specific files that contain information about the Java environment; and trusted applets may sometimes run without these restrictions. But for almost all practical purposes, the answer is almost always no.
Because of these security issues, you need to be careful when using code fragments and examples from this book in an applet. Everything shown here works when run in an application, but when run in an applet, it may fail with a SecurityException. It's not always obvious whether a particular method or class will cause problems. The write( ) method of BufferedOutputStream, for instance, is completely safe when the ultimate destination is a byte array. However, that same write( ) method will throw an exception when the destination is a file. An attempt to open a connection to a web server may succeed or fail depending on whether or not the web server you're connecting to is the same one the applet came from.
Consequently, this book focuses very much on applications. There is very little I/O that can be done from an applet without running afoul of the security manager. The problem may not always be obviousnot all web browsers properly report security exceptionsbut it is there. If you can make an applet work when it's run as a standalone application and you cannot get it to work inside a web browser, the problem is likely a conflict with the browser's security manager.