Beispiel #1
0
        public NtStatus SetEndOfFile(
            string filename,
            long length,
            DokanFileInfo info)
        {
            try
            {
                string      path    = GetPath(filename);
                ChannelSftp channel = GetChannel();
                SftpATTRS   attr    = channel.stat(path);

                attr.setSIZE(length);
                channel.setStat(path, attr);

                return(NtStatus.Success);
            }
            catch (SftpException)
            {
                return(NtStatus.Error);
            }
            catch (Exception e)
            {
                connectionError_ = true;
                Debug(e.ToString());
                Reconnect();
                return(NtStatus.Error);
            }
        }
Beispiel #2
0
 public int OpenDirectory(
     String filename,
     DokanFileInfo info)
 {
     Debug("OpenDirectory {0}", filename);
     try
     {
         string    path = GetPath(filename);
         SftpATTRS attr = GetChannel().stat(path);
         if (attr.isDir())
         {
             return(0);
         }
         else
         {
             return(-DokanNet.ERROR_PATH_NOT_FOUND); // TODO: return not directory?
         }
     }
     catch (SftpException e)
     {
         Debug(e.ToString());
         return(-DokanNet.ERROR_PATH_NOT_FOUND);
     }
     catch (Exception e)
     {
         connectionError_ = true;
         Debug(e.ToString());
         Reconnect();
         return(-DokanNet.ERROR_PATH_NOT_FOUND);
     }
 }
Beispiel #3
0
        private void expandSFTP(string path, TreeViewEventArgs e)
        {
            try
            {
                SftpGoToRoot();
                string fpath = sftproot + path;
                Log.Write(l.Debug, fpath);
                sftpc.cd(fpath);
                foreach (ChannelSftp.LsEntry lse in sftpc.ls("."))
                {
                    SftpATTRS attrs = lse.getAttrs();
                    if (lse.getFilename() != "." && lse.getFilename() != ".." && attrs.getPermissionsString().StartsWith("d"))
                    {
                        TreeNode ParentNode = new TreeNode();
                        ParentNode.Text = lse.getFilename();
                        e.Node.Nodes.Add(ParentNode);

                        TreeNode ChildNode = new TreeNode();
                        ChildNode.Text = lse.getFilename();
                        ParentNode.Nodes.Add(ChildNode);
                    }
                }
            }
            catch (Exception ex)
            {
                sftpc.quit();
                sftp_login();
                expandSFTP(path, e);
            }
        }
Beispiel #4
0
 public DokanError OpenDirectory(
     string filename,
     DokanFileInfo info)
 {
     Debug("OpenDirectory {0}", filename);
     try
     {
         string    path = GetPath(filename);
         SftpATTRS attr = GetChannel().stat(path);
         if (attr.isDir())
         {
             return(DokanError.ErrorSuccess);
         }
         else
         {
             return(DokanError.ErrorPathNotFound); // TODO: return not directory?
         }
     }
     catch (SftpException e)
     {
         Debug(e.ToString());
         return(DokanError.ErrorPathNotFound);
     }
     catch (Exception e)
     {
         connectionError_ = true;
         Debug(e.ToString());
         Reconnect();
         return(DokanError.ErrorPathNotFound);
     }
 }
Beispiel #5
0
 public int SetAllocationSize(string filename, long length, DokanFileInfo info)
 {
     try
     {
         string      path    = GetPath(filename);
         ChannelSftp channel = GetChannel();
         SftpATTRS   attr    = channel.stat(path);
         if (attr.getSize() < length)
         {
             attr.setSIZE(length);
         }
         channel.setStat(path, attr);
     }
     catch (SftpException)
     {
         return(-1);
     }
     catch (Exception e)
     {
         connectionError_ = true;
         Debug(e.ToString());
         Reconnect();
         return(-1);
     }
     return(0);
 }
Beispiel #6
0
        public int SetFileAttributes(
            String filename,
            FileAttributes attr,
            DokanFileInfo info)
        {
            Debug("SetFileAttributes {0}", filename);
            try
            {
                string      path    = GetPath(filename);
                ChannelSftp channel = GetChannel();
                SftpATTRS   sattr   = channel.stat(path);

                int permissions = sattr.getPermissions();
                Debug(" permissons {0} {1}", permissions, sattr.getPermissionsString());
                sattr.setPERMISSIONS(permissions);
                channel.setStat(path, sattr);
                return(0);
            }
            catch (SftpException)
            {
                return(-1);
            }
            catch (Exception e)
            {
                connectionError_ = true;
                Debug(e.ToString());
                Reconnect();
                return(-1);
            }
        }
