summaryrefslogtreecommitdiffstats
path: root/src/main/java/org/openslx/filetransfer/Transfer.java
blob: a8c9a8af8015fadc7279e58a8eb43381bea285c0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
package org.openslx.filetransfer;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.nio.charset.StandardCharsets;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;

import org.apache.log4j.Logger;

public abstract class Transfer
{
	protected final SSLSocketFactory sslSocketFactory;
	protected final SSLSocket satelliteSocket;
	protected final DataOutputStream dataToServer;
	protected final DataInputStream dataFromServer;
	protected String TOKEN = null;
	protected long[] RANGE = null;
	protected String ERROR = null;

	protected final Logger log;

	protected Transfer( String ip, int port, SSLContext context, Logger log ) throws IOException
	{
		this.log = log;
		// create socket.
		sslSocketFactory = context.getSocketFactory();

		satelliteSocket = (SSLSocket)sslSocketFactory.createSocket( ip, port );
		satelliteSocket.setSoTimeout( 2000 ); // set socket timeout.

		dataToServer = new DataOutputStream( satelliteSocket.getOutputStream() );
		dataFromServer = new DataInputStream( satelliteSocket.getInputStream() );
	}

	protected Transfer( SSLSocket socket, Logger log ) throws IOException
	{
		this.log = log;
		satelliteSocket = socket;
		dataToServer = new DataOutputStream( satelliteSocket.getOutputStream() );
		dataFromServer = new DataInputStream( satelliteSocket.getInputStream() );
		sslSocketFactory = null;
	}

	protected boolean sendRange( long startOffset, long endOffset )
	{
		if ( RANGE != null ) {
			log.warn( "Range already set!" );
			return false;
		}
		try {
			sendKeyValuePair( "RANGE", startOffset + ":" + endOffset );
			RANGE[0] = startOffset;
			RANGE[1] = endOffset;
		} catch ( SocketTimeoutException ste ) {
			ste.printStackTrace();
			this.close( "Socket timeout occured ... close connection." );
		} catch ( IOException e ) {
			e.printStackTrace();
			readMetaData();
			if ( ERROR != null ) {
				if ( ERROR.equals( "timeout" ) ) {
					this.close( "Remote Socket timeout occured ... close connection." );
				}
			}
			log.info( "Sending RANGE in Uploader failed..." );
			return false;
		}
		return true;
	}

	/***********************************************************************/
	/**
	 * Method for sending token for identification from satellite to master.
	 * 
	 * @param token The token to send
	 */
	public boolean sendToken( String token )
	{
		if ( TOKEN != null ) {
			log.warn( "Trying to send token while a token is already set! Ignoring..." );
			return false;
		}
		TOKEN = token;
		try {
			sendKeyValuePair( "TOKEN", TOKEN );
		} catch ( SocketTimeoutException ste ) {
			ste.printStackTrace();
			this.close( "Socket timeout occured ... close connection." );
		} catch ( IOException e ) {
			e.printStackTrace();
			readMetaData();
			if ( ERROR != null ) {
				if ( ERROR.equals( "timeout" ) ) {
					this.close( "Remote Socket timeout occured ... close connection." );
				}
			}
			log.info( "Sending TOKEN in Downloader failed..." );
			return false;
		}
		return true;
	}

	/***********************************************************************/
	/**
	 * Method for reading incoming token for identification.
	 * 
	 */
	public String getToken()
	{
		return TOKEN;
	}

	private boolean parseRange( String range )
	{
		if ( range == null )
			return true;
		if ( RANGE != null ) {
			log.warn( "Warning: RANGE already set when trying to parse from " + range );
			return false;
		}
		String parts[] = range.split( ":", 2 );
		long ret[] = new long[ 2 ];
		try {
			ret[0] = Long.parseLong( parts[0] );
			ret[1] = Long.parseLong( parts[1] );
		} catch ( Throwable t ) {
			log.warn( "Not parsable range: '" + range + "'" );
			return false;
		}
		if ( ret[1] <= ret[0] ) {
			log.warn( "Invalid range. Start >= end" );
			return false;
		}
		RANGE = ret;
		return true;
	}

	/***********************************************************************/
	/**
	 * Getter for beginning of RANGE.
	 * 
	 * @return
	 */
	public long getStartOfRange()
	{
		if ( RANGE != null ) {
			return RANGE[0];
		}
		return -1;
	}

