/
AbstractFtpDoorV1.java
4019 lines (3548 loc) · 133 KB
/
AbstractFtpDoorV1.java
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
COPYRIGHT STATUS:
Dec 1st 2001, Fermi National Accelerator Laboratory (FNAL) documents and
software are sponsored by the U.S. Department of Energy under Contract No.
DE-AC02-76CH03000. Therefore, the U.S. Government retains a world-wide
non-exclusive, royalty-free license to publish or reproduce these documents
and software for U.S. Government purposes. All documents and software
available from this server are protected under the U.S. and Foreign
Copyright Laws, and FNAL reserves all rights.
Distribution of the software available from this server is free of
charge subject to the user following the terms of the Fermitools
Software Legal Information.
Redistribution and/or modification of the software shall be accompanied
by the Fermitools Software Legal Information (including the copyright
notice).
The user is asked to feed back problems, benefits, and/or suggestions
about the software to the Fermilab Software Providers.
Neither the name of Fermilab, the URA, nor the names of the contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
DISCLAIMER OF LIABILITY (BSD):
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL FERMILAB,
OR THE URA, OR THE U.S. DEPARTMENT of ENERGY, OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Liabilities of the Government:
This software is provided by URA, independent from its Prime Contract
with the U.S. Department of Energy. URA is acting independently from
the Government and in its own private capacity and is not acting on
behalf of the U.S. Government, nor as its contractor nor its agent.
Correspondingly, it is understood and agreed that the U.S. Government
has no connection to this software and in no manner whatsoever shall
be liable for nor assume any responsibility or obligation for any claim,
cost, or damages arising out of or resulting from the use of the software
available from this server.
Export Control:
All documents and software available from this server are subject to U.S.
export control laws. Anyone downloading information from this server is
obligated to secure any necessary Government licenses before exporting
documents or software obtained from this server.
*/
package org.dcache.ftp.door;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Predicate;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Range;
import com.google.common.collect.Sets;
import com.google.common.net.InetAddresses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import javax.security.auth.Subject;
import java.io.BufferedOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.channels.ServerSocketChannel;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import diskCacheV111.doors.AbstractInterruptibleLineBasedInterpreter;
import diskCacheV111.doors.FTPTransactionLog;
import diskCacheV111.util.CacheException;
import diskCacheV111.util.CheckStagePermission;
import diskCacheV111.util.ChecksumFactory;
import diskCacheV111.util.FileExistsCacheException;
import diskCacheV111.util.FileNotFoundCacheException;
import diskCacheV111.util.FsPath;
import diskCacheV111.util.NotDirCacheException;
import diskCacheV111.util.NotFileCacheException;
import diskCacheV111.util.PermissionDeniedCacheException;
import diskCacheV111.util.PnfsHandler;
import diskCacheV111.util.TimeoutCacheException;
import diskCacheV111.vehicles.DoorRequestInfoMessage;
import diskCacheV111.vehicles.DoorTransferFinishedMessage;
import diskCacheV111.vehicles.GFtpProtocolInfo;
import diskCacheV111.vehicles.GFtpTransferStartedMessage;
import diskCacheV111.vehicles.IoDoorEntry;
import diskCacheV111.vehicles.IoDoorInfo;
import diskCacheV111.vehicles.IoJobInfo;
import diskCacheV111.vehicles.ProtocolInfo;
import dmg.cells.nucleus.CDC;
import dmg.cells.nucleus.CellAddressCore;
import dmg.cells.nucleus.CellCommandListener;
import dmg.cells.nucleus.CellEndpoint;
import dmg.cells.nucleus.CellInfo;
import dmg.cells.nucleus.CellInfoProvider;
import dmg.cells.nucleus.CellMessage;
import dmg.cells.nucleus.CellMessageAnswerable;
import dmg.cells.nucleus.CellMessageReceiver;
import dmg.cells.nucleus.CellMessageSender;
import dmg.cells.nucleus.CellPath;
import dmg.cells.nucleus.NoRouteToCellException;
import dmg.util.Args;
import dmg.util.CommandExitException;
import org.dcache.acl.enums.AccessType;
import org.dcache.auth.LoginReply;
import org.dcache.auth.LoginStrategy;
import org.dcache.auth.Origin;
import org.dcache.auth.Subjects;
import org.dcache.auth.attributes.HomeDirectory;
import org.dcache.auth.attributes.LoginAttribute;
import org.dcache.auth.attributes.ReadOnly;
import org.dcache.auth.attributes.RootDirectory;
import org.dcache.cells.CellStub;
import org.dcache.cells.Option;
import org.dcache.ftp.proxy.ActiveAdapter;
import org.dcache.ftp.proxy.ProxyAdapter;
import org.dcache.ftp.proxy.SocketAdapter;
import org.dcache.namespace.ACLPermissionHandler;
import org.dcache.namespace.ChainedPermissionHandler;
import org.dcache.namespace.FileAttribute;
import org.dcache.namespace.FileType;
import org.dcache.namespace.PermissionHandler;
import org.dcache.namespace.PosixPermissionHandler;
import org.dcache.services.login.RemoteLoginStrategy;
import org.dcache.util.Checksum;
import org.dcache.util.ChecksumType;
import org.dcache.util.Glob;
import org.dcache.util.PortRange;
import org.dcache.util.Transfer;
import org.dcache.util.TransferRetryPolicy;
import org.dcache.util.list.DirectoryEntry;
import org.dcache.util.list.DirectoryListPrinter;
import org.dcache.util.list.ListDirectoryHandler;
import org.dcache.vehicles.FileAttributes;
import org.dcache.vehicles.PnfsListDirectoryMessage;
import static org.dcache.namespace.FileAttribute.*;
/**
* Exception indicating an error during processing of an FTP command.
*/
class FTPCommandException extends Exception
{
/** FTP reply code. */
protected int _code;
/** Human readable part of FTP reply. */
protected String _reply;
/**
* Constructs a command exception with the given ftp reply code and
* message. The message will be used for both the public FTP reply
* string and for the exception message.
*/
public FTPCommandException(int code, String reply)
{
this(code, reply, reply);
}
/**
* Constructs a command exception with the given ftp reply code,
* public and internal message.
*/
public FTPCommandException(int code, String reply, String msg)
{
super(msg);
_code = code;
_reply = reply;
}
/** Returns FTP reply code. */
public int getCode()
{
return _code;
}
/** Returns the public FTP reply string. */
public String getReply()
{
return _reply;
}
}
public abstract class AbstractFtpDoorV1
extends AbstractInterruptibleLineBasedInterpreter
implements CellMessageReceiver, CellCommandListener, CellInfoProvider, CellMessageSender
{
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractFtpDoorV1.class);
private static final Timer TIMER = new Timer("Performance marker timer", true);
protected InetSocketAddress _localAddress;
protected InetSocketAddress _remoteAddress;
protected CellAddressCore _cellAddress;
protected CellEndpoint _cellEndpoint;
/**
* Enumeration type for representing the connection mode.
*
* For PASSIVE transfers the client establishes the data
* connection.
*
* For ACTIVE transfers dCache establishes the data connection.
*
* Depending on the values of _isProxyRequiredOnActive and
* _isProxyRequiredOnPassive, the data connection with the client
* will be established either to an adapter (proxy) at the FTP
* door, or to the pool directly.
*/
protected enum Mode
{
PASSIVE, ACTIVE
}
/**
* Enumeration type for representing RFC 3659 facts.
*
* Note that the Globus Online service erroneously requires fact
* names to be capitalised, whereas RFC 3659 makes no such
* requirement. This bug has been reported:
*
* https://ggus.eu/tech/ticket_show.php?ticket=72601
*
* and, within Globus' internal tracker, as:
*
* http://jira.globus.org/browse/OPS-1
*/
protected enum Fact
{
SIZE("Size"),
MODIFY("Modify"),
TYPE("Type"),
UNIQUE("Unique"),
PERM("Perm"),
OWNER("UNIX.owner"),
GROUP("UNIX.group"),
MODE("UNIX.mode");
private final String _name;
Fact(String name)
{
_name = name;
}
public String getName()
{
return _name;
}
public static Fact find(String s)
{
for (Fact fact: values()) {
if (s.equalsIgnoreCase(fact.getName())) {
return fact;
}
}
return null;
}
}
/**
* Enumeration type for representing RFC 2428 protocol families.
*
* EPSV and EPRT commands
*/
protected enum Protocol {
IPV4(Inet4Address.class),
IPV6(Inet6Address.class);
private Class<? extends InetAddress> _class;
Protocol(Class<? extends InetAddress> addressClass) {
_class = addressClass;
}
public static Protocol fromAddress(InetAddress c) {
if (c.getClass().equals(Inet4Address.class)) {
return IPV4;
} else {
return IPV6;
}
}
/**
* find finds the matching enum element for a given protocol code
* @param code protocol code as defined in RFC2428: 1 for IPv4, 2 for IPv6
* @return Protocol (IPV4 or IPV6)
* @throws FTPCommandException if a code other than 1 or 2 is passed as argument
*/
public static Protocol find(String code) throws FTPCommandException {
switch (code) {
case "1": return IPV4;
case "2": return IPV6;
default: throw new FTPCommandException(522, "Unknown protocol family '"+code+". "+
"Known protocol families are 1: IPv4 and 2: IPv6, use one of (1,2)");
}
}
/**
* getAddressClass gets the address class associated with this enum element
* @return class type (Inet4Address or Inet6Address)
*/
public Class<? extends InetAddress> getAddressClass() {
return _class;
}
}
/**
* Feature strings returned when the client sends the FEAT
* command.
*/
private static final String[] FEATURES = {
"EOF", "PARALLEL", "MODE-E-PERF", "SIZE", "SBUF",
"ERET", "ESTO", "GETPUT", "MDTM",
"CKSUM " + buildChecksumList(), "MODEX",
"TVFS"
/*
* do not publish DCAU as supported feature. This will force
* some clients to always encrypt data channel
*/
// "DCAU"
};
private final static int DEFAULT_DATA_PORT = 20;
/**
* The maximum number of retries done on write. Must be one to
* avoid that empty replicas are left on pools.
*/
private final static int MAX_RETRIES_WRITE = 1;
/**
* Time stamp format as defined in RFC 3659.
*/
private final DateFormat TIMESTAMP_FORMAT =
new SimpleDateFormat("yyyyMMddHHmmss");
private static String buildChecksumList(){
String result = "";
int mod = 0;
for (ChecksumType type: ChecksumType.values()) {
result += type.getName() + ",";
mod = 1;
}
return result.substring(0, result.length() - mod);
}
/**
* Writer for control channel.
*/
protected PrintWriter _out;
/**
* Stub object for talking to the PNFS manager.
*/
protected PnfsHandler _pnfs;
/**
* Used for directory listing.
*/
protected ListDirectoryHandler _listSource;
/**
* User's Origin
*/
protected Origin _origin;
@Option(
name = "poolManager",
description = "Well known name of the pool manager",
defaultValue = "PoolManager"
)
protected String _poolManager;
@Option(
name = "pnfsManager",
description = "Well known name of the PNFS manager",
defaultValue = "PnfsManager"
)
protected String _pnfsManager;
@Option(name = "gplazma",
description = "Cell path to gPlazma",
defaultValue = "gPlazma")
protected String _gPlazma;
@Option(name = "billing",
description = "Cell path to billing",
defaultValue = "billing")
protected String _billing;
@Option(
name = "clientDataPortRange"
)
protected String _portRange;
/**
* Name or IP address of the interface on which we listen for
* connections from the pool in case an adapter is used.
*/
@Option(
name = "ftp-adapter-internal-interface",
description = "Interface to bind to"
)
protected String _local_host;
@Option(
name = "read-only",
description = "Whether to mark the FTP door read only",
defaultValue = "false"
)
protected boolean _readOnly;
@Option(
name = "maxRetries",
defaultValue = "3"
)
protected int _maxRetries;
@Option(
name = "poolManagerTimeout",
defaultValue = "1500"
)
protected int _poolManagerTimeout;
@Option(
name = "poolManagerTimeoutUnit",
defaultValue = "SECONDS"
)
protected TimeUnit _poolManagerTimeoutUnit;
@Option(
name = "pnfsTimeout",
defaultValue = "60"
)
protected int _pnfsTimeout;
@Option(
name = "pnfsTimeoutUnit",
defaultValue = "SECONDS"
)
protected TimeUnit _pnfsTimeoutUnit;
@Option(
name = "poolTimeout",
defaultValue = "300"
)
protected int _poolTimeout;
@Option(
name = "poolTimeoutUnit",
defaultValue = "SECONDS"
)
protected TimeUnit _poolTimeoutUnit;
@Option(
name = "retryWait",
defaultValue = "30",
unit = "seconds"
)
protected int _retryWait;
/**
* Size of the largest block used in the socket adapter in mode
* E. Blocks larger than this are divided into smaller blocks.
*/
@Option(
name = "maxBlockSize",
defaultValue = "131072",
unit = "bytes"
)
protected int _maxBlockSize;
@Option(
name = "deleteOnConnectionClosed",
description = "Whether to remove files on incomplete transfers",
defaultValue = "false"
)
protected boolean _removeFileOnIncompleteTransfer;
/**
* True if passive transfers have to be relayed through the door,
* i.e., the client must not connect directly to the pool.
*/
@Option(
name = "proxyPassive",
description = "Whether proxy is required for passive transfers",
required = true
)
protected boolean _isProxyRequiredOnPassive;
/**
* True if active transfers have to be relayed through the door.
*/
@Option(
name = "proxyActive",
description = "Whether proxy is required for active transfers",
required = true
)
protected boolean _isProxyRequiredOnActive;
/**
* File (StageConfiguration.conf) containing DNs and FQANs whose owner are allowed to STAGE files
* (i.e. allowed to copy file from dCache in case file is stored on tape but not on disk).
* /opt/d-cache/config/StageConfiguration.conf
* By default, such file does not exist, so that tape protection feature is not in use.
*/
@Option(
name = "stageConfigurationFilePath",
description = "File containing DNs and FQANs for which STAGING is allowed",
defaultValue = ""
)
protected String _stageConfigurationFilePath;
/**
* transferTimeout (in seconds)
*
* Is used for waiting for the end of transfer after the pool
* already notified us that the file transfer is finished. This is
* needed because we are using adapters. If timeout is 0, there is
* no timeout.
*/
@Option(
name = "transfer-timeout",
description = "Transfer timeout",
defaultValue = "0",
unit = "seconds"
)
protected int _transferTimeout;
@Option(
name = "tlog",
description = "Path to FTP transaction log"
)
protected String _tLogRoot;
/**
* wlcg demands that support for overwrite in srm and gridftp
* be off by default.
*/
@Option(
name = "overwrite",
defaultValue = "false"
)
protected boolean _overwrite;
@Option(
name = "io-queue"
)
protected String _ioQueueName;
@Option(
name = "maxStreamsPerClient",
description = "Maximum allowed streams per client in mode E",
defaultValue = "-1", // -1 = unlimited
unit = "streams"
)
protected int _maxStreamsPerClient;
@Option(
name = "defaultStreamsPerClient",
description = "Default number of streams per client in mode E",
defaultValue = "1",
unit = "streams"
)
protected int _defaultStreamsPerClient;
@Option(
name = "perfMarkerPeriod",
description = "Performance marker period",
defaultValue = "90"
)
protected long _performanceMarkerPeriod;
@Option(
name = "perfMarkerPeriodUnit",
description = "Performance marker period unit",
defaultValue = "SECONDS"
)
protected TimeUnit _performanceMarkerPeriodUnit;
protected final int _sleepAfterMoverKill = 1; // seconds
protected final int _spaceManagerTimeout = 5 * 60;
protected PortRange _passiveModePortRange;
protected ServerSocketChannel _passiveModeServerSocket;
private final Map<String,Method> _methodDict =
new HashMap<>();
protected int _commandCounter;
protected String _lastCommand = "<init>";
protected InetSocketAddress _clientDataAddress;
protected volatile Socket _dataSocket;
// added for the support or ERET with partial retrieve mode
protected long prm_offset = -1;
protected long prm_size = -1;
protected long _skipBytes;
protected boolean _confirmEOFs;
protected Subject _subject;
protected boolean _isUserReadOnly;
protected FsPath _pathRoot = new FsPath();
protected String _cwd = "/"; // Relative to _pathRoot
protected FsPath _filepath; // Absolute filepath to the file to be renamed
protected String _xferMode = "S";
protected CellStub _billingStub;
protected CellStub _poolManagerStub;
protected CellStub _poolStub;
protected CellStub _gPlazmaStub;
protected TransferRetryPolicy _readRetryPolicy;
protected TransferRetryPolicy _writeRetryPolicy;
/** Tape Protection */
protected CheckStagePermission _checkStagePermission;
protected LoginStrategy _loginStrategy;
/** Can be "mic", "conf", "enc", "clear". */
protected String _gReplyType = "clear";
protected Mode _mode = Mode.ACTIVE;
protected Protocol _preferredProtocol;
/**
* if _sessionAllPassive is set to true, all
* future transfers in the session will use
* passive mode. The flag is set by ftp_epsv.
*/
protected boolean _sessionAllPassive = false;
//These are the number of parallel streams to have
//when doing mode e transfers
protected int _parallel;
protected int _bufSize;
protected String ftpDoorName = "FTP";
protected Checksum _checkSum;
protected ChecksumFactory _checkSumFactory;
protected ChecksumFactory _optCheckSumFactory;
protected long _allo;
/** List of selected RFC 3659 facts. */
protected Set<Fact> _currentFacts = Sets.newHashSet(
Fact.SIZE, Fact.MODIFY, Fact.TYPE, Fact.UNIQUE, Fact.PERM,
Fact.OWNER, Fact.GROUP, Fact.MODE );
/**
* Encapsulation of an FTP transfer.
*/
protected class FtpTransfer extends Transfer
{
private final Mode _mode;
private final String _xferMode;
private final int _parallel;
private final InetSocketAddress _client;
private final int _bufSize;
private final boolean _reply127;
private final int _version;
private long _offset;
private long _size;
protected FTPTransactionLog _tLog;
/**
* Socket adapter used for the transfer.
*/
protected ProxyAdapter _adapter;
/**
* Task that periodically generates performance markers. May
* be null.
*/
protected PerfMarkerTask _perfMarkerTask;
/**
* True if the transfer was aborted.
*/
protected boolean _aborted;
/**
* True if the transfer completed successfully.
*/
protected boolean _completed;
public FtpTransfer(FsPath path,
long offset,
long size,
Mode mode,
String xferMode,
int parallel,
InetSocketAddress client,
int bufSize,
boolean reply127,
int version)
{
super(AbstractFtpDoorV1.this._pnfs,
AbstractFtpDoorV1.this._subject, path);
setDomainName(_cellAddress.getCellDomainName());
setCellName(_cellAddress.getCellName());
setClientAddress(_remoteAddress);
setCheckStagePermission(_checkStagePermission);
setOverwriteAllowed(_overwrite);
setPoolManagerStub(_poolManagerStub);
setPoolStub(_poolStub);
setBillingStub(_billingStub);
setAllocation(_allo);
_offset = offset;
_size = size;
_mode = mode;
_xferMode = xferMode;
_parallel = parallel;
_client = client;
_bufSize = bufSize;
_reply127 = reply127;
_version = version;
setTransfer(this);
}
public int getVersion()
{
return _version;
}
/**
* Create an adapter, if needed.
*
* Since a pool may reject to be passive, we need to set up an
* adapter even when we can use passive pools.
*/
private synchronized void createAdapter()
throws IOException
{
switch (_mode) {
case PASSIVE:
_adapter =
new SocketAdapter(_passiveModeServerSocket);
break;
case ACTIVE:
if (_isProxyRequiredOnActive) {
LOGGER.info("Creating adapter for active mode");
_adapter =
new ActiveAdapter(_passiveModePortRange,
_client.getAddress().getHostAddress(),
_client.getPort());
}
break;
}
if (_adapter != null) {
_adapter.setMaxBlockSize(_maxBlockSize);
_adapter.setModeE(_xferMode.equals("E"));
if (isWrite()) {
_adapter.setDirClientToPool();
} else {
_adapter.setDirPoolToClient();
}
}
}
/**
* Sanity check offset and size parameters. Must be done after
* the name space entry has been read because we need the size
* of the file first.
*/
public synchronized void checkAndDeriveOffsetAndSize()
throws FTPCommandException
{
long fileSize = getFileAttributes().getSize();
if (_offset == -1) {
_offset = 0;
}
if (_size == -1) {
_size = fileSize;
}
if (_offset < 0) {
throw new FTPCommandException(500, "prm offset is " + _offset);
}
if (_size < 0) {
throw new FTPCommandException(500, "prm_size is " + _size);
}
if (_offset + _size > fileSize) {
throw new FTPCommandException(500,
"invalid prm_offset=" + _offset
+ " and prm_size " + _size
+ " for file of size " + fileSize);
}
}
@Override
protected synchronized ProtocolInfo getProtocolInfoForPoolManager()
{
return new GFtpProtocolInfo("GFtp",
_version,
0,
_client,
_parallel,
_parallel,
_parallel,
_bufSize, 0, 0);
}
@Override
protected synchronized ProtocolInfo getProtocolInfoForPool()
{
/* We can only let the pool be passive if this has been
* enabled and if we can provide the address to the client
* using a 127 response.
*/
boolean usePassivePool = !_isProxyRequiredOnPassive && _reply127;
/* Construct protocol info. For backward compatibility, when
* an adapter could be used we put the adapter address into
* the protocol info.
*/
GFtpProtocolInfo protocolInfo;
if (_adapter != null) {
protocolInfo =
new GFtpProtocolInfo("GFtp",
_version, 0,
new InetSocketAddress(_local_host, _adapter.getPoolListenerPort()),
_parallel,
_parallel,
_parallel,
_bufSize,
_offset,
_size);
} else {
protocolInfo =
new GFtpProtocolInfo("GFtp",
_version, 0,
_client,
_parallel,
_parallel,
_parallel,
_bufSize,
_offset,
_size);
}
protocolInfo.setDoorCellName(getCellName());
protocolInfo.setDoorCellDomainName(getDomainName());
protocolInfo.setClientAddress(_client.getAddress().getHostAddress());
protocolInfo.setPassive(usePassivePool);
protocolInfo.setMode(_xferMode);
if (_optCheckSumFactory != null) {
protocolInfo.setChecksumType(_optCheckSumFactory.getType().getName());
}
if (_checkSumFactory != null) {
protocolInfo.setChecksumType(_checkSumFactory.getType().getName());
}
return protocolInfo;
}
public void createTransactionLog()
{
if (_tLogRoot != null) {
LOGGER.info("Door will log ftp transactions to {}", _tLogRoot);
_tLog = new FTPTransactionLog(_tLogRoot);
startTlog(_tLog, _path.toString(), isWrite() ? "write" : "read");
}
}
public void setChecksum(Checksum checksum)
throws CacheException
{
if (checksum != null) {
setStatus("PnfsManager: Setting checksum");
try {
_pnfs.setChecksum(getPnfsId(), checksum);
} finally {
setStatus(null);
}
}
}
protected synchronized void startTransfer()
{
if (_adapter != null) {
_adapter.start();
}
setStatus("Mover " + getPool() + "/" + getMoverId() + ": " +
(isWrite() ? "Receiving" : "Sending"));
reply("150 Opening BINARY data connection for " + _path, false);
if (isWrite() && _xferMode.equals("E") && _performanceMarkerPeriod > 0) {
long period = _performanceMarkerPeriodUnit.toMillis(_performanceMarkerPeriod);
long timeout = period / 2;
_perfMarkerTask =
new PerfMarkerTask(getPoolAddress(), getMoverId(), timeout);
TIMER.schedule(_perfMarkerTask, period, period);
}
}
@Override
public synchronized void startMover(String queue, long timeout)
throws CacheException, InterruptedException
{
super.startMover(queue, timeout);
setStatus("Mover " + getPool() + "/" + getMoverId());
if (_version == 1) {
startTransfer();
}
}
public synchronized void transferStarted(CellMessage envelope,
GFtpTransferStartedMessage message)
{
try {
if (_aborted || _completed) {
return;
}
if (_version != 2) {
LOGGER.error("Received unexpected GFtpTransferStartedMessage for {} from {}", message
.getPnfsId(), envelope.getSourcePath());
return;
}
if (!message.getPnfsId().equals(getPnfsId().getId())) {
LOGGER.error("GFtpTransferStartedMessage has wrong ID, expected {} but got {}", getPnfsId(), message
.getPnfsId());
throw new FTPCommandException(451, "Transient internal failure");
}
if (message.getPassive() && !_reply127) {