Beispiel #7
0
        public int SetFileTime(
            String filename,
            DateTime ctime,
            DateTime atime,
            DateTime mtime,
            DokanFileInfo info)
        {
            Debug("SetFileTime {0}", filename);
            try
            {
                Debug(" filetime {0} {1} {2}", ctime.ToString(), atime.ToString(), mtime.ToString());

                string      path    = GetPath(filename);
                ChannelSftp channel = GetChannel();
                SftpATTRS   attr    = channel.stat(path);

                TimeSpan at = (atime - new DateTime(1970, 1, 1, 0, 0, 0));
                TimeSpan mt = (mtime - new DateTime(1970, 1, 1, 0, 0, 0));

                int uat = (int)at.TotalSeconds;
                int umt = (int)mt.TotalSeconds;

                if (mtime == DateTime.MinValue)
                {
                    umt = attr.getMTime();
                }
                if (atime == DateTime.MinValue)
                {
                    uat = attr.getATime();
                }

                attr.setACMODTIME(uat, umt);
                channel.setStat(path, attr);
                return(0);
            }
            catch (SftpException)
            {
                return(-1);
            }
            catch (Exception e)
            {
                connectionError_ = true;
                Debug(e.ToString());
                Reconnect();
                return(-1);
            }
        }
        internal SftpLogFileInfoSharpSSH(Uri uri)
        {
            this.uri            = uri;
            this.remoteFileName = uri.PathAndQuery;

            string userName = null;
            string password = null;

            if (uri.UserInfo != null && uri.UserInfo.Length > 0)
            {
                string[] split = uri.UserInfo.Split(new char[] { ':' });
                if (split.Length > 0)
                {
                    userName = split[0];
                }
                if (split.Length > 1)
                {
                    password = split[1];
                }
            }
            if (userName == null || password == null)
            {
                IList <string> userNames = new List <string>();
                LoginDialog    dlg       = new LoginDialog(uri.Host, userNames);
                dlg.UserName = userName;
                if (DialogResult.OK == dlg.ShowDialog())
                {
                    password = dlg.Password;
                    userName = dlg.UserName;
                }
            }

            UserInfo userInfo = new SharpSshUserInfo(userName, password);
            JSch     jsch     = new JSch();
            int      port     = uri.Port != -1 ? uri.Port : 22;
            Session  session  = jsch.getSession(userName, this.uri.Host, port);

            session.setUserInfo(userInfo);
            session.connect();
            Channel channel = session.openChannel("sftp");

            channel.connect();
            this.sftpChannel = (ChannelSftp)channel;
            SftpATTRS sftpAttrs = this.sftpChannel.lstat(this.remoteFileName);

            this.originalFileLength = sftpAttrs.getSize();
        }
Beispiel #9
0
 /// <exception cref="System.IO.IOException"></exception>
 internal override WalkRemoteObjectDatabase.FileStream Open(string path)
 {
     try
     {
         SftpATTRS a = this.ftp.Lstat(path);
         return(new WalkRemoteObjectDatabase.FileStream(this.ftp.Get(path), a.GetSize()));
     }
     catch (SftpException je)
     {
         if (je.id == ChannelSftp.SSH_FX_NO_SUCH_FILE)
         {
             throw new FileNotFoundException(path);
         }
         throw new TransportException("Can't get " + this.objectsPath + "/" + path + ": "
                                      + je.Message, je);
     }
 }
Beispiel #10
0
 private bool isExist(string path, DokanFileInfo info)
 {
     try
     {
         ChannelSftp channel = GetChannel();
         SftpATTRS   attr    = channel.stat(path);
         if (attr.isDir())
         {
             info.IsDirectory = true;
         }
         return(true);
     }
     catch (SftpException)
     {
         return(false);
     }
 }
Beispiel #11
0
 private string ReadPermission(string path)
 {
     try
     {
         SftpATTRS attr = GetChannel().stat(path);
         return(Convert.ToString(attr.getPermissions() & 0xFFF, 8) + "\n");
     }
     catch (SftpException)
     {
         return("");
     }
     catch (Exception)
     {
         connectionError_ = true;
         Reconnect();
         return("");
     }
 }
