Giter Site home page Giter Site logo

ume05rw / sharpcifs.std Goto Github PK

View Code? Open in Web Editor NEW
85.0 8.0 34.0 613 KB

SharpCifs.Std is a port from SharpCifs to .NET Standard. Original SharpCifs: https://github.com/zinkpad/SharpCifs

License: GNU Lesser General Public License v2.1

C# 100.00%
xamarin smb jcifs csproj

sharpcifs.std's People

Contributors

anat0li avatar mdonoughe avatar mukmyash avatar ume05rw avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sharpcifs.std's Issues

Comapibility issue with .NET Core 2.0 Preview 2

Hello,
Thanks for this library it saved me a lot of time!

When connecting to a samba share I get this error as soon as I call ListFiles (or any other method). This only happens with dotnetcore 2.0-preview2 and the same code works without any issue on dotnetcore 1.1

Failed to connect: [172.22.55.90]
   at SharpCifs.Smb.SmbTransport.Connect()
   at SharpCifs.Smb.SmbTree.TreeConnect(ServerMessageBlock andx, ServerMessageBlock andxResponse)
   at SharpCifs.Smb.SmbFile.DoConnect()
   at SharpCifs.Smb.SmbFile.Connect()
   at SharpCifs.Smb.SmbFile.Connect0()
   at SharpCifs.Smb.SmbFile.ResolveDfs(ServerMessageBlock request)
   at SharpCifs.Smb.SmbFile.Send(ServerMessageBlock request, ServerMessageBlock response)
   at SharpCifs.Smb.SmbFile.DoFindFirstNext(List`1 list, Boolean files, String wildcard, Int32 searchAttributes, ISmbFilenameFilter fnf, ISmbFileFilter ff)
   at SharpCifs.Smb.SmbFile.DoEnum(List`1 list, Boolean files, String wildcard, Int32 searchAttributes, ISmbFilenameFilter fnf, ISmbFileFilter ff)
   at SharpCifs.Smb.SmbFile.ListFiles(String wildcard, Int32 searchAttributes, ISmbFilenameFilter fnf, ISmbFileFilter ff)
   at SharpCifs.Smb.SmbFile.ListFiles(String wildcard)

I have also tried to set client IP by using

Config.SetProperty("jcifs.smb.client.laddr", ip);

but the issue persists.

Any advice?
Best Regards

SmbTransport.ClearCachedConnections with force=true leads to InvalidOperationException

When calling SmbTransport.ClearCachedConnections (true) with force=true, we experienced an InvalidOperationException:

System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
at System.Collections.Generic.List`1.Enumerator.MoveNextRare()
at SharpCifs.Smb.SmbTransport.ClearCachedConnections(Boolean force)

Here is the code: SmbTransport.ClearCachedConnections. The code enumerates over that collection (SmbConstants.Connections), and then tries to remove an element from it (with force=true), which gives it the InvalidOperationException. At least that is what stackoverflow suggests "You can't remove items from the same list you're using in the foreach, you'll get an exception (System.InvalidOperationException)."
Otherwise this other stack overflow suggests that the collection itself is modified by another thread, but the code above has a lock on the collection, so I think it is the one responsible stack overflow

So, it seems if we changed it to use an index-based for loop instead, we could get around this problem.

连接Cifs服务器的时候,报错Failed to connect: 0.0.0.0<00>/192.168.1.27

I use the demo on the website and then the direct link appears to be so wrong, the reason why this error is possible??

at SharpCifs.Smb.SmbTransport.Connect()
at SharpCifs.Smb.SmbTree.TreeConnect(ServerMessageBlock andx, ServerMessageBlock andxResponse)
at SharpCifs.Smb.SmbFile.DoConnect()
at SharpCifs.Smb.SmbFile.Connect()
at SharpCifs.Smb.SmbFile.Connect0()
at SharpCifs.Smb.SmbFile.QueryPath(String path, Int32 infoLevel)
at SharpCifs.Smb.SmbFile.Exists()
at DsSmartCloud.OssDao.CifsGlusterfsRepositily.PushStreamToGlusterFs(String appid, Byte[] stream, String uploadid, String name, Int64 totalsize) in E:\BjXinzheProj\SmartCloudGateWay\SmartCloudGateWay\GlusterFs\CifsGlusterfsRepositily.cs:line 80

SMB 2.0 Support

Hi ume05rw,

Thanks for this library!
Me and my team are glad to have found this, but we are seriously concerned about the SMB 2.0 support. For us and our costumers it is highly important to support smb 2.0+ since MS is recommending to stop using SMB 1.0.
So, does the current version supports SMB 2.0+ and if not, do you plan to add this support in the near future? It would be great!

0.2.12 nuget-package not installable

If i try to install the current stable version ( at thi time it is 0.2.12 ), i get an error that this version is not compatible with netstandard2.0 and it does not support any targetframework. Installing version 0.2.11 is ok, no problem. I hav Xamarin.Forms 3.1.xx and Android 8.1 and Netstandard 2.0 as target

CancellationToken overload for GetOutputStreamAsync

Hello i am using SharpCifs and i am encountering problems when for some reason the writing operation blocks and i wanted to know if there is any way for the library to support an overload for GetOutputStreamAsync with a CancellationToken.

Current method:

public static Task<InputStream> GetInputStreamAsync(this SmbFile smbFile);

Desired overload:
public static Task<InputStream> GetInputStreamAsync(this SmbFile smbFile,CancellationToken token);

SMB-File does not take data

I can create a new SMB-File with the below code, but for unknown reason, the text doesn't get written to the file... but I get no error either.

SharpCifs.Smb.NtlmPasswordAuthentication auth = new SharpCifs.Smb.NtlmPasswordAuthentication(null, username, password);
string urlWrite = "smb://" + serverAddress + "/" + sharename + "/my_text.txt";
SharpCifs.Smb.SmbFile writeFile = new SharpCifs.Smb.SmbFile(urlWrite, auth);
if (!writeFile.Exists())
    writeFile.CreateNewFile();

using (SharpCifs.Util.Sharpen.OutputStream writeStream = file.GetOutputStream())
{
    writeStream.Write(System.Text.Encoding.UTF8.GetBytes("Hello!"));
    writeStream.Flush();
    writeStream.Close();
}

Dual License

is it possible to provide this lib in dual license mode?
And provide a version with MIT or Apache 2.0 license?

Smb Connection fail

Hi,
if I'm opening my App I'd like to connect to smb server (Works). I also want to change the user/password that access to the smb server. And thats where I get to my problem. Even if the user/password is incorrect, I still can upload files. If I watch the file information on smb, those files were created with the previous, successfully logged in user.

My question: How am I able to disconnect and completely log off with the user credentials?

I already tried the following:
SmbFile.Initialize();
SmbSession.ClearCachedConnection();
SmbTransport.ClearCachedConnections();
SmbTransport.ClearCachedConnections(true);

I'm trying the procedure doing the following:

I've got a method for testing, if the connection is successfull. The method is giving me a boolean.

try
                {
                    SharpCifs.Config.SetProperty("jcifs.smb.client.username", user);
                    SharpCifs.Config.SetProperty("jcifs.smb.client.password", password);
                    SharpCifs.Config.SetProperty("jcifs.smb.client.responseTimeout", "2000");

                    var smb1 = new SmbFile("smb://" + path);

                    if (smb1.Exists())
                    {
                        var test = new SmbFile("smb://" + path+"ConnectionTest"+new Random().Next(0, 1000)+".txt");
                        test.CreateNewFile();

                        var writeStream = test.GetOutputStream();

                        writeStream.Write(Encoding.UTF8.GetBytes("Connection successfull"));
                        writeStream.Dispose();

                        return true;
                    }
                    return false;
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e.StackTrace);
                    return false;
                }

I also write the variable content in debug, to see whats the variables value. The same thing I do for the SharpCifs Config Properties. Those values looks how they supposed to look.

Hope you can help me quickly.

Have a nice day.

SharpCifs.Smb.SmbException: Failed to connect, 0.0.0.0<00>/192.168.0.26 [ 192.168.0.26:1733 --> 192.168.0.26:445 ]

Hi,

I made a folder on my Win10 and configurated a share with credentials for a local windows user. Then I tried to list the files in this share.
This is the exception I get:

SharpCifs.Smb.SmbException
  HResult=0x80131620
  Nachricht = Failed to connect, 0.0.0.0<00>/192.168.0.26  [ 192.168.0.26:1733 --> 192.168.0.26:445 ]
  Quelle = SharpCifs.Std
  Stapelüberwachung:
   at SharpCifs.Smb.SmbTransport.Connect()
   at SharpCifs.Smb.SmbTree.TreeConnect(ServerMessageBlock andx, ServerMessageBlock andxResponse)
   at SharpCifs.Smb.SmbFile.DoConnect()
   at SharpCifs.Smb.SmbFile.Connect()
   at SharpCifs.Smb.SmbFile.Connect0()
   at SharpCifs.Smb.SmbFile.GetType()
   at SharpCifs.Smb.SmbFile.DoEnum(List`1 list, Boolean files, String wildcard, Int32 searchAttributes, ISmbFilenameFilter fnf, ISmbFileFilter ff)
   at SharpCifs.Smb.SmbFile.ListFiles(String wildcard, Int32 searchAttributes, ISmbFilenameFilter fnf, ISmbFileFilter ff)
   at SharpCifs.Smb.SmbFile.ListFiles()
   at TestCifs.Program.Main(String[] args) in C:\...:line 13

  Diese Ausnahme wurde ursprünglich von dieser Aufrufliste ausgelöst:
    [Externer Code]

