summaryrefslogtreecommitdiffstats
path: root/src/main/java/org/openslx/filetransfer/Transfer.java
blob: aebd3ce70544703363cc2e201fe3a01983019c60 (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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
package org.openslx.filetransfer;

import java.io.Closeable;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

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

import net.jpountz.lz4.LZ4Factory;

import org.apache.logging.log4j.Logger;
import org.openslx.util.Util;

public abstract class Transfer
{
	protected final Socket transferSocket;
	protected final DataOutputStream outStream;
	protected final DataInputStream dataFromServer;
	private String remoteError;
	private boolean shouldGetToken;
	protected boolean useCompression = true;

	protected final Logger log;

	protected final static LZ4Factory lz4factory = LZ4Factory.fastestInstance();

	/**
	 * Actively initiated transfer.
	 * 
	 * @param host Remote Host
	 * @param port Remote Port
	 * @param context SSL Context for encryption, null if plain
	 * @param log Logger to use
	 * @throws IOException
	 */
	protected Transfer( String host, int port, int readTimeoutMs, SSLContext context, Logger log ) throws IOException
	{
		this.log = log;
		// create socket.
		if ( context == null ) {
			transferSocket = new Socket();
		} else {
			SSLSocketFactory sslSocketFactory = context.getSocketFactory();
			transferSocket = sslSocketFactory.createSocket();
		}
		transferSocket.setSoTimeout( readTimeoutMs );
		transferSocket.connect( new InetSocketAddress( host, port ), 4000 );

		outStream = new DataOutputStream( transferSocket.getOutputStream() );
		dataFromServer = new DataInputStream( transferSocket.getInputStream() );
		shouldGetToken = false;
	}

	/**
	 * Passive transfer through incoming connection.
	 * 
	 * @param socket already connected socket to remote peer
	 * @param log Logger to use
	 * @throws IOException
	 */
	protected Transfer( Socket socket, Logger log ) throws IOException
	{
		this.log = log;
		transferSocket = socket;
		outStream = new DataOutputStream( transferSocket.getOutputStream() );
		dataFromServer = new DataInputStream( transferSocket.getInputStream() );
		shouldGetToken = true;
	}

	protected boolean sendRange( long startOffset, long endOffset )
	{
		try {
			sendKeyValuePair( "RANGE", startOffset + ":" + endOffset );
		} catch ( IOException e ) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	protected void sendUseCompression()
	{
		try {
			sendKeyValuePair( "COMPRESS", "true" );
		} catch ( IOException e ) {
			e.printStackTrace();
		}
	}

	/***********************************************************************/
	/**
	 * 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 );
			sendEndOfMeta();
		} catch ( IOException e ) {
			e.printStackTrace();
			this.close( e.toString() );
			return false;
		}
		return true;
	}

	protected boolean sendToken( String token )
	{
		try {
			sendKeyValuePair( "TOKEN", token );
		} catch ( IOException e ) {
			e.printStackTrace();
			this.close( e.toString() );
			return false;
		}
		return true;
	}

	public void sendDoneAndClose()
	{
		sendDone();
		sendEndOfMeta();
		close( "Transfer finished" );
	}

	protected boolean sendDone()
	{
		try {
			sendKeyValuePair( "DONE", "" );
		} catch ( IOException e ) {
			e.printStackTrace();
			this.close( e.toString() );
			return false;
		}
		return true;
	}

	protected boolean sendEndOfMeta()
	{
		try {
			outStream.writeShort( 0 );
			outStream.flush();
		} catch ( SocketTimeoutException e ) {
			log.error( "Error sending end of meta - socket timeout" );
			return false;
		} catch ( IOException e ) {
			log.error( "Error sending end of meta - " + e.toString() );
			return false;
		}
		return true;
	}

	/***********************************************************************/
	/**
	 * Method for reading MetaData, like TOKEN and FileRange.
	 * Split incoming bytes after first '=' and store value to specific
	 * variable.
	 * 
	 * @return map of meta data received, null on error
	 */
	protected MetaData readMetaData()
	{

		Map<String, String> entries = new HashMap<>();
		try {
			while ( true ) {
				String data = dataFromServer.readUTF();

				if ( data == null || data.length() == 0 )
					break; // End of meta data

				String[] splitted = data.split( "=", 2 );
				if ( splitted.length != 2 ) {
					log.warn( "Invalid key value pair received (" + data + ")" );
					continue;
				}
				if ( splitted[0].equals( "ERROR" ) )
					remoteError = splitted[1];
				if ( entries.containsKey( splitted[0] ) ) {
					log.warn( "Received meta data key " + splitted[0] + " when already received, ignoring!" );
				} else {
					entries.put( splitted[0], splitted[1] );
				}
			}
		} catch ( SocketTimeoutException ste ) {
			sendErrorCode( "timeout" );
			this.close( "Socket Timeout occured in readMetaData." );
			return null;
		} catch ( Exception e ) {
			this.close( "Exception occured in readMetaData: " + e.toString() );
			return null;
		}
		return new MetaData( entries );
	}

	private void sendKeyValuePair( String key, String value ) throws IOException
	{
		if ( outStream == null )
			return;
		try {
			outStream.writeUTF( key + "=" + value );
		} catch ( Exception e ) {
			this.close( e.getClass().getSimpleName() + " when sending KVP with key " + key );
		}
	}

	/***********************************************************************/
	/**
	 * Method for closing connection, if download has finished.
	 * 
	 */
	protected void close( String error, UploadStatusCallback callback, boolean sendToPeer )
	{
		close( error, callback, sendToPeer, null );
	}

	protected void close( String error, UploadStatusCallback callback, boolean sendToPeer, Exception e )
	{
		if ( error != null ) {
			if ( sendToPeer )
				sendErrorCode( error );
			if ( callback != null )
				callback.uploadError( error );
			log.info( "Closing with error '" + error + "'", e );
		}
		synchronized ( transferSocket ) {
			safeClose( dataFromServer, outStream, transferSocket );
		}
	}

	protected void close( String error )
	{
		close( error, null );
	}

	protected void close( String error, Exception e )
	{
		close( error, null, false, e );
	}

	public void cancel()
	{
		synchronized ( transferSocket ) {
			try {
				transferSocket.shutdownOutput();
			} catch ( Exception e ) {
				// Silence
			}
			try {
				transferSocket.shutdownInput();
			} catch ( Exception e ) {
				// Silence
			}
		}
	}

	/**
	 * 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()
	{
		synchronized ( transferSocket ) {
			return transferSocket.isConnected() && !transferSocket.isClosed()
					&& !transferSocket.isInputShutdown() && !transferSocket.isOutputShutdown();
		}
	}

	/**
	 * Get error string received from remote side, if any.
	 * 
	 * @return Error string, if received, or null.
	 */
	public String getRemoteError()
	{
		return remoteError;
	}

	/**
	 * Get transfer token, sent by remote peer that initiated connection.
	 * Call this ONLY if all of the following conditions are met:
	 * - this is an incoming transfer connection
	 * - you didn't call it before
	 * - you didn't call download or upload yet
	 * 
	 * @return The transfer token
	 */
	public String getToken()
	{
		if ( !shouldGetToken ) {
			log.error( "Invalid call of getToken. You either initiated the connection yourself, or you already called getToken before." );
			this.close( null );
			return null;
		}
		shouldGetToken = false;
		MetaData meta = readMetaData();
		if ( meta == null )
			return null;
		if (meta.peerWantsCompression()) {
			useCompression = true;
		}
		return meta.getToken();
	}

	/**
	 * Should we call getToken()? Used internally for detecting wrong usage of
	 * the transfer classes.
	 * 
	 * @return yes or no
	 */
	protected boolean shouldGetToken()
	{
		return shouldGetToken;
	}

	/**
	 * Close given stream, socket, anything closeable.
	 * Never throws any exception, if it's not closeable there's
	 * not much else we can do.
	 * 
	 * @param list one or more closeables. Pass one, many, or an array
	 */
	static protected void safeClose( Closeable... list )
	{
		Util.safeClose( list );
	}

	/**
	 * High level access to key-value-pairs.
	 */
	class MetaData
	{

		private Map<String, String> meta;

		private MetaData( Map<String, String> meta )
		{
			this.meta = meta;
		}

		/**
		 * Get transfer token, sent by remote peer that initiated connection.
		 * 
		 * @return The transfer token
		 */
		public String getToken()
		{
			return meta.get( "TOKEN" );
		}

		/**
		 * Check if remote peer set the DONE key, telling us the transfer is complete.
		 * 
		 * @return yes or no
		 */
		public boolean isDone()
		{
			return meta.containsKey( "DONE" );
		}

		/**
		 * Return range from this meta data class, or null
		 * if it doesn't contain a (valid) range key-value-pair.
		 * 
		 * @return The range instance
		 */
		public FileRange getRange()
		{
			if ( meta.containsKey( "RANGE" ) )
				return parseRange( meta.get( "RANGE" ) );
			return null;
		}

		/**
		 * Parse range in format START:END to {@link FileRange} instance.
		 * 
		 * @param range String representation of range
		 * @return {@link FileRange} instance of range, or null on error
		 */
		private FileRange parseRange( String range )
		{
			if ( range == null )
				return null;
			String parts[] = range.split( ":" );
			if ( parts.length != 2 )
				return null;
			long start, end;
			try {
				start = Long.parseLong( parts[0] );
				end = Long.parseLong( parts[1] );
			} catch ( Throwable t ) {
				log.warn( "Not parsable range: '" + range + "'" );
				return null;
			}
			if ( start >= end ) {
				log.warn( "Invalid range. Start >= end" );
				return null;
			}
			return new FileRange( start, end );
		}

		/**
		 * Peer indicated that it wants to use snappy compression.
		 */
		public boolean peerWantsCompression()
		{
			return meta.containsKey( "COMPRESS" );
		}

		@Override
		public String toString()
		{
			StringBuilder sb = new StringBuilder();
			for ( Entry<String, String> it : meta.entrySet() ) {
				if ( sb.length() != 0 ) {
					sb.append( ' ' );
				}
				sb.append( it.getKey() );
				sb.append( '=' );
				sb.append( it.getValue() );
			}
			return sb.toString();
		}

	}

}