	/***********************************************************************/
	/**
	 * Getter for end of RANGE.
	 * 
	 * @return
	 */
	public long getEndOfRange()
	{
		if ( RANGE != null ) {
			return RANGE[1];
		}
		return -1;
	}

	/***********************************************************************/
	/**
	 * Method for returning difference of current Range.
	 * 
	 * @return
	 */
	public int getDiffOfRange()
	{
		return (int)Math.abs( getEndOfRange() - getStartOfRange() );
	}

	/***********************************************************************/
	/**
	 * Method for reading MetaData, like TOKEN and FileRange.
	 * Split incoming bytes after first '=' and store value to specific
	 * variable.
	 * 
	 * @return true on success, false if reading failed
	 */
	public boolean readMetaData()
	{
		try {
			while ( true ) {
				byte[] incoming = new byte[ 255 ];

				// First get length.
				int retLengthByte;
				retLengthByte = dataFromServer.read( incoming, 0, 1 );
				// If .read() didn't return 1, it was not able to read first byte.
				if ( retLengthByte != 1 ) {
					log.debug( " retLenthByte was not 1! retLengthByte = " + retLengthByte);
					this.close( "Error occured while reading Metadata." );
					return false;
				}

				int length = incoming[0] & 0xFF;
				log.debug( "length (downloader): " + length );

				if ( length == 0 )
					break;

				/*
				 * Read the next available bytes and split by '=' for
				 * getting TOKEN or RANGE.
				 */
				int hasRead = 0;
				while ( hasRead < length ) {
					int ret = dataFromServer.read( incoming, hasRead, length - hasRead );
					if ( ret == -1 ) {
						this.close( "Error occured while reading Metadata." );
						return false;
					}
					hasRead += ret;
				}

				String data = new String( incoming, 0, length, StandardCharsets.UTF_8 );

				String[] splitted = data.split( "=", 2 );
				if ( splitted.length != 2 ) {
					log.warn( "Invalid key value pair received (" + data + ")" );
					continue;
				}
				if ( splitted[0].equals( "TOKEN" ) ) {
					if ( TOKEN != null ) {
						this.close( "Received a token when a token is already set!" );
						return false;
					}
					TOKEN = splitted[1];
					log.debug( "TOKEN: " + TOKEN );
				}
				else if ( splitted[0].equals( "RANGE" ) ) {
					if ( !parseRange( splitted[1] ) ) {
						this.close( "Could not parse RANGE token" );
						return false;
					}
					log.debug( "RANGE: '" + splitted[1] + "'" );
				}
				else if ( splitted[0].equals( "ERROR" ) ) {
					ERROR = splitted[1];
					log.debug( "ERROR: " + ERROR );
				}
			}
		} catch ( SocketTimeoutException ste ) {
			ste.printStackTrace();
			sendErrorCode( "timeout" );
			this.close( "Socket Timeout occured in readMetaData." );
			return false;
		} catch ( Exception e ) {
			e.printStackTrace();
			this.close( e.toString() );
			return false;
		}
		return true;
	}

	private void sendKeyValuePair( String key, String value ) throws IOException
	{
		byte[] data = ( key + "=" + value ).getBytes( StandardCharsets.UTF_8 );
		dataToServer.writeByte( data.length );
		dataToServer.write( data );
	}

	/***********************************************************************/
	/**
	 * Method for sending error Code to server. For example in case of wrong
	 * token, send code for wrong token.
	 * 
	 */
	public Boolean sendErrorCode( String errString )
	{
		try {
			sendKeyValuePair( "ERROR", errString );
		} catch ( IOException e ) {
			e.printStackTrace();
			this.close( e.toString() );
			return false;
		}
		return true;
	}

	/***********************************************************************/
	/**
	 * Method for closing connection, if download has finished.
	 * 
	 */
	public void close( String error )
	{
		if ( error != null )
			log.info( error );
		try {
			if ( satelliteSocket != null )
				this.satelliteSocket.close();
			if ( dataFromServer != null )
				dataFromServer.close();
			if ( dataToServer != null )
				dataToServer.close();
		} catch ( IOException e ) {
			e.printStackTrace();
		}
	}

	/**
	 * Returns whether this transfer/connection is considered valid or usable,
	 * which means the socket is still properly connected to the remote peer.
	 * 
	 * @return true or false
	 */
	public boolean isValid()
	{
		return satelliteSocket.isConnected() && !satelliteSocket.isClosed()
				&& !satelliteSocket.isInputShutdown() && !satelliteSocket.isOutputShutdown();
	}

}