Innere Ausnahme 1:
TransportException: transport closed in negotiate

Innere Ausnahme 2:
TransportException: transport closed in negotiate

Innere Ausnahme 3:
IOException: transport closed in negotiate

I tried it with the name of my computer and with the IP. I also turned my local firewall off. But I still get the same exceltion.

Here my code:

    class Program
    {
        static void Main(string[] args)
        {
            var auth1 = new NtlmPasswordAuthentication(null, "testtest", "testtest");
            var folder = new SmbFile("smb://192.168.0.26/UncPathTest", auth1);

            foreach (SmbFile item in folder.ListFiles())
            {
                Console.WriteLine(item.GetName());
            }

            Console.WriteLine("This is the end");
        }
    }

What I'm doing wrong?

SharpCifs.Smb.SmbException : This client does not support the negotiated dialect.

hello, everyone

I tried to connect to the target file,using new SmbFile("smb://{userName}:{password}@{serverIp}/{shareName}").
The test was successful two weeks ago and failed today.

What is the reason for this anomaly.

Error description:
SharpCifs.Smb.SmbException : Failed to connect, 0.0.0.0<00>/192.168.1.20 [ 192.168.1.16:62452 --> 192.168.1.20:445 ]
---- SharpCifs.Util.Transport.TransportException : This client does not support the negotiated dialect.
-------- SharpCifs.Util.Transport.TransportException : This client does not support the negotiated dialect.
------------ SharpCifs.Smb.SmbException : This client does not support the negotiated dialect.

Thank U.

Strong naming

Hi

Could you sign / add strong name to your assembly so it can be referenced by strong named assemblies ?

Thx :)

((Stream)OutputStream).CanSeek is true, but Seek() throws an exception

    private void btnTest_Click(object sender, EventArgs e)
    {
        var url = $"smb://{txtPath.Text}/test.test";
        var file = new SmbFile(url, _auth);
        file.CreateNewFile();
        var ostream = file.GetOutputStream();
        ostream.Write(123);
        ostream.Write(123);
        var stream = (Stream)ostream;
        Debug.WriteLine(stream.CanSeek); //stream.CanSeek is true
        stream.Seek(0, SeekOrigin.Begin); //strangely enough this works
        stream.Seek(0, SeekOrigin.End); //throws an exception:

//Exception thrown: 'System.NullReferenceException' in SharpCifs.Std.dll
//An unhandled exception of type 'System.NullReferenceException' occurred in SharpCifs.Std.dll
//Object reference not set to an instance of an object.
StackTrace:
at SharpCifs.Util.Sharpen.WrappedSystemStream.get_Length()
at SharpCifs.Util.Sharpen.WrappedSystemStream.Seek(Int64 offset, SeekOrigin origin)
at NetShareTest.Form1.btnTest_Click(Object sender, EventArgs e)
}

Looks like the CanSeek property of Stream object which is returned by implicit operator Stream should return false always. Or Seek() method should work properly and should not throw any exception.

How to check file is written

Hi,

nice work you guys :-)

Just one question, is there a way to make sure the file has ben written 100% before reading?

Do I need to look at the file size and when no change for at while, it's done?

Best,
CU

GetShareSecurity() returns null GetSecurity() catches timeout

I'm calling GetShareSecurity(); method (both with false/true) on a smb share and it always returns null despite using Administrator credentials when loging to smb windows server. I'm able to list all the the shares using ListFiles() without troubles. Using GetSecurity() I always catch timeout exception:

Transport1 timedout waiting for response to SmbComSessionSetupAndX[command=SMB_COM_SESSION_SETUP_ANDX,received=False,errorCode=0,flags=0x0018,flags2=0xC803,signSeq=0,tid=0,pid=41146,uid=0,mid=23,wordCount=12,byteCount=69,andxCommand=0xFF,andxOffset=0,snd_buf_size=16644,maxMpxCount=10,VC_NUMBER=1,sessionKey=0,lmHash.length=0,ntHash.length=0,capabilities=-2147479468,accountName=,primaryDomain=,NATIVE_OS=Windows,NATIVE_LANMAN=jCIFS]