Beispiel #12
0
        public NtStatus GetFileInformation(
            string filename,
            out FileInformation fileinfo,
            DokanFileInfo info)
        {
            fileinfo = new FileInformation();
            try
            {
                string path = GetPath(filename);
                fileinfo.FileName = path;
                SftpATTRS attr = GetChannel().stat(path);

                fileinfo.Attributes = attr.isDir() ?
                                      FileAttributes.Directory :
                                      FileAttributes.Normal;

                if (DokanSSHFS.UseOffline)
                {
                    fileinfo.Attributes |= FileAttributes.Offline;
                }

                DateTime org = new DateTime(1970, 1, 1, 0, 0, 0, 0);

                fileinfo.CreationTime   = org.AddSeconds(attr.getMTime());
                fileinfo.LastAccessTime = org.AddSeconds(attr.getATime());
                fileinfo.LastWriteTime  = org.AddSeconds(attr.getMTime());
                fileinfo.Length         = attr.getSize();

                return(NtStatus.Success);
            }
            catch (SftpException)
            {
                return(NtStatus.Error);
            }
            catch (Exception e)
            {
                connectionError_ = true;
                Debug(e.ToString());
                Reconnect();
                return(NtStatus.Error);
            }
        }
Beispiel #13
0
 private bool WritePermission(
     string path,
     int permission)
 {
     try
     {
         Debug("WritePermission {0}:{1}", path, Convert.ToString(permission, 8));
         ChannelSftp channel = GetChannel();
         SftpATTRS   attr    = channel.stat(path);
         attr.setPERMISSIONS(permission);
         channel.setStat(path, attr);
     }
     catch (SftpException)
     {
     }
     catch (Exception e)
     {
         connectionError_ = true;
         Debug(e.ToString());
         Reconnect();
     }
     return(true);
 }
