File Source: DCC.java
/*
P/P * Method: com.dmdirc.addons.dcc.DCC__static_init
*/
1 /*
2 * Copyright (c) 2006-2009 Chris Smith, Shane Mc Cormack, Gregory Holmes
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a copy
5 * of this software and associated documentation files (the "Software"), to deal
6 * in the Software without restriction, including without limitation the rights
7 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 * copies of the Software, and to permit persons to whom the Software is
9 * furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice shall be included in
12 * all copies or substantial portions of the Software.
13 *
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20 * SOFTWARE.
21 */
22
23 package com.dmdirc.addons.dcc;
24
25 import java.net.Socket;
26 import java.net.ServerSocket;
27 import java.io.IOException;
28 import java.util.concurrent.Semaphore;
29
30 /**
31 * This class handles the main "grunt work" of DCC, subclasses process the data
32 * received by this class.
33 *
34 * @author Shane 'Dataforce' McCormack
35 */
36 public abstract class DCC implements Runnable {
37 /** Address. */
38 protected long address = 0;
39 /** Port. */
40 protected int port = 0;
41 /** Socket used to communicate with. */
42 protected Socket socket;
43 /** The Thread in use for this. */
44 private volatile Thread myThread;
45 /** Are we already running? */
46 protected boolean running = false;
47 /** Are we a listen socket? */
48 protected boolean listen = false;
49
50 /**
51 * The current socket in use if this is a listen socket.
52 * This reference may be changed if and only if exactly one permit from the
53 * <code>serverSocketSem</code> and <code>serverListenignSem</code>
54 * semaphores is held by the thread doing the modification.
55 */
56 private ServerSocket serverSocket;
57
58 /**
59 * Semaphore to control write access to ServerSocket.
60 * If an object acquires a permit from the <code>serverSocketSem</code>, then
61 * <code>serverSocket</code> is <em>guaranteed</em> not to be externally
62 * modified until that permit is released, <em>unless</em> the object also
63 * acquires a permit from the <code>serverListeningSem</code>.
64 */
65 private final Semaphore serverSocketSem = new Semaphore(1);
66
67 /**
68 * Semaphore used when we're blocking waiting for connections.
69 * If an object acquires a permit from the <code>serverListeningSem</code>,
70 * then it is <em>guaranteed</em> that the {@link #run()} method is blocking
71 * waiting for incoming connections. In addition, it is <em>guaranteed</em>
72 * that the {@link #run()} method is holding the <code>serverSocketSem</code>
73 * permit, and it will continue holding that permit until it can reaquire
74 * the <code>serverListeningSem</code> permit.
75 */
76 private final Semaphore serverListeningSem = new Semaphore(0);
77
78 /**
79 * Creates a new instance of DCC.
80 */
81 public DCC() {
/*
P/P * Method: void com.dmdirc.addons.dcc.DCC()
*
* Postconditions:
* this.address == 0
* this.listen == 0
* this.port == 0
* this.running == 0
* this.serverListeningSem == &new Semaphore(DCC#2)
* this.serverSocketSem == &new Semaphore(DCC#1)
* new Semaphore(DCC#1) num objects == 1
* new Semaphore(DCC#2) num objects == 1
*/
82 super();
83 }
84
85 /**
86 * Connect this dcc.
87 */
88 public void connect() {
89 try {
/*
P/P * Method: void connect()
*
* Preconditions:
* (soft) init'ed(this.address)
* (soft) init'ed(this.port)
* (soft) init'ed(this.listen)
* (soft) this.serverSocket != null
*
* Postconditions:
* this.address == One-of{old this.address, 0}
* init'ed(this.address)
* possibly_updated(this.fileOut)
* this.handler.timeStarted == old this.handler.timeStarted
* possibly_updated(this.in)
* this.myThread == One-of{old this.myThread, &new Thread(connect#2)}
* possibly_updated(this.out)
* init'ed(this.port)
* this.socket == One-of{old this.socket, &new Socket(connect#1)}
* possibly_updated(this.transferFile)
* ...
*
* Test Vectors:
* this.listen: {0}, {1}
*/
90 if (listen) {
91 address = 0;
92 port = serverSocket.getLocalPort();
93 } else {
94 // socket = new Socket(longToIP(address), port, bindIP, 0);
95 socket = new Socket(longToIP(address), port);
96 socketOpened();
97 }
98 } catch (IOException ioe) {
99 socketClosed();
100 return;
101 }
102
103 myThread = new Thread(this);
104 myThread.start();
105 }
106
107 /**
108 * Start a listen socket rather than a connect socket.
109 *
110 * @throws IOException If the listen socket can't be created
111 */
112 public void listen() throws IOException {
/*
P/P * Method: void listen()
*
* Preconditions:
* this.serverSocketSem != null
* (soft) init'ed(this.address)
* (soft) init'ed(this.port)
*
* Postconditions:
* this.address == One-of{old this.address, 0}
* init'ed(this.address)
* possibly_updated(this.fileOut)
* this.handler.timeStarted == old this.handler.timeStarted
* possibly_updated(this.in)
* this.listen == 1
* new ServerSocket(listen#1) num objects == 1
* this.myThread == One-of{old this.myThread, &new Thread(connect#2)}
* possibly_updated(this.out)
* init'ed(this.port)
* ...
*/
113 serverSocketSem.acquireUninterruptibly();
114 serverSocket = new ServerSocket(0, 1);
115 serverSocketSem.release();
116
117 listen = true;
118 connect();
119 }
120
121 /**
122 * Start a listen socket rather than a connect socket, use a port from the
123 * given range.
124 *
125 * @param startPort Port to try first
126 * @param endPort Last port to try.
127 * @throws IOException If no sockets were available in the given range
128 */
129 public void listen(final int startPort, final int endPort) throws IOException {
/*
P/P * Method: void listen(int, int)
*
* Preconditions:
* (soft) endPort <= 232-2
* (soft) init'ed(this.address)
* (soft) init'ed(this.port)
* (soft) this.serverSocket != null
* (soft) startPort <= 232-2
* (soft) this.serverSocketSem != null
*
* Postconditions:
* this.address == One-of{old this.address, 0}
* init'ed(this.address)
* possibly_updated(this.fileOut)
* this.handler.timeStarted == old this.handler.timeStarted
* possibly_updated(this.in)
* this.listen == 1
* this.myThread == One-of{old this.myThread, &new Thread(connect#2)}
* possibly_updated(this.out)
* init'ed(this.port)
* this.serverSocket == One-of{old this.serverSocket, &new ServerSocket(listen#1)}
* ...
*/
130 listen = true;
131
132 for (int i = startPort; i <= endPort; ++i) {
133 try {
134 serverSocketSem.acquireUninterruptibly();
135 serverSocket = new ServerSocket(i, 1);
136 serverSocketSem.release();
137 // Found a socket we can use!
138 break;
139 } catch (IOException ioe) {
140 // Try next socket.
141 } catch (SecurityException se) {
142 // Try next socket.
143 }
144 }
145
146 if (serverSocket == null) {
147 throw new IOException("No available sockets in range "+startPort+":"+endPort);
148 } else {
149 connect();
150 }
151 }
152
153 /**
154 * This handles the socket to keep it out of the main thread
155 */
156 @Override
157 public void run() {
/*
P/P * Method: void run()
*
* Preconditions:
* init'ed(this.running)
* (soft) init'ed(this.serverSocket)
* (soft) init'ed(this.socket)
* (soft) init'ed(this.myThread)
* (soft) this.serverListeningSem != null
* (soft) this.serverSocketSem != null
*
* Presumptions:
* this.serverSocket@177 != null
*
* Postconditions:
* possibly_updated(this.fileOut)
* possibly_updated(this.handler.timeStarted)
* possibly_updated(this.handler.transferCount)
* possibly_updated(this.in)
* possibly_updated(this.out)
* possibly_updated(this.readSize)
* init'ed(this.running)
* init'ed(this.serverSocket)
* init'ed(this.socket)
* possibly_updated(this.transferFile)
* ...
*
* Test Vectors:
* this.running: {0}, {1}
*/
158 if (running) { return; }
159 running = true;
160 // handleSocket is implemented by sub classes, and should return false
161 // when the socket is closed.
162 Thread thisThread = Thread.currentThread();
163
164 while (myThread == thisThread) {
165 serverSocketSem.acquireUninterruptibly();
166
167 if (serverSocket == null) {
168 serverSocketSem.release();
169
170 if (!handleSocket()) {
171 close();
172 break;
173 }
174 } else {
175 try {
176 serverListeningSem.release();
177 socket = serverSocket.accept();
178 serverSocket.close();
179 socketOpened();
180 } catch (IOException ioe) {
181 socketClosed();
182 break;
183 } finally {
184 serverListeningSem.acquireUninterruptibly();
185 serverSocket = null;
186 serverSocketSem.release();
187 }
188 }
189 }
190 // Socket closed
191
192 thisThread = null;
193 running = false;
194 }
195
196 /**
197 * Called to close the socket
198 */
199 protected void close() {
/*
P/P * Method: void close()
*
* Preconditions:
* this.serverSocketSem != null
* (soft) init'ed(this.serverSocket)
* (soft) init'ed(this.socket)
* (soft) this.serverListeningSem != null
*
* Postconditions:
* possibly_updated(this.in)
* possibly_updated(this.out)
* this.serverSocket == null
* this.socket == null
*
* Test Vectors:
* java.net.ServerSocket:isClosed(...)@212: {1}, {0}
* java.net.Socket:isClosed(...)@227: {1}, {0}
* java.util.concurrent.Semaphore:tryAcquire(...)@202: {1}, {0}
*/
200 boolean haveSLS = false;
201
202 while (!serverSocketSem.tryAcquire() && !(haveSLS = serverListeningSem.tryAcquire())) {
203 try {
204 Thread.sleep(100);
205 } catch (InterruptedException ex) {
206 // Do we care? I doubt we do! Should be unchecked damnit.
207 }
208 }
209
210 if (serverSocket != null) {
211 try {
212 if (!serverSocket.isClosed()) {
213 serverSocket.close();
214 }
215 } catch (IOException ioe) { }
216 serverSocket = null;
217 }
218
219 if (haveSLS) {
220 serverListeningSem.release();
221 } else {
222 serverSocketSem.release();
223 }
224
225 if (socket != null) {
226 try {
227 if (!socket.isClosed()) {
228 socket.close();
229 }
230 } catch (IOException ioe) { }
231 socketClosed();
232 socket = null;
233 }
234 }
235
236 /**
237 * Called when the socket is first opened, before any data is handled.
238 */
/*
P/P * Method: void socketOpened()
*/
239 protected void socketOpened() { }
240
241 /**
242 * Called when the socket is closed, before the thread terminates.
243 */
/*
P/P * Method: void socketClosed()
*/
244 protected void socketClosed() { }
245
246 /**
247 * Check if this socket can be written to.
248 *
249 * @return True if the socket is writable, false otehrwise
250 */
251 public boolean isWriteable() {
/*
P/P * Method: bool isWriteable()
*
* Postconditions:
* return_value == 0
*/
252 return false;
253 }
254
255 /**
256 * Handle the socket.
257 *
258 * @return false when socket is closed, true will cause the method to be
259 * called again.
260 */
261 protected abstract boolean handleSocket();
262
263 /**
264 * Set the address to connect to for this DCC
265 *
266 * @param address Address as an int (Network Byte Order, as specified in the DCC CTCP)
267 * @param port Port to connect to
268 */
269 public void setAddress(final long address, final int port) {
/*
P/P * Method: void setAddress(long, int)
*
* Postconditions:
* this.address == address
* init'ed(this.address)
* this.port == port
* init'ed(this.port)
*/
270 this.address = address;
271 this.port = port;
272 }
273
274 /**
275 * Is this a listening socket
276 *
277 * @return True if this is a listening socket
278 */
279 public boolean isListenSocket() {
/*
P/P * Method: bool isListenSocket()
*
* Preconditions:
* init'ed(this.listen)
*
* Postconditions:
* return_value == this.listen
* init'ed(return_value)
*/
280 return listen;
281 }
282
283 /**
284 * Get the host this socket is listening on/connecting to
285 *
286 * @return The IP that this socket is listening on/connecting to.
287 */
288 public String getHost() {
/*
P/P * Method: String getHost()
*
* Preconditions:
* init'ed(this.address)
*
* Postconditions:
* java.lang.StringBuilder:toString(...)._tainted == 0
* return_value == &java.lang.StringBuilder:toString(...)
*/
289 return longToIP(address);
290 }
291
292 /**
293 * Get the port this socket is listening on/connecting to
294 *
295 * @return The port that this socket is listening on/connecting to.
296 */
297 public int getPort() {
/*
P/P * Method: int getPort()
*
* Preconditions:
* init'ed(this.port)
*
* Postconditions:
* return_value == this.port
* init'ed(return_value)
*/
298 return port;
299 }
300
301 /**
302 * Convert the given IP Address to a long
303 *
304 * @param ip Input IP Address
305 * @return ip as a long
306 */
307 public static long ipToLong(final String ip) {
/*
P/P * Method: long ipToLong(String)
*
* Preconditions:
* ip != null
*
* Postconditions:
* return_value == 0
*/
308 final String bits[] = ip.split("\\.");
309 if (bits.length > 3) {
310 return (Long.parseLong(bits[0]) << 24) + (Long.parseLong(bits[1]) << 16) + (Long.parseLong(bits[2]) << 8) + Long.parseLong(bits[3]);
311 }
312 return 0;
313 }
314
315 /**
316 * Convert the given long to an IP Address
317 *
318 * @param in Input long
319 * @return long as an IP
320 */
321 public static String longToIP(final long in) {
/*
P/P * Method: String longToIP(long)
*
* Postconditions:
* java.lang.StringBuilder:toString(...)._tainted == 0
* return_value == &java.lang.StringBuilder:toString(...)
*/
322 return ((in & 0xff000000) >> 24)+"."+((in & 0x00ff0000) >> 16)+"."+((in & 0x0000ff00) >> 8)+"."+(in & 0x000000ff);
323 }
324 }
SofCheck Inspector Build Version : 2.17854
| DCC.java |
2009-Jun-25 01:54:24 |
| DCC.class |
2009-Sep-02 17:04:14 |