/
AbstractFtpDoorV1.java
4591 lines (4078 loc) · 162 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.CharMatcher;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
import com.google.common.collect.Range;
import com.google.common.collect.Sets;
import com.google.common.net.InetAddresses;
import com.google.common.primitives.Ints;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
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.ProtocolFamily;
import java.net.Socket;
import java.net.SocketException;
import java.net.StandardProtocolFamily;
import java.net.UnknownHostException;
import java.nio.channels.ServerSocketChannel;
import java.security.NoSuchAlgorithmException;
import java.security.Principal;
import java.text.DateFormat;
import java.text.ParseException;
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.Iterator;
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.Executor;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import diskCacheV111.doors.FTPTransactionLog;
import diskCacheV111.doors.LineBasedInterpreter;
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.PnfsId;
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.CellIdentityAware;
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.NoRouteToCellException;
import dmg.util.CommandExitException;
import org.dcache.acl.enums.AccessType;
import org.dcache.auth.GidPrincipal;
import org.dcache.auth.GroupNamePrincipal;
import org.dcache.auth.LoginReply;
import org.dcache.auth.LoginStrategy;
import org.dcache.auth.Origin;
import org.dcache.auth.Subjects;
import static org.dcache.auth.attributes.Activity.*;
import org.dcache.auth.attributes.Activity;
import org.dcache.auth.attributes.HomeDirectory;
import org.dcache.auth.attributes.LoginAttribute;
import org.dcache.auth.attributes.Restrictions;
import org.dcache.auth.attributes.Restriction;
import org.dcache.auth.attributes.RootDirectory;
import org.dcache.cells.CellStub;
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.Args;
import org.dcache.util.AsynchronousRedirectedTransfer;
import org.dcache.util.Checksum;
import org.dcache.util.ChecksumType;
import org.dcache.util.Glob;
import org.dcache.util.NetLoggerBuilder;
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 com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.Iterables.*;
import static java.lang.Math.min;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import static org.dcache.acl.enums.AccessType.ACCESS_ALLOWED;
import static org.dcache.ftp.door.AnonymousPermission.ALLOW_ANONYMOUS_USER;
import static org.dcache.ftp.door.AnonymousPermission.FORBID_ANONYMOUS_USER;
import static org.dcache.namespace.FileAttribute.*;
import static org.dcache.util.NetLoggerBuilder.Level.INFO;
@Inherited
@Retention(RUNTIME)
@Target(METHOD)
@interface Help
{
String value();
}
enum AnonymousPermission
{
ALLOW_ANONYMOUS_USER, FORBID_ANONYMOUS_USER
}
/**
* Exception indicating an error during processing of an FTP command.
*/
class FTPCommandException extends Exception
{
/** FTP reply code. */
protected final int _code;
/** Human readable part of FTP reply. */
protected final 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 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, Exception cause)
{
super(reply, cause);
_code = 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
implements LineBasedInterpreter, CellMessageReceiver, CellCommandListener,
CellInfoProvider, CellMessageSender, CellIdentityAware
{
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractFtpDoorV1.class);
private static final Timer TIMER = new Timer("Performance marker timer", true);
private static final Logger ACCESS_LOGGER = LoggerFactory.getLogger("org.dcache.access.ftp");
protected FtpDoorSettings _settings;
protected InetSocketAddress _localSocketAddress;
protected InetSocketAddress _remoteSocketAddress;
protected CellAddressCore _cellAddress;
protected CellEndpoint _cellEndpoint;
protected Executor _executor;
/**
* Enumeration type for representing the connection mode.
*
* For PASSIVE transfers the client establishes the data
* connection.
*
* For ACTIVE transfers dCache establishes the data connection.
*
* When INVALID, the client most reset the mode.
*
* 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, INVALID
}
/**
* 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"),
CREATE("Create"),
TYPE("Type"),
UNIQUE("Unique"),
PERM("Perm"),
OWNER("UNIX.owner"),
GROUP("UNIX.group"),
MODE("UNIX.mode"),
// See http://www.iana.org/assignments/os-specific-parameters
CHANGE("UNIX.ctime"),
ACCESS("UNIX.atime");
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, 1, StandardProtocolFamily.INET),
IPV6(Inet6Address.class, 2, StandardProtocolFamily.INET6);
private Class<? extends InetAddress> _class;
private int _code;
private ProtocolFamily _protocolFamily;
Protocol(Class<? extends InetAddress> addressClass, int code, ProtocolFamily protocolFamily) {
_class = addressClass;
_code = code;
_protocolFamily = protocolFamily;
}
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;
}
public int getCode() {
return _code;
}
public ProtocolFamily getProtocolFamily() {
return _protocolFamily;
}
}
/**
* 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",
"MFMT",
"MFCT",
"MFF " + buildSemiColonList(Fact.MODIFY, Fact.CREATE, Fact.MODE),
"PASV AllowDelayed"
/*
* do not publish DCAU as supported feature. This will force
* some clients to always encrypt data channel
*/
// "DCAU"
};
private static final 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 static final int MAX_RETRIES_WRITE = 1;
/**
* Time stamp format as defined in RFC 3659.
*/
private final DateFormat TIMESTAMP_FORMAT =
new SimpleDateFormat("yyyyMMddHHmmss");
private static String buildSemiColonList(Fact... facts)
{
StringBuilder sb = new StringBuilder();
for (Fact fact : facts) {
sb.append(fact.getName()).append(';');
}
return sb.toString();
}
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;
protected InetAddress _internalInetAddress;
protected ServerSocketChannel _passiveModeServerSocket;
private final Map<String,Method> _methodDict =
new HashMap<>();
private final Map<String,Help> _helpDict = new HashMap<>();
protected int _commandCounter;
protected String _lastCommand = "<init>";
protected String _commandLine;
private boolean _isHello = true;
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 Restriction _doorRestriction;
protected Restriction _authz = Restrictions.denyAll();
protected FsPath _userRootPath = FsPath.ROOT;
protected FsPath _doorRootPath = FsPath.ROOT;
protected String _cwd = "/"; // Relative to _doorRootPath
protected FsPath _filepath; // Absolute filepath to the file to be renamed
protected PnfsId _fileId; // Id of the file to be renamed
private String _symlinkPath; // User-supplied path of new symlink
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;
/**
* Defines passive replies that have been delayed.
*/
private enum DelayedPassiveReply
{
/** No passive reply was delayed. */
NONE,
/** A 127/227 reply was delayed. */
PASV,
/** A 129/229 reply was delayed. */
EPSV
}
/**
* Whether the FTP client has enabled delayed passive.
*/
private boolean _allowDelayed;
/**
* Indicates whether and which passive reply has been delayed.
*/
private DelayedPassiveReply _delayedPassive = DelayedPassiveReply.NONE;
//These are the number of parallel streams to have
//when doing mode e transfers
protected int _parallel;
protected int _bufSize;
private final String _ftpDoorName;
private final String _tlogName;
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 AsynchronousRedirectedTransfer<GFtpTransferStartedMessage>
{
private final Mode _mode;
private final String _xferMode;
private final int _parallel;
private final InetSocketAddress _client;
private final int _bufSize;
private final DelayedPassiveReply _delayedPassive;
private final ProtocolFamily _protocolFamily;
private final int _version;
private final String _commandLine = AbstractFtpDoorV1.this._commandLine;
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;
public FtpTransfer(FsPath path,
long offset,
long size,
Mode mode,
String xferMode,
int parallel,
InetSocketAddress client,
int bufSize,
DelayedPassiveReply delayedPassive,
ProtocolFamily protocolFamily,
int version)
{
super(AbstractFtpDoorV1.this._executor,
AbstractFtpDoorV1.this._pnfs,
AbstractFtpDoorV1.this._subject,
AbstractFtpDoorV1.this._authz, path);
setDomainName(_cellAddress.getCellDomainName());
setCellName(_cellAddress.getCellName());
setClientAddress(_remoteSocketAddress);
setCheckStagePermission(_checkStagePermission);
setOverwriteAllowed(_settings.isOverwrite());
setPoolManagerStub(_poolManagerStub);
setPoolStub(_poolStub);
setBillingStub(_billingStub);
setAllocation(_allo);
setIoQueue(_settings.getIoQueueName());
_offset = offset;
_size = size;
_mode = mode;
_xferMode = xferMode;
_parallel = parallel;
_client = client;
_bufSize = bufSize;
_delayedPassive = delayedPassive;
_protocolFamily = protocolFamily;
_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, _internalInetAddress);
break;
case ACTIVE:
if (_settings.isProxyRequiredOnActive()) {
LOGGER.info("Creating adapter for active mode");
_adapter =
new ActiveAdapter(_internalInetAddress,
_client.getAddress().getHostAddress(),
_client.getPort());
}
break;
}
if (_adapter != null) {
_adapter.setMaxBlockSize(_settings.getMaxBlockSize());
_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 = !_settings.isProxyRequiredOnPassive() && _delayedPassive != DelayedPassiveReply.NONE;
/* 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,
_adapter.getInternalAddress(),
_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);
protocolInfo.setProtocolFamily(_protocolFamily);
if (_optCheckSumFactory != null) {
protocolInfo.setChecksumType(_optCheckSumFactory.getType().getName());
}
if (_checkSumFactory != null) {
protocolInfo.setChecksumType(_checkSumFactory.getType().getName());
}
return protocolInfo;
}
public void createTransactionLog()
{
String tlogRoot = _settings.getTlogRoot();
if (tlogRoot != null) {
LOGGER.info("Door will log ftp transactions to {}", tlogRoot);
_tLog = new FTPTransactionLog(tlogRoot);
if (_subject != null) {
try {
String user = AbstractFtpDoorV1.this.getUserName() + "(" +
Subjects.getUid(_subject) + "." +
Subjects.getPrimaryGid(_subject) + ")";
_tLog.begin(user, _tlogName, isWrite() ? "write" : "read",
_path.toString(), _remoteSocketAddress.getAddress());
} catch (NoSuchElementException | IllegalArgumentException e) {
LOGGER.error("Could not start tLog: " + e.getMessage());
}
}
}
}
public void abort(int replyCode, String msg)
{
abort(new FTPCommandException(replyCode, msg));
}
public void abort(int replyCode, String msg, Exception exception)
{
abort(new FTPCommandException(replyCode, msg, exception));
}
@Override
protected void onQueued()
{
setStatus("Mover " + getPool() + "/" + getMoverId());
}
@Override
protected synchronized void onRedirect(GFtpTransferStartedMessage redirect) throws FTPCommandException
{
if (redirect != null) {
if (_version != 2) {
LOGGER.error("Received unexpected GFtpTransferStartedMessage for {}", redirect.getPnfsId());
return;
}
if (!redirect.getPnfsId().equals(getPnfsId().getId())) {
LOGGER.error("GFtpTransferStartedMessage has wrong ID, expected {} but got {}", getPnfsId(), redirect.getPnfsId());
throw new FTPCommandException(451, "Transient internal failure");
}
if (redirect.getPassive() && _delayedPassive == DelayedPassiveReply.NONE) {
LOGGER.error("Pool unexpectedly volunteered to be passive");
throw new FTPCommandException(451, "Transient internal failure");
}
/* If passive X mode was requested, but the pool rejected
* it, then we have to fail for now. REVISIT: We should
* use the other adapter in this case.
*/
if (_mode == Mode.PASSIVE && !redirect.getPassive() && _xferMode.equals("X")) {
throw new FTPCommandException(504, "Cannot use passive X mode");
}
/* Determine the 127 response address to send back to the
* client. When the pool is passive, this is the address of
* the pool (and in this case we no longer need the
* adapter). Otherwise this is the address of the adapter.
*/
if (redirect.getPassive()) {
assert _delayedPassive != DelayedPassiveReply.NONE;
assert _mode == Mode.PASSIVE;
assert _adapter != null;
replyDelayedPassive(_commandLine, _delayedPassive,
redirect.getPoolAddress());
LOGGER.info("Closing adapter");
_adapter.close();
_adapter = null;
} else if (_mode == Mode.PASSIVE) {
replyDelayedPassive(_commandLine, _delayedPassive,
(InetSocketAddress) _passiveModeServerSocket.socket().getLocalSocketAddress());
}
}
if (_adapter != null) {
_adapter.start();
}
setStatus("Mover " + getPool() + "/" + getMoverId() + ": " +
(isWrite() ? "Receiving" : "Sending"));
reply(_commandLine, "150 Opening BINARY data connection for " + _path, false);
if (isWrite() && _xferMode.equals("E") && _settings.getPerformanceMarkerPeriod() > 0) {
long period = _settings.getPerformanceMarkerPeriodUnit().toMillis(
_settings.getPerformanceMarkerPeriod());
long timeout = period / 2;
_perfMarkerTask =
new PerfMarkerTask(_commandLine, getPoolAddress(), getMoverId(), timeout);
TIMER.schedule(_perfMarkerTask, period, period);
}
}
@Override
protected void onFinish() throws FTPCommandException
{
try {
ProxyAdapter adapter;
synchronized (this) {
adapter = _adapter;
}
if (adapter != null) {
LOGGER.info("Waiting for adapter to finish.");
adapter.join(300000); // 5 minutes
if (adapter.isAlive()) {
throw new FTPCommandException(451, "FTP proxy did not shut down");
} else if (_adapter.hasError()) {
throw new FTPCommandException(451, "FTP proxy failed: " + _adapter.getError());
}
LOGGER.debug("Closing adapter");
adapter.close();
}
synchronized (this) {
_adapter = null;
if (_perfMarkerTask != null) {
_perfMarkerTask.stop((GFtpProtocolInfo) getProtocolInfo());
}
if (_tLog != null) {
_tLog.middle(getFileAttributes().getSize());
_tLog.success();
_tLog = null;
}
}
notifyBilling(0, "");
setTransfer(null);
reply(_commandLine, "226 Transfer complete.");
} catch (InterruptedException e) {
throw new FTPCommandException(451, "FTP proxy was interrupted", e);
}
}
/**
* Aborts a transfer and performs all necessary cleanup steps,
* including killing movers and removing incomplete files. A
* failure message is send to the client. Both the reply code
* and reply message are logged as errors.
*
* If an exception is specified, then the error message in the
* exception is logged too and the exception itself is logged
* at a debug level. The intention is that an exception is
* only specified for exceptional cases, i.e. errors we would
* not expect to appear in normal use (potential
* bugs). Communication errors and the like should not be
* logged with an exception.
*/
@Override
protected synchronized void onFailure(Throwable t)
{
if (_perfMarkerTask != null) {
_perfMarkerTask.stop();
}
if (_adapter != null) {
_adapter.close();
_adapter = null;
if (_mode == Mode.PASSIVE) {
closePassiveModeServerSocket();
AbstractFtpDoorV1.this._mode = Mode.INVALID;
}