Beispiel #14
0
        public static void RunExample(String[] arg)
        {
            try
            {
                JSch jsch = new JSch();

                InputForm inForm = new InputForm();
                inForm.Text          = "Enter username@hostname";
                inForm.textBox1.Text = Environment.UserName + "@localhost";

                if (!inForm.PromptForInput())
                {
                    Console.WriteLine("Cancelled");
                    return;
                }
                String host = inForm.textBox1.Text;
                String user = host.Substring(0, host.IndexOf('@'));
                host = host.Substring(host.IndexOf('@') + 1);

                Session session = jsch.getSession(user, host, 22);

                // username and password will be given via UserInfo interface.
                UserInfo ui = new MyUserInfo();
                session.setUserInfo(ui);

                session.connect();

                Channel channel = session.openChannel("sftp");
                channel.connect();
                ChannelSftp c = (ChannelSftp)channel;

                Stream     ins  = Console.OpenStandardInput();
                TextWriter outs = Console.Out;

                ArrayList cmds = new ArrayList();
                byte[]    buf  = new byte[1024];
                int       i;
                String    str;
                int       level = 0;

                while (true)
                {
                    outs.Write("sftp> ");
                    cmds.Clear();
                    i = ins.Read(buf, 0, 1024);
                    if (i <= 0)
                    {
                        break;
                    }

                    i--;
                    if (i > 0 && buf[i - 1] == 0x0d)
                    {
                        i--;
                    }
                    //str=Util.getString(buf, 0, i);
                    //Console.WriteLine("|"+str+"|");
                    int s = 0;
                    for (int ii = 0; ii < i; ii++)
                    {
                        if (buf[ii] == ' ')
                        {
                            if (ii - s > 0)
                            {
                                cmds.Add(Util.getString(buf, s, ii - s));
                            }
                            while (ii < i)
                            {
                                if (buf[ii] != ' ')
                                {
                                    break;
                                }
                                ii++;
                            }
                            s = ii;
                        }
                    }
                    if (s < i)
                    {
                        cmds.Add(Util.getString(buf, s, i - s));
                    }
                    if (cmds.Count == 0)
                    {
                        continue;
                    }

                    String cmd = (String)cmds[0];
                    if (cmd.Equals("quit"))
                    {
                        c.quit();
                        break;
                    }
                    if (cmd.Equals("exit"))
                    {
                        c.exit();
                        break;
                    }
                    if (cmd.Equals("rekey"))
                    {
                        session.rekey();
                        continue;
                    }
                    if (cmd.Equals("compression"))
                    {
                        if (cmds.Count < 2)
                        {
                            outs.WriteLine("compression level: " + level);
                            continue;
                        }
                        try
                        {
                            level = int.Parse((String)cmds[1]);
                            Hashtable config = new Hashtable();
                            if (level == 0)
                            {
                                config.Add("compression.s2c", "none");
                                config.Add("compression.c2s", "none");
                            }
                            else
                            {
                                config.Add("compression.s2c", "zlib,none");
                                config.Add("compression.c2s", "zlib,none");
                            }
                            session.setConfig(config);
                        }
                        catch {}                       //(Exception e){}
                        continue;
                    }
                    if (cmd.Equals("cd") || cmd.Equals("lcd"))
                    {
                        if (cmds.Count < 2)
                        {
                            continue;
                        }
                        String path = (String)cmds[1];
                        try
                        {
                            if (cmd.Equals("cd"))
                            {
                                c.cd(path);
                            }
                            else
                            {
                                c.lcd(path);
                            }
                        }
                        catch (SftpException e)
                        {
                            Console.WriteLine(e.message);
                        }
                        continue;
                    }
                    if (cmd.Equals("rm") || cmd.Equals("rmdir") || cmd.Equals("mkdir"))
                    {
                        if (cmds.Count < 2)
                        {
                            continue;
                        }
                        String path = (String)cmds[1];
                        try
                        {
                            if (cmd.Equals("rm"))
                            {
                                c.rm(path);
                            }
                            else if (cmd.Equals("rmdir"))
                            {
                                c.rmdir(path);
                            }
                            else
                            {
                                c.mkdir(path);
                            }
                        }
                        catch (SftpException e)
                        {
                            Console.WriteLine(e.message);
                        }
                        continue;
                    }
                    if (cmd.Equals("chgrp") || cmd.Equals("chown") || cmd.Equals("chmod"))
                    {
                        if (cmds.Count != 3)
                        {
                            continue;
                        }
                        String path = (String)cmds[2];
                        int    foo  = 0;
                        if (cmd.Equals("chmod"))
                        {
                            byte[] bar = Util.getBytes((String)cmds[1]);
                            int    k;
                            for (int j = 0; j < bar.Length; j++)
                            {
                                k = bar[j];
                                if (k < '0' || k > '7')
                                {
                                    foo = -1; break;
                                }
                                foo <<= 3;
                                foo  |= (k - '0');
                            }
                            if (foo == -1)
                            {
                                continue;
                            }
                        }
                        else
                        {
                            try{ foo = int.Parse((String)cmds[1]); }
                            catch {}                           //(Exception e){continue;}
                        }
                        try
                        {
                            if (cmd.Equals("chgrp"))
                            {
                                c.chgrp(foo, path);
                            }
                            else if (cmd.Equals("chown"))
                            {
                                c.chown(foo, path);
                            }
                            else if (cmd.Equals("chmod"))
                            {
                                c.chmod(foo, path);
                            }
                        }
                        catch (SftpException e)
                        {
                            Console.WriteLine(e.message);
                        }
                        continue;
                    }
                    if (cmd.Equals("pwd") || cmd.Equals("lpwd"))
                    {
                        str  = (cmd.Equals("pwd")?"Remote":"Local");
                        str += " working directory: ";
                        if (cmd.Equals("pwd"))
                        {
                            str += c.pwd();
                        }
                        else
                        {
                            str += c.lpwd();
                        }
                        outs.WriteLine(str);
                        continue;
                    }
                    if (cmd.Equals("ls") || cmd.Equals("dir"))
                    {
                        String path = ".";
                        if (cmds.Count == 2)
                        {
                            path = (String)cmds[1];
                        }
                        try
                        {
                            ArrayList vv = c.ls(path);
                            if (vv != null)
                            {
                                for (int ii = 0; ii < vv.Count; ii++)
                                {
                                    object obj = vv[ii];
                                    if (obj is ChannelSftp.LsEntry)
                                    {
                                        outs.WriteLine(vv[ii]);
                                    }
                                }
                            }
                        }
                        catch (SftpException e)
                        {
                            Console.WriteLine(e.message);
                        }
                        continue;
                    }
                    if (cmd.Equals("lls") || cmd.Equals("ldir"))
                    {
                        String path = ".";
                        if (cmds.Count == 2)
                        {
                            path = (String)cmds[1];
                        }
                        try
                        {
                            //java.io.File file=new java.io.File(path);
                            if (!File.Exists(path))
                            {
                                outs.WriteLine(path + ": No such file or directory");
                                continue;
                            }
                            if (Directory.Exists(path))
                            {
                                String[] list = Directory.GetDirectories(path);
                                for (int ii = 0; ii < list.Length; ii++)
                                {
                                    outs.WriteLine(list[ii]);
                                }
                                continue;
                            }
                            outs.WriteLine(path);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e);
                        }
                        continue;
                    }
                    if (cmd.Equals("get") ||
                        cmd.Equals("get-resume") || cmd.Equals("get-append") ||
                        cmd.Equals("put") ||
                        cmd.Equals("put-resume") || cmd.Equals("put-append")
                        )
                    {
                        if (cmds.Count != 2 && cmds.Count != 3)
                        {
                            continue;
                        }
                        String p1 = (String)cmds[1];
                        //	  String p2=p1;
                        String p2 = ".";
                        if (cmds.Count == 3)
                        {
                            p2 = (String)cmds[2];
                        }
                        try
                        {
                            SftpProgressMonitor monitor = new MyProgressMonitor();
                            if (cmd.StartsWith("get"))
                            {
                                int mode = ChannelSftp.OVERWRITE;
                                if (cmd.Equals("get-resume"))
                                {
                                    mode = ChannelSftp.RESUME;
                                }
                                else if (cmd.Equals("get-append"))
                                {
                                    mode = ChannelSftp.APPEND;
                                }
                                c.get(p1, p2, monitor, mode);
                            }
                            else
                            {
                                int mode = ChannelSftp.OVERWRITE;
                                if (cmd.Equals("put-resume"))
                                {
                                    mode = ChannelSftp.RESUME;
                                }
                                else if (cmd.Equals("put-append"))
                                {
                                    mode = ChannelSftp.APPEND;
                                }
                                c.put(p1, p2, monitor, mode);
                            }
                        }
                        catch (SftpException e)
                        {
                            Console.WriteLine(e.message);
                        }
                        continue;
                    }
                    if (cmd.Equals("ln") || cmd.Equals("symlink") || cmd.Equals("rename"))
                    {
                        if (cmds.Count != 3)
                        {
                            continue;
                        }
                        String p1 = (String)cmds[1];
                        String p2 = (String)cmds[2];
                        try
                        {
                            if (cmd.Equals("rename"))
                            {
                                c.rename(p1, p2);
                            }
                            else
                            {
                                c.symlink(p1, p2);
                            }
                        }
                        catch (SftpException e)
                        {
                            Console.WriteLine(e.message);
                        }
                        continue;
                    }
                    if (cmd.Equals("stat") || cmd.Equals("lstat"))
                    {
                        if (cmds.Count != 2)
                        {
                            continue;
                        }
                        String    p1    = (String)cmds[1];
                        SftpATTRS attrs = null;
                        try
                        {
                            if (cmd.Equals("stat"))
                            {
                                attrs = c.stat(p1);
                            }
                            else
                            {
                                attrs = c.lstat(p1);
                            }
                        }
                        catch (SftpException e)
                        {
                            Console.WriteLine(e.message);
                        }
                        if (attrs != null)
                        {
                            outs.WriteLine(attrs);
                        }
                        else
                        {
                        }
                        continue;
                    }
                    if (cmd.Equals("version"))
                    {
                        outs.WriteLine("SFTP protocol version " + c.version());
                        continue;
                    }
                    if (cmd.Equals("help") || cmd.Equals("?"))
                    {
                        outs.WriteLine(help);
                        continue;
                    }
                    outs.WriteLine("unimplemented command: " + cmd);
                }
                session.disconnect();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Beispiel #15
0
        /// <summary>
        /// Initiates a new SCP response on sourceforge.net for downloading a file.
        /// </summary>
        /// <param name="uri">URI to download (includes username and password)</param>
        /// <param name="timeout">Timeout for this session</param>
        public ScpWebResponse(Uri uri, int timeout)
        {
            JSch jsch = new JSch();

            string[] userPass = uri.UserInfo.Split(':');
            if (userPass.Length != 2)
            {
                throw new WebException("Username and password information for sourceforge.net incomplete");
            }

            session = jsch.getSession(userPass[0], "frs.sourceforge.net", 22);

            // username and password will be given via UserInfo interface.
            //UserInfo ui = new UserInfo();
            //session.setUserInfo(ui);
            session.setPassword(userPass[1]);
            Hashtable hastable = new Hashtable();

            hastable.put("StrictHostKeyChecking", "no");
            session.setConfig(hastable);

            if (DbManager.Proxy != null)
            {
                session.setProxy(new ProxyHTTP(DbManager.Proxy.Address.Host, DbManager.Proxy.Address.Port));
            }

            try
            {
                session.connect(timeout);
            }
            catch (JSchException e)
            {
                if (e.Message == "Auth fail")
                {
                    throw new WebException("Invalid username or password for sourceforge");
                }
                throw;
            }

            // exec 'scp -f rfile' remotely
            string sfPath = GetSourceforgePath(uri.LocalPath);

            // Determine file modified date
            ChannelSftp channelSftp = (ChannelSftp)session.openChannel("sftp");

            channelSftp.connect();
            try
            {
                SftpATTRS attrs = channelSftp.lstat(sfPath);
                this.lastModified = RpcApplication.UnixToDotNet(attrs.getMTime());
            }
            catch (SftpException)
            {
                throw new WebException("The file \"" + sfPath + "\" could not be found.");
            }
            finally
            {
                channelSftp.disconnect();
            }

            String  command = "scp -f " + sfPath.Replace(" ", "\\ ");
            Channel channel = session.openChannel("exec");

            ((ChannelExec)channel).setCommand(command);

            // get I/O streams for remote scp
            Stream outs = channel.getOutputStream();
            Stream ins  = channel.getInputStream();

            channel.connect();

            byte[] buf = new byte[1024];

            // send '\0'
            buf[0] = 0; outs.Write(buf, 0, 1); outs.Flush();


            int c = checkAck(ins);

            if (c != 'C')
            {
                return;
            }

            // read '0644 '
            ins.Read(buf, 0, 5);

            while (true)
            {
                ins.Read(buf, 0, 1);
                if (buf[0] == ' ')
                {
                    break;
                }
                this.contentLength = this.contentLength * 10 + (buf[0] - '0');
            }

            for (int i = 0; ; i++)
            {
                ins.Read(buf, i, 1);
                if (buf[i] == (byte)0x0a)
                {
                    Util.getString(buf, 0, i);
                    break;
                }
            }

            this.responseUri = new Uri("scp://" + session.getHost() + sfPath);
            // send '\0'
            buf[0] = 0; outs.Write(buf, 0, 1); outs.Flush();

            this.responseStream = ins;
        }
Beispiel #16
0
 void setAttrs(SftpATTRS attrs)
 {
     this.attrs = attrs;
 }
Beispiel #17
0
 internal LsEntry(String filename, String longname, SftpATTRS attrs)
 {
     setFilename(filename);
     setLongname(longname);
     setAttrs(attrs);
 }
Beispiel #18
0
        private void fNewDir_Load(object sender, EventArgs e)
        {
            try
            {
                host      = ((frmMain)this.Tag).ftpHost();
                UN        = ((frmMain)this.Tag).ftpUser();
                pass      = ((frmMain)this.Tag).ftpPass();
                port      = ((frmMain)this.Tag).ftpPort();
                ftporsftp = ((frmMain)this.Tag).FTP();
                ftps      = ((frmMain)this.Tag).FTPS();
                ftpes     = ((frmMain)this.Tag).FTPES();
                ((frmMain)this.Tag).SetParent(host);

                if (ftporsftp)
                {
                    ftpc = new FtpClient(host, port);

                    if (ftps)
                    {
                        if (ftpes)
                        {
                            ftpc.SecurityProtocol = FtpSecurityProtocol.Tls1OrSsl3Explicit;
                        }
                        else
                        {
                            ftpc.SecurityProtocol = FtpSecurityProtocol.Tls1OrSsl3Implicit;
                        }
                        ftpc.ValidateServerCertificate += new EventHandler <ValidateServerCertificateEventArgs>(ftp_ValidateServerCertificate);
                    }

                    ftpc.Open(UN, pass);
                    Log.Write(l.Info, "Connected: " + ftpc.IsConnected.ToString());
                }
                else
                {
                    sftp_login();
                    sftproot = sftpc.pwd();
                }

                if (((frmMain)this.Tag).ftpParent() == "")
                {
                    tParent.Text = ((frmMain)this.Tag).ftpHost();
                }
                else
                {
                    tParent.Text = ((frmMain)this.Tag).ftpParent();
                }

                tPath.Text = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\FTPbox";

                Log.Write(l.Debug, ((frmMain)this.Tag).ftpParent() + " " + ((frmMain)this.Tag).ftpHost());

                treeView1.Nodes.Clear();

                TreeNode first = new TreeNode();
                first.Text = "/";
                treeView1.Nodes.Add(first);

                if (ftporsftp)
                {
                    foreach (FtpItem dir in ftpc.GetDirList())
                    {
                        if (dir.Name != "." && dir.Name != ".." && dir.ItemType == FtpItemType.Directory)
                        {
                            TreeNode ParentNode = new TreeNode();
                            ParentNode.Text = dir.Name;
                            treeView1.Nodes.Add(ParentNode);

                            TreeNode ChildNode = new TreeNode();
                            ChildNode.Text = dir.Name;
                            ParentNode.Nodes.Add(ChildNode);
                        }
                    }
                }
                else
                {
                    foreach (ChannelSftp.LsEntry lse in sftpc.ls("."))
                    {
                        SftpATTRS attrs = lse.getAttrs();
                        if (lse.getFilename() != "." && lse.getFilename() != ".." && attrs.getPermissionsString().StartsWith("d"))
                        {
                            TreeNode ParentNode = new TreeNode();
                            ParentNode.Text = lse.getFilename();
                            treeView1.Nodes.Add(ParentNode);

                            TreeNode ChildNode = new TreeNode();
                            ChildNode.Text = lse.getFilename();
                            ParentNode.Nodes.Add(ChildNode);
                        }
                    }
                }
                treeView1.SelectedNode = first;
                Set_Language(((frmMain)this.Tag).lang());
            }
            catch { this.Close(); }
        }
Beispiel #19
0
        public NtStatus CreateFile(
            string filename,
            DokanNet.FileAccess access,
            FileShare share,
            FileMode mode,
            FileOptions options,
            FileAttributes attributes,
            DokanFileInfo info)
        {
            if (info.IsDirectory)
            {
                switch (mode)
                {
                case FileMode.Open:
                    Debug("OpenDirectory {0}", filename);
                    try
                    {
                        string    path = GetPath(filename);
                        SftpATTRS attr = GetChannel().stat(path);
                        if (attr.isDir())
                        {
                            return(NtStatus.Success);
                        }
                        else
                        {
                            return(NtStatus.ObjectPathNotFound);    // TODO: return not directory?
                        }
                    }
                    catch (SftpException e)
                    {
                        Debug(e.ToString());
                        return(NtStatus.ObjectPathNotFound);
                    }
                    catch (Exception e)
                    {
                        connectionError_ = true;
                        Debug(e.ToString());
                        Reconnect();
                        return(NtStatus.ObjectPathNotFound);
                    }


                case FileMode.CreateNew:
                    Debug("CreateDirectory {0}", filename);
                    try
                    {
                        string      path    = GetPath(filename);
                        ChannelSftp channel = GetChannel();

                        channel.mkdir(path);
                        return(NtStatus.Success);
                    }
                    catch (SftpException e)
                    {
                        Debug(e.ToString());
                        return(NtStatus.Error);
                    }
                    catch (Exception e)
                    {
                        connectionError_ = true;
                        Debug(e.ToString());
                        Reconnect();
                        return(NtStatus.Error);    // TODO: more appropriate error code
                    }

                default:
                    Debug("Error FileMode invalid for directory {0}", mode);
                    return(NtStatus.Error);
                }
            }
            else
            {
                Debug("CreateFile {0}", filename);
                try
                {
                    string      path    = GetPath(filename);
                    ChannelSftp channel = GetChannel();

                    if (CheckAltStream(path))
                    {
                        return(NtStatus.Success);
                    }

                    switch (mode)
                    {
                    case FileMode.Open:
                    {
                        Debug("Open");
                        if (isExist(path, info))
                        {
                            return(NtStatus.Success);
                        }
                        else
                        {
                            return(NtStatus.ObjectNameNotFound);
                        }
                    }

                    case FileMode.CreateNew:
                    {
                        Debug("CreateNew");
                        if (isExist(path, info))
                        {
                            return(NtStatus.ObjectNameCollision);
                        }

                        Debug("CreateNew put 0 byte");
                        Tamir.SharpSsh.java.io.OutputStream stream = channel.put(path);
                        stream.Close();
                        return(NtStatus.Success);
                    }

                    case FileMode.Create:
                    {
                        Debug("Create put 0 byte");
                        Tamir.SharpSsh.java.io.OutputStream stream = channel.put(path);
                        stream.Close();
                        return(NtStatus.Success);
                    }

                    case FileMode.OpenOrCreate:
                    {
                        Debug("OpenOrCreate");

                        if (!isExist(path, info))
                        {
                            Debug("OpenOrCreate put 0 byte");
                            Tamir.SharpSsh.java.io.OutputStream stream = channel.put(path);
                            stream.Close();
                        }
                        return(NtStatus.Success);
                    }

                    case FileMode.Truncate:
                    {
                        Debug("Truncate");

                        if (!isExist(path, info))
                        {
                            return(NtStatus.ObjectNameNotFound);
                        }

                        Debug("Truncate put 0 byte");
                        Tamir.SharpSsh.java.io.OutputStream stream = channel.put(path);
                        stream.Close();
                        return(NtStatus.Success);
                    }

                    case FileMode.Append:
                    {
                        Debug("Append");

                        if (isExist(path, info))
                        {
                            return(NtStatus.Success);
                        }

                        Debug("Append put 0 byte");
                        Tamir.SharpSsh.java.io.OutputStream stream = channel.put(path);
                        stream.Close();
                        return(NtStatus.Success);
                    }

                    default:
                        Debug("Error unknown FileMode {0}", mode);
                        return(NtStatus.Error);
                    }
                }
                catch (SftpException e)
                {
                    Debug(e.ToString());
                    return(NtStatus.ObjectNameNotFound);
                }
                catch (Exception e)
                {
                    connectionError_ = true;
                    Debug(e.ToString());
                    Reconnect();
                    return(NtStatus.ObjectNameNotFound);
                }
            }
        }
Beispiel #20
0
        public virtual void FtpPoll(string fileName, int timeout, Dictionary <string, string> config)
        {
            fileName = fileName + ".asc";
            var printxml = config["printxml"] == "true";

            if (printxml)
            {
                Console.WriteLine("Polling for outbound result file.  Timeout set to " + timeout + "ms. File to wait for is " + fileName);
            }
            ChannelSftp channelSftp;

            var url            = config["sftpUrl"];
            var username       = config["sftpUsername"];
            var password       = config["sftpPassword"];
            var knownHostsFile = config["knownHostsFile"];

            var jsch = new JSch();

            jsch.setKnownHosts(knownHostsFile);

            var session = jsch.getSession(username, url);

            session.setPassword(password);

            try
            {
                session.connect();

                var channel = session.openChannel("sftp");
                channel.connect();
                channelSftp = (ChannelSftp)channel;
            }
            catch (SftpException e)
            {
                throw new CnpOnlineException("Error occured while attempting to establish an SFTP connection", e);
            }

            //check if file exists
            SftpATTRS sftpAttrs = null;
            var       stopWatch = new Stopwatch();

            stopWatch.Start();
            do
            {
                if (printxml)
                {
                    Console.WriteLine("Elapsed time is " + stopWatch.Elapsed.TotalMilliseconds);
                }
                try
                {
                    sftpAttrs = channelSftp.lstat("outbound/" + fileName);
                    if (printxml)
                    {
                        Console.WriteLine("Attrs of file are: " + sftpAttrs);
                    }
                }
                catch (SftpException e)
                {
                    if (printxml)
                    {
                        Console.WriteLine(e.message);
                    }
                    System.Threading.Thread.Sleep(30000);
                }
            } while (sftpAttrs == null && stopWatch.Elapsed.TotalMilliseconds <= timeout);

            // Close the connections.
            channelSftp.quit();
            session.disconnect();
        }
Beispiel #21
0
 Ssh_exp_name(String filename,
     String longname,
     SftpATTRS attrs)
 {
     setFilename(filename);
       setLongname(longname);
       setAttrs(attrs);
 }