Apache Mina SFTP: Mount Remote Sub-Directory instead of Filesystem Root - sftp

I would to use Apache SSHD to create an SFTP server and use SftpFileSystemProvider to mount a remote directory.
I successfully create the virtual file system with SftpFileSystemProvider following the documentation https://github.com/apache/mina-sshd/blob/master/docs/sftp.md#using-sftpfilesystemprovider-to-create-an-sftpfilesystem.
However I'm stuck when mouting remote directory even with the documentation https://github.com/apache/mina-sshd/blob/master/docs/sftp.md#configuring-the-sftpfilesystemprovider. It keeps mouting the root directory instead of the target one.
I tried:
adding the target directory into the sftp uri (not working)
getting new filesystem from path (not working)
Here is a quick example.
object Main:
class Events extends SftpEventListener
class Auth extends PasswordAuthenticator {
override def authenticate(username: String, password: String, session: ServerSession): Boolean = {
true
}
}
class FilesSystem extends VirtualFileSystemFactory {
override def createFileSystem(session: SessionContext): FileSystem = {
val uri = new URI("sftp://xxx:yyy#host/plop")
// val uri = SftpFileSystemProvider.createFileSystemURI("host", 22, "xxx", "yyy")
val fs = Try(FileSystems.newFileSystem(uri, Collections.emptyMap[String, Object](), new SftpFileSystemProvider().getClass().getClassLoader())) match {
case Failure(exception) =>
println("Failed to mount bucket")
println(exception.getMessage)
throw exception
case Success(filesSystem) =>
println("Bucket mounted")
filesSystem
}
//fs.getPath("plop").getFileSystem
fs
}
}
private val fs = new FilesSystem()
private val sftpSubSystem = new SftpSubsystemFactory.Builder().build()
sftpSubSystem.addSftpEventListener(new Events())
private val sshd: SshServer = SshServer.setUpDefaultServer()
sshd.setPort(22)
sshd.setHost("0.0.0.0")
sshd.setSubsystemFactories(Collections.singletonList(sftpSubSystem))
sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(Paths.get("hostkey.ser")))
sshd.setShellFactory(new InteractiveProcessShellFactory())
sshd.setCommandFactory(new ScpCommandFactory())
sshd.setFileSystemFactory(fs)
sshd.setPasswordAuthenticator(new Auth())
sshd.setSessionHeartbeat(HeartbeatType.IGNORE, Duration.ofSeconds(30L))
#main def m() = {
sshd.start()
while (sshd.isStarted) {
}
}
end Main
Am I missing something ?
SSHD version 2.8.0, SFTP protocol version 3, Scala3, Java11

I could be wrong, but, I think that these two ...
sshd.setShellFactory(new InteractiveProcessShellFactory())
sshd.setCommandFactory(new ScpCommandFactory())
sshd.setFileSystemFactory(fs)
... are redundant and this ...
private val sftpSubSystem = new SftpSubsystemFactory.Builder().build()
... needs to be made aware of the virtual file system.

Related

Corda - Specifying an app name for a mock network

If I call flowSession.getCounterpartyFlowInfo() from a unit test using MockNetwork, it returns FlowInfo(flowVersion=1, appName=<unknown>)
Here is my current MockNetwork configuration:
network = MockNetwork(
MockNetworkParameters(
cordappsForAllNodes = listOf(
TestCordapp.findCordapp("com.example.contract"),
TestCordapp.findCordapp("com.example.workflow")
),
networkParameters = testNetworkParameters(
minimumPlatformVersion = 5
)
)
)
Is there a way to specify the appName of an application running in a mock network?
I don't think there is a configuration for that. The appName is derived from the jar file name by removing the '.jar' extension.
For the MockNode, the packages are scanned and classes are loaded.
Here is how it's derived:
val Class<out FlowLogic<*>>.appName: String
get() {
val jarFile = location.toPath()
return if (jarFile.isRegularFile() && jarFile.toString().endsWith(".jar")) {
jarFile.fileName.toString().removeSuffix(".jar")
} else {
"<unknown>"
}
}

Symfony 4 : How to delete a file from folder using remove function of the filesystem component