Could anyone help on that. Here simplified code snippet. I can provide more details if needed:

            var smbPath = "smb://" + targetIP;
            var authOption = new NtlmPasswordAuthentication("Administrator:XXX") 
            var smbShares = new SmbFile(smbPath, authOption);
                try
                {
                    var shares = smbShares.ListFiles();
                    foreach (var share in shares)
                    {                
                        Console.WriteLine($"Share Name = {share.GetName()}"); //works
                        var sSec = share.GetShareSecurity(true); //always null though
                        var test = share.GetSecurity(); //always response timeout
                    }
                }
                catch (Exception e)
                {}

File author

Its possible to get File Author? NTAccount?

Connection problem, NullReferenceException

Hi!
Im doing following, which I have verifed in Windows that works.
I'm testing this in my UWP application as a part of the Xamarin solution.

var serverAddress = @"192.168.1.150\Downloads\"; 
var _fileRepository = new SmbFile($"smb:\\{serverAddress}");
var canRead = _fileRepository.CanRead();

I then get following exception inside your code:

{System.NullReferenceException: Object reference not set to an instance of an object.
at SharpCifs.Smb.SmbFile.GetType()
at SharpCifs.Smb.SmbFile.CanRead()

异常未捕捉到导致死循环

当samba服务断开或者异常的时候,请求连接时,
var remote = (IPEndPoint)this.Socket?.RemoteEndPoint;
RemoteEndPoint 强制类型的转码类是 EndPoint 出现异常,导致异常类SmbException没有捕捉到,ConnectionState不能重置为0,导致程序在下一次连接时,在
while (ConnectionState != 0)
{
if (ConnectionState == 2 || ConnectionState == 3)
{
// connected or disconnecting
return;
}
try
{
Runtime.Wait(Session.transport,2000);
}
catch (Exception ie)
{
throw new SmbException(ie.Message, ie);
}
}
这边一直死循环,阻塞进程,另外Runtime.Wait(Session.transport,2000);中,等待超时应该设置一个超时间,这样程序更灵活一点。
望修复,感谢开源。

mbFile.Initialize() Error

In the iterator from line 100 of SmbTransport.cs, it is an error because it is changing the collection. This will not be able to re-initialize SmbFile when changing the client's IP.

(SmbTransport.csの100行目からのイテレーターの中で、コレクションを変更しているので、エラーとなります。これによってclientのIPを変更する場合のSmbFileの再初期化ができません。)

Connection problem after setting wifi enabled

Hello,

I have the following problem.
If I start my application on an android smart phone when wifi is off then it cannot connect to the shared folder and it is OK. But if I turn on the wifi without restarting my app then it also cannot connect, the exception is the same as when wifi is off. I tried to call these ones but didn't help:
SmbFile.Initialize();
SmbTransport.ClearCachedConnections();
SmbSession.ClearCachedConnections();
SmbTransport.ClearCachedConnections(true);

What can I do in this case?

(If I start my app when wifi is on then all things work. After turning it off then things don't work and it is OK and after turning it on again then things work again.)

Failed to connect: 0.0.0.0<00>/192.168.1.218

I've followed the instructions, but all of the examples produce the same error. I am able to connect to the share from a Mac, other Windows machines, and from another app, AirDisk Pro. The share is on a Windows 10 Professional machine on a Windows Domain. Any ideas or known issues?

Failed to connect: 0.0.0.0<00>/192.168.1.218
2017-11-11 19:11:42.683 NetworkFileSync3[6981:3166492]   at SharpCifs.Smb.SmbTransport.Connect () [0x00025] in <4c9231bb48bc4e91ad96cf2ef3ec2de1>:0 
  at SharpCifs.Smb.SmbTree.TreeConnect (SharpCifs.Smb.ServerMessageBlock andx, SharpCifs.Smb.ServerMessageBlock andxResponse) [0x00162] in <4c9231bb48bc4e91ad96cf2ef3ec2de1>:0 

Examples should use `using`

Wrapping code in a using block is the standard way in .NET to free up resources.

For example, instead of the current sample code for reading a file, how about this:

Read a File:

//using System;
//using System.IO;
//using System.Text;
//using SharpCifs.Smb;

//Get target's SmbFile.
var file = new SmbFile("smb://UserName:Password@ServerIP/ShareName/Folder/FileName.txt");

//Get readable stream.
using (var readStream = file.GetInputStream()) {

    //Create reading buffer.
    var memStream = new MemoryStream();

    //Get bytes.
    ((Stream)readStream).CopyTo(memStream);
}

Console.WriteLine(Encoding.UTF8.GetString(memStream.ToArray()));

ListFiles does not return control

Hi,
Some background process automatically write files in shared directory (~5 files per second)
When I'm trying to get list files in this directory via "ListFiles()", the function
falls into an infinite loop. (see class SmbFile.DoFindFirstNext )

internal virtual void DoFindFirstNext(...)
{
  ...
 for (;;)
 {
    if (resp.IsEndOfSearch || resp.NumEntries == 0)
    {
              break; // <- never break while "some background process" working
    }
 }
}

Can you make overloaded function "ListFiles" that define maxCount of reading items in directory?

My simple-working example is:

public virtual SmbFile[] ListFiles(int maxCount)
{
            _maxCount = maxCount;
            return ListFiles("*", AttrDirectory | AttrHidden | AttrSystem, null, null);
}

internal virtual void DoFindFirstNext(...)
{
     ...
    if (resp.IsEndOfSearch || resp.NumEntries == 0 || list.Count > _maxCount)
    {
          break;
    }
}

Best Regards

"Connect & Auth:" examples return true for the base domain of any local IP

Code (Mostly from http://sharpcifsstd.dobes.jp/ with a slight modification)

        SharpCifs.Config.SetProperty("jcifs.smb.client.lport", "8137");
        string invalidIP = "192.168.0.240"; // Make sure there are no machines on your local network with the specific IP
        //string to Auth-Object.
        Console.WriteLine("SMB1");
        var auth1 = new NtlmPasswordAuthentication("anonymous:Password");
        var smb1 = new SmbFile($"smb://{invalidIP}/ ", auth1);
        Console.WriteLine($"exists? {smb1.Exists()}");
        //3 string to Auth-Object.
        Console.WriteLine("SMB2");
        var auth2 = new NtlmPasswordAuthentication(null, "anonymous", "Password");
        var smb2 = new SmbFile($"smb://{invalidIP}/", auth2);
        Console.WriteLine($"exists? {smb2.Exists()}");

        //Insert auth info into URL.
        Console.WriteLine("SMB3");
        var smb3 = new SmbFile($"smb://Username:Password@{invalidIP}/");
        Console.WriteLine($"exists? {smb3.Exists()}");
        //You can store authentication information in SharpCifs.Std.
        SharpCifs.Config.SetProperty("jcifs.smb.client.username", "UserName");
        SharpCifs.Config.SetProperty("jcifs.smb.client.password", "Password");

        Console.WriteLine("SMB4");

        var smb4 = new SmbFile($"smb://{invalidIP}/");
        Console.WriteLine($"exists? {smb4.Exists()}");`

Output:

SMB1
exists? True
SMB2
exists? True
SMB3
exists? True
SMB4
exists? True

Non-existent devices should obviously lack SMB1/2/3/4 support

WrappedSystemStream should override Dispose() to dispose internal stream.

Summary : InputStream implicitly cast itself to System.IO.Stream. This indicates the given back stream should free its internal resource when disposing, but WrappedSystemStream not override Dispose method nor dispose it's internal stream after using.


まず初めに、このライブラリを共有して頂きありがとうございます。
日本人の方のようですので日本語でIssueを上げさせて頂きます。

InputStreamStreamへの暗黙的な型変換を用意しています。
しかしWrappedSystemStreamDispose時にInputStreamDisposeをコールしないため、これに起因して下記のようなコードではInputStreamが解放されなくなってしまいます。
暗黙的に型変換できるということは、通常はアップキャスト(正確にはこの場合違いますが)してから責任を移譲した場合、Stream型として扱っても内部リソースを開放できる必要があると思います。

Task<Stream> OpenReadStream()
{
    var smbFile = new SmbFile(...);
    return await smbFile.GetInputStreamAsync();
}

using (var stream = await OpenReadStream())
{
    // do something here 
} // this will not dispose InputStream

上記はC#としては自然なコードだと思っています。
C#の他のリソースとの連携を考えると、Stream型の方が都合がよく、可読性も向上します。
しかし、現在のコードだとInputStreamが開いたままになってしまうため、戻り値をInputStreamにせざるを得ません。

意図的にCloseについてもoverrideせずキャストされたStreamCloseした時のInputStream解放を避けているようですが、何か理由があるのでしょうか?

CreateNewFile and Log question

Hello,

I am having an issue with the CreateNewFile method. It seems to be taking around a minute to create a new file. I was also wondering if the log file gets written anywhere? I am trying to look in the log file to see if I can see why it is taking so long.

Best,
Paul

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.