I am trying to remove a file from folder using remove function of the filesystem component in Symfony 4.
Here is my code in the controller:
//Get old logo
$oldlogo = $employer->getLogo();
//If there is a old logo we need to detele it
if($oldlogo){
$filesystem = new Filesystem();
$path=$this->getTargetDirectory().'/public/uploads/logos/'.$oldlogo;
$filesystem->remove($path);
}
private $targetDirectory;
public function __construct($targetDirectory)
{
$this->targetDirectory = $targetDirectory;
}
public function getTargetDirectory()
{
return $this->targetDirectory;
}
Service.yalm:
parameters:
logos_directory: '%kernel.project_dir%/public/uploads/logos'
App\Controller\EmployerController:
arguments:
$targetDirectory: '%logos_directory%'
I have no error message but the file not deleted from the folder.
I using this solution:
in my services.yaml I add:
public_directory: '%kernel.project_dir%/public'
and in my controller I use
$filesystem = new Filesystem();
$path=$this->getParameter("public_directory").'/uploads/logos/'.$oldlogo;
$filesystem->remove($path);

Finishing a forked process blocks SBT with a custom output strategy

In SBT, I fork a Java process with:
class FilteredOutput extends FilterOutputStream(System.out) {
var buf = ArrayBuffer[Byte]()
override def write(b: Int) {
buf.append(b.toByte)
if (b == '\n'.toInt)
flush()
}
override def flush(){
if (buf.nonEmpty) {
val arr = buf.toArray
val txt = try new String(arr, "UTF-8") catch { case NonFatal(ex) ⇒ "" }
if (!txt.startsWith("pydev debugger: Unable to find real location for"))
out.write(arr)
buf.clear()
}
super.flush()
}
}
var process = Option.empty[Process]
process = Some(Fork.java.fork(ForkOptions(outputStrategy = new FilteredOutput()), Seq("my.company.MyClass")))
as a result of a custom task.
Later on, I terminate it with:
process.map { p =>
log info "Killing process"
p.destroy()
}
by means of another custom task.
The result is that SBT doesn't accept more input and gets blocked. Ctrl+C is the only way of restoring control back, but SBT dies as a consequence.
The problem has to do with the custom output strategy, that filters some annoying messages.
With jstack I haven't seen any deadlock.
SBT version 0.13.9.
The solution is to avoid closing System.out:
class FilteredOutput extends FilterOutputStream(System.out) {
var buf = ArrayBuffer[Byte]()
override def write(b: Int) {
...
}
override def flush(){
...
}
override def close() {}
}

How can I obtain the list of files in a project from VSIX(/MPF) code?

I am building a VSIX package to support a custom language in Visual Studio using MPF. I am in a custom designer and I need to find the files referenced in the project to resolve some dependencies. Where can I access this list?
I assume, that you´re using MPF to implement the project system for your custom language service. When doing so, you probably have a project root node which is derived from either ProjectNode or HierarchyNode...
If so, you could share the root node´s instance with the designer and try to find files by traversing the hierarchy, for instance...
internal class HierarchyVisitor
{
private readonly Func<HierarchyNode, bool> filterCallback;
public HierarchyVisitor(
Func<HierarchyNode, bool> filter)
{
this.filterCallback = filter;
}
public IEnumerable<HierarchyNode> Visit(
HierarchyNode node)
{
var stack = new Stack<HierarchyNode>();
stack.Push(node);
while (stack.Any())
{
HierarchyNode next = stack.Pop();
if (this.filterCallback(next))
{
yield return next;
}
for (
HierarchyNode child = next.FirstChild;
child != null;
child = child.NextSibling)
{
stack.Push(child);
}
}
}
}
To get a list of all nodes in the hierarchy, you could just do...
ProjectNode root = ...
var visitor = new HierarchyVisitor(x => true);
IEnumerable<HierarchyNode> flatList = visitor.Visit(root);
Or to filter for a certain file type, you could try something like this...
ProjectNode root = ...
var visitor = new HierarchyVisitor((HierarchyNode x) =>
{
const string XmlFileExtension = ".xml";
string path = new Uri(x.Url, UriKind.Absolut).LocalPath;
return string.Compare(
XmlFileExtension,
Path.GetFileExtension(path),
StringComparison.InvariantCultureIgnoreCase) == 0;
});
IEnumerable<HierarchyNode> xmlFiles = visitor.Visit(root);

Flex Crossdomain.xml file and FTP

How do I use crossdomain with ftp?
I am trying to do a "hello world" level test of FTP in Flex, but for three days now, I cannot overcome the issue with how to coerce flex into accepting my crossdomain policy - even for testing purposes.
Here is my code: The exact error text follows.
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" initialize="onInitialize()" layout="vertical">
<mx:Script>
<![CDATA[
import mx.utils.*;
import mx.controls.Alert;
private var fileRef:FileReference;
private var fileSize:uint;
private var fileContents:ByteArray;
//you need to initiate two scokets one for sending
//commands and second for sending data to FTP Server
//socket for sending commands to FTP
private var s:Socket
//responce from FTP
private var ftpResponce:String;
//socket for sending Data to FTP
private var dataChannelSocket:Socket;
//responce from FTP when sending Data to FTP
private var dataResponce:String;
//will hold the IP address of new socket created by FTP
private var dataChannelIP:String;
//will hold the Port number created by FTP
private var dataChannelPort:int;
private var user:String="I have the right user"; //FTP usernae
private var pass:String="the pw is correct"; //FTP Password
private function receiveReply(e:ProgressEvent):void {
ftpResponce=s.readUTFBytes(s.bytesAvailable)
var serverResponse:Number=Number(ftpResponce.substr(0, 3));
if (ftpResponce.indexOf('227') > -1) {
//get the ip from the string response
var temp:Object=ftpResponce.substring(ftpResponce.indexOf("(") + 1
, ftpResponce.indexOf(")"));
var dataChannelSocket_temp:Object=temp.split(",");
dataChannelIP=dataChannelSocket_temp.slice(0, 4).join(".");
dataChannelPort=parseInt(dataChannelSocket_temp[4]) * 256 +
int(dataChannelSocket_temp[5]);
//create new Data Socket based on dataChannelSocket and dataChannelSocket port
dataChannelSocket=new Socket(dataChannelIP, dataChannelPort);
dataChannelSocket.addEventListener(ProgressEvent.SOCKET_DATA, receiveData);
}
//few FTP Responce Codes
switch (String(serverResponse)) {
case "220":
//FTP Server ready responce
break;
case "331":
//User name okay, need password
break;
case "230":
//User logged in
break;
case "250":
//CWD command successful
break;
case "227":
//Entering Passive Mode (h1,h2,h3,h4,p1,p2).
break;
default:
}
//for more please
//http://http://www.altools.com/image/support/alftp/ALFTP_35_help/
//FTP_response_codes_rfc_959_messages.htm
traceData(ftpResponce);
}
private function receiveData(e:ProgressEvent):void {
dataResponce=dataChannelSocket.readUTFBytes(
dataChannelSocket.bytesAvailable);
traceData("dataChannelSocket_response—>" + dataResponce);
}
private function showError(e:IOErrorEvent):void {
traceData("Error—>" + e.text);
}
private function showSecError(e:SecurityErrorEvent):void {
traceData("SecurityError–>" + e.text);
}
private function onInitialize():void {
Security.loadPolicyFile("http://www.myUrlIsCorrectInMyProgram.com/crossdomain.xml");
}
private function createRemoteFile(fileName:String):void {
if (fileName != null && fileName != "") {
s.writeUTFBytes("STOR " + fileName + "\n");
s.flush();
}
}
private function sendData():void {
fileContents=fileRef.data as ByteArray;
fileSize=fileRef.size;
dataChannelSocket.writeBytes(fileContents, 0, fileSize);
dataChannelSocket.flush();
}
//initialize when application load
private function upLoad():void {
fileRef=new FileReference();
//some eventlistener
fileRef.addEventListener(Event.SELECT, selectEvent);
fileRef.addEventListener(Event.OPEN, onFileOpen);
//this function connects to the ftp server
connect();
//send the usernae and password
this.userName(user);
this.passWord(pass);
//if you want to change the directory for upload file
this.changeDirectory("/test/"); //directory name
//enter into PASSV Mode
s.writeUTFBytes("PASV\n");
s.flush();
}
private function onFileOpen(event:Event):void {
}
private function traceData(event:Object):void {
var tmp:String="================================\n";
ta.text+=event.toString() + "\n";
ta.verticalScrollPosition+=20;
}
private function ioErrorEvent(event:IOErrorEvent):void {
Alert.show("IOError:" + event.text);
}
private function selectEvent(event:Event):void {
btn_upload.enabled=true;
filename.text=fileRef.name;
fileRef.load();
}
private function uploadFile():void {
createRemoteFile(fileRef.name);
sendData();
}
private function connect():void {
s=new Socket("ftp.myUrlIsCorrectInMyProgram.com", 21);
s.addEventListener(ProgressEvent.SOCKET_DATA, receiveReply);
s.addEventListener(IOErrorEvent.IO_ERROR, showError);
s.addEventListener(SecurityErrorEvent.SECURITY_ERROR, showSecError);
s.addEventListener(Event.CONNECT, onSocketConnect);
s.addEventListener(Event.CLOSE, onSocketClose);
s.addEventListener(Event.ACTIVATE, onSocketAtivate);
}
private function onSocketConnect(evt:Event):void {
//traceData("OnSocketConnect–>"+evt.target.toString());
}
private function onSocketClose(evt:Event):void {
//traceData("onSocketClose–>"+evt.target.toString());
}
private function onSocketAtivate(evt:Event):void {
//traceData("onSocketAtivate–>"+evt.target.toString());
}
private function userName(str:String):void {
sendCommand("USER " + str);
}
private function passWord(str:String):void {
sendCommand("PASS " + str);
}
private function changeDirectory(str:String):void {
sendCommand("CWD " + str);
}
private function sendCommand(arg:String):void {
arg+="\n";
s.writeUTFBytes(arg);
s.flush();
}
]]>
[SWF] /FTP-debug/FTP.swf - 739,099 bytes after decompression
Warning: Domain www.myUrlIsCorrectInMyProgram.com does not specify a meta-policy. Applying default meta-policy 'master-only'. This configuration is deprecated. See http://www.adobe.com/go/strict_policy_files to fix this problem.
Warning: Timeout on xmlsocket://ftp.myUrlIsCorrectInMyProgram.com:843 (at 3 seconds) while waiting for socket policy file. This should not cause any problems, but see http://www.adobe.com/go/strict_policy_files for an explanation.
Warning: [strict] Ignoring policy file at xmlsocket://ftp.myUrlIsCorrectInMyProgram.com:21 due to incorrect syntax. See http://www.adobe.com/go/strict_policy_files to fix this problem.
* Security Sandbox Violation *
Connection to ftp.myUrlIsCorrectInMyProgram.com:21 halted - not permitted from http://localhost/FTP-debug/FTP.swf
Error: Request for resource at xmlsocket://ftp.myUrlIsCorrectInMyProgram.com:21 by requestor from http://localhost/FTP-debug/FTP.swf is denied due to lack of policy file permissions.
The "Information" at the URL's listed above is categorically unintelligable to me.
Please, someone help!
I also had the same issue but was able to fix it using the flash policy server that I downloaded from http://www.flash-resources.net/download.html.
I ran this on the same machine that I have my tomcat server installed and made the call
Security.loadPolicyFile("xmlsocket://:843");
from the application and it worked perfectly. No errors.
I also had the same issue but was able to fix it using the flash policy server that I downloaded from here.
I ran this on the same machine that I have my tomcat server installed and made the call
Security.loadPolicyFile("xmlsocket://Machine Name:843");
from the application and it worked perfectly. No errors.
Watch the typo around the Machine Name in the last post.
See the crossdomain spec:
http://learn.adobe.com/wiki/download/attachments/64389123/CrossDomain_PolicyFile_Specification.pdf?version=1
This covers the warning you have and can help you get this working.

Resources