GithubHelp home page GithubHelp logo

marsaud-smb2's Introduction

SMB2 Client for Node.js

Node compatibility License PackagePhobia

Package Version Build Status Latest Commit

Introduction

This library is a simple implementation of SMB2 for Node.js. It allows you to access a SMB2 share as if you were using the native fs library.

The development is still at an experimental stage and should not be yet considered for production environment.

Installation

npm install -S @marsaud/smb2

API

Asynchronicity

All async methods can be used with Node-style callbacks or return promises if none is passed:

// Node-style callback
smb2Client.readFile('foo.txt', function(err, content) {
  if (err) throw err;
  console.log(content);
});

// With promise, ideal with ES2017 async functions
const content = await smb2Client.readFile('foo.txt');
console.log(content);

Construction

var smb2Client = new SMB2 ( options )

The SMB2 class is the constructor of your SMB2 client.

the parameter options accepts this list of attributes:

  • share: the share you want to access
  • domain: the domain of which the user is registered
  • username: the username of the user that access the share
  • password: the password
  • port (optional): default 445, the port of the SMB server
  • packetConcurrency (optional): default 20, the number of simultaneous packet when writing / reading data from the share
  • autoCloseTimeout (optional): default 10000, the timeout in milliseconds before to close the SMB2 session and the socket, if set to 0 the connection will never be closed unless you do it

Example:

// load the library
var SMB2 = require('@marsaud/smb2');

// create an SMB2 instance
var smb2Client = new SMB2({
  share: '\\\\000.000.000.000\\c$',
  domain: 'DOMAIN',
  username: 'username',
  password: 'password!',
});

Connection management

The connection to the SMB server will be automatically open when necessary.

Unless you have set autoCloseTimeout to 0 during client construction, the connection will be closed automatically.

If you have set autoCloseTimeout to 0, the connection MUST be closed manually:

smb2Client.disconnect();

High level methods

smb2Client.exists ( path, callback )

Test whether or not the given path exists by checking with the file system.

Example:

smb2Client.exists('path\\to\\my\\file.txt', function(err, exists) {
  if (err) throw err;
  console.log(exists ? "it's there" : "it's not there!");
});

smb2Client.mkdir ( path, [mode], callback )

Asynchronous mkdir(2): create a directory.

mode defaults to 0o777.

Example:

smb2Client.mkdir('path\\to\\the\\directory', function(err) {
  if (err) throw err;
  console.log('Directory created!');
});

smb2Client.readdir ( path, [options], callback )

  • path String
  • options Object
    • encoding String | Null default = null
  • callback Function

Asynchronous readdir(3): reads the contents of a directory.

The result is an array of the names of the files in the directory excluding '.' and '..'.

If you want the response to include stats, you need to pass the stats: true. Response will be an Array of this form:

[
    {
        name: String,
        birthtime: Date,
        mtime: Date,
        atime: Date,
        ctime: Date,
        isDirectory(): boolean
    },
...
]

Example:

smb2Client.readdir('Windows\\System32', function(err, files) {
  if (err) throw err;
  console.log(files);
});

smb2Client.stat ( path, callback )

  • path String
  • callback Function

Asynchronous stat: query stats of a directory or file.

Response will be an object with the following structure :

{
    birthtime: Date,
    mtime: Date,
    atime: Date,
    ctime: Date,
    isDirectory(): boolean
}

smb2Client.readFile ( path, [options], callback )

  • path String
  • options Object
    • encoding String | Null default = null
  • callback Function

Asynchronously reads the entire content of a file.

Example:

smb2Client.readFile('path\\to\\my\\file.txt', function(err, content) {
  if (err) throw err;
  console.log(content);
});

If no encoding is specified, then the raw buffer is returned.

smb2Client.rename ( oldPath, newPath, [ options, ] callback )

Asynchronous rename(2): rename a file.

smb2Client.rename(
  'path\\to\\my\\file.txt',
  'new\\path\\to\\my\\new-file-name.txt',
  function(err) {
    if (err) throw err;
    console.log('file has been renamed');
  }
);

Existing files are not replaced by default, you need to pass the replace: true option for this use case:

smb2Client.rename(
  'path\\to\\my\\file.txt',
  'path\\to\\existing\\file.txt',
  {
    replace: true
  }
  function(err) {
    if (err) throw err;
    console.log('file has been renamed');
  }
);

smb2Client.rmdir ( path, callback )

Asynchronous rmdir(2): delete an empty directory.

Example:

smb2Client.rmdir('path\\to\\the\\directory', function(err) {
  if (err) throw err;
  console.log('Directory deleted!');
});

smb2Client.unlink ( path, callback )

Asynchronous unlink(2): delete a file.

smb2Client.unlink('path\\to\\my\\file.txt', function(err) {
  if (err) throw err;
  console.log('file has been deleted');
});

smb2Client.writeFile ( filename, data, [options], callback )

  • filename String
  • data String | Buffer
  • options Object
    • encoding String | Null default = 'utf8'
  • callback Function

Asynchronously writes data to a file, replacing the file if it already exists. data can be a string or a buffer.

The encoding option is ignored if data is a buffer.

Example:

smb2Client.writeFile('path\\to\\my\\file.txt', 'Hello Node', function(err) {
  if (err) throw err;
  console.log("It's saved!");
});

smb2Client.truncate ( filename, length, callback )

  • filename String
  • length Number
  • callback Function

Asynchronously truncate a file to a size of precisely length bytes.

Example:

smb2Client.truncate('path\\to\\my\\file.txt', 10, function(err) {
  if (err) throw err;
  console.log("It's truncated!");
});

Streams

smb2Client.createReadStream ( fileName, [options], callback )

Returns a read stream on the file.

Unlike fs.createReadStream, this function is asynchronous, as we need use asynchronous smb requests to get the stream.

Example:

smb2Client.createReadStream('path\\to\\the\\file', function(err, readStream) {
  if (err) throw err;
  var writeStream = fs.createWriteStream('localFile');
  readStream.pipe(writeStream);
});

Supported options:

  • autoClose: whether the fd should be closed at the end or on error, default true
  • end: offset in the file after which to stop reading, default Infinity
  • fd: if specified, the path will be ignored and this opened file will be used instead
  • flags: see Node documentation, default 'r'
  • start: offset in the file from which to start reading, default 0

smb2Client.createWriteStream ( fileName, [options], callback )

Returns a write stream on the file.

Unlike fs.createWriteStream, this function is asynchronous, as we need use asynchronous smb requests to get the stream.

Example:

smb2Client.createWriteStream('path\\to\\the\\file', function(err, writeStream) {
  if (err) throw err;
  var readStream = fs.createReadStream('localFile');
  readStream.pipe(writeStream);
});

Supported options:

  • autoClose: whether the fd should be closed at the end or on error, default true
  • fd: if specified, the path will be ignored and this opened file will be used instead
  • flags: see Node documentation, default 'wx'
  • start: offset in the file from which to start writing, default 0

Low-level API

smb2Client.open('path\\to\\the\\file', 'r', function(err, fd) {
  if (err) throw err;

  smb2Client.read(
    fd, // file descriptor
    Buffer.alloc(10), // buffer where to store the data
    0, // offset in the buffer
    10, // number of bytes to read
    0, // offset in the file
    function(err, bytesRead, buffer) {
      smb2Client.close(fd, function() {});

      if (err) throw cb(err);
      console.log(bytesRead, buffer);
    }
  );
});

smb2Client.open('path\\to\\the\\file', 'w', function(err, fd) {
  if (err) throw err;

  smb2Client.write(
    fd, // file descriptor
    Buffer.from('foo bar\n'), // data to write to the file
    0, // offset in the buffer
    10, // number of bytes to write
    0, // offset in the file
    function(err, bytesWritten, buffer) {
      smb2Client.close(fd, function() {});

      if (err) throw cb(err);
      console.log(bytesWritten);
    }
  );
});

This API is modeled after Node's fs module.

Note: be careful of autoCloseTimeout with this process as it is not intended to cover multiple method calls, you should set it to 0 and manually disconnect().

Contributors

References

The[MS-SMB2]: Server Message Block (SMB) Protocol Versions 2 and 3
Copyright (C) 2014 Microsoft
http://msdn.microsoft.com/en-us/library/cc246482.aspx

License

(The MIT License)

Copyright (c) 2013-2014 Benjamin Chelli <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

marsaud-smb2's People

Contributors

bchelli avatar bhsdodo avatar bitdeli-chef avatar ghemid-mohamed avatar jalfonso avatar jpogas avatar julien-f avatar marsaud avatar nerminator avatar niels-be avatar nraynaud avatar pkeuter avatar svatal avatar vdiez avatar wescoeur 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

marsaud-smb2's Issues

Error STATUS_FILE_CLOSED after pipe stream created with createReadStream

Hi,

I have an error when i'm reading list of file using readstream.
I have a loop on all file of a dir.
For each file I create a read stream that I pipe to a csv parser streamwritter (https://www.npmjs.com/package/csv-parser).
File is read well but when at the end of loop an error STATUS_FILE_CLOSED occures :

[...]

for (let file of files) {
            try {
                if(file.isDirectory())
                {
                    continue;
                }
                var rs = await smb2Client.createReadStream('dummy\\path\\test\\' + file.name,);
                rows.push(...await manageCsvFile(rs));
            } catch (e) {
                console.log('error on file' + file.name, e)
            }
}
[...]

--------

async function manageCsvFile(rs) {
    let rows = [];
    var fd = rs.pipe(csv({
        separator: ';'
    }));
    var end = new Promise(function(resolve, reject) {
        fd.on('data', (row) => {
            rows.push(row);
        })
        fd.on('end', () => {
            console.log('CSV file successfully processed');
        })
        fd.on('close', () => {
            console.log('Stream has been destroyed and file has been closed');
            resolve();
        });
    });
    await end;
    return rows;
}

----ERROR Message

"errorType": "Error",
  "errorMessage": "STATUS_FILE_CLOSED (0xC0000128) : An I/O request other than close and several other special case operations was attempted using a file object that had already been closed.",
  "trace": [
    "Error: STATUS_FILE_CLOSED (0xC0000128) : An I/O request other than close and several other special case operations was attempted using a file object that had already been closed.",
    "    at SMB2Forge.request (/var/task/node_modules/@marsaud/smb2/lib/tools/smb2-forge.js:22:15)",
    "    at Readable.stream._destroy (/var/task/node_modules/@marsaud/smb2/lib/api/createReadStream.js:42:9)",
    "    at Readable.destroy (internal/streams/destroy.js:39:8)",
    "    at endReadableNT (internal/streams/readable.js:1350:16)",
    "    at processTicksAndRejections (internal/process/task_queues.js:82:21)"
  ]

Can you help me on this issue ?
Best regards

Implement SMB signing

Hi, I was looking around at this library for a project and found an issue with SMB signing not being supported.

We were getting this error when trying to access any SMB shares: Failure: STATUS_ACCESS_DENIED (0xC0000022) : {Access Denied} A process has requested access to an object but has not been granted those access rights. I found we had a group policy enabled on the file server: Computer Configuration > Windows Settings > Security Settings > Local Policies > Security Options > Microsoft network server: Digitally sign communications (always). After I disabled that policy, I was able to access the shares.

Any thoughts? Thank you!

npm released version 0.13 does not support overwriting existing files with stream

Error when trying to do smb2Client.createWriteStream on an already existing file. According to the documentation it should just overwrite without error.

{ Error: STATUS_OBJECT_NAME_COLLISION (0xC0000035) : The object name already exists.
    at SMB2Forge.request (/node_modules/@marsaud/smb2/lib/tools/smb2-forge.js:22:15)
    at module.exports.createWriteStream (/node_modules/@marsaud/smb2/lib/api/createWriteStream.js:77:5)
    at /node_modules/@marsaud/smb2/lib/tools/smb2-connection.js:52:21
    at /node_modules/@marsaud/smb2/lib/tools/smb2-connection.js:147:8
    at /node_modules/@marsaud/smb2/lib/tools/smb2-connection.js:116:25
    at Object.<anonymous> (/node_modules/@marsaud/smb2/lib/tools/message.js:15:15)
    at Socket.<anonymous> (/node_modules/@marsaud/smb2/lib/tools/smb2-forge.js:71:31)
    at emitOne (events.js:116:13)
    at Socket.emit (events.js:211:7)
    at addChunk (_stream_readable.js:263:12)
  messageName: 'create',

readdir only lists 510 items

Hi, I was wondering why my program kept saying the file doesn't exist while I can confirm that it does in the shared folder. Upon trial and error, I found that the .readdir() function only lists the first 510 items while I have 3002 items in my shared folder and the file I'm looking for is near the bottom.

Is there a way to get the complete list of files using the .readdir() function or at least sort the files in descending order first before getting the list?

Thanks.

TypeError: Cannot read property 'mark' of undefined

below code always results in an error. Installed version is @marsaud/[email protected]

const SMB2 = require('samba2');

// create an SMB2 instance
var smb2Client = new SMB2({
  share:'\\\\10.0.0.5\\incoming'
  , domain:'DOMAIN'
  , username:'user'
  , password:'secret'
});

smb2Client.readdir('.', (err, files) => {
  if (err) throw err;
  console.log(files);
});

TypeError: Cannot read property 'mark' of undefined
    at Object.<anonymous> (/node_modules/samba2/lib/api/createWriteStream.js:1:693)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (/node_modules/samba2/lib/smb2.js:96:57)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (/app.js:6:14)
    at Module._compile (module.js:409:26)

help with implementing QUERY_INFO

trying to make QUERY_INFO command
according to https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-smb2/d623b2f7-a5cd-4639-8cc9-71fa7d9f9ba9
adding structure file:

request: [
    ['StructureSize', 2, 41],
    ['InfoType', 1,0x1],
    ['FileInfoClass', 1, 0x12], 
    ['OutputBufferLength', 4, 0x00010000],
    ['InputBufferOffset', 2, 0],
    ['Reserved', 2, 0],
    ['InputBufferLength', 4, 0],
    ['AdditionalInformation', 4, 0],
    ['Flags', 1, 0],
    ['FileId', 16],
    ['Buffer', "InputBufferLength"],
  ],

but server respond with
STATUS_INVALID_PARAMETER (0xC000000D) : An invalid parameter was passed to a service or function.

where I'm wrong?

Multiple connections in same time

I have this code:

const smbClient = new SMB2({
  share: '\\\\127.0.0.1\\f',
  domain: 'WORKGROUP',
  username: 'user',
  password: 'pass'
});

function downloadFile (path, destination) {
  smbClient.createReadStream(path, function(err, readStream) {
    if (err) throw err;
    var writeStream = fs.createWriteStream(destination);
    readStream.pipe(writeStream);
  });
}

Then I want download two files:

downloadFile('file1.txt', 'f1.txt')
downloadFile('file2.txt', 'f2.txt')

But I get error: Uncaught Error: connect EISCONN 127.0.0.1:445 - Local (127.0.0.1:45618). When I comment one of the function call (or wait for first one to finish), everythings is fine. It seems that the client is creating new connection for every function call instead of use already created one.

Error: connect EINVAL x.x.x.x:445 - Local (x.x.x.x:9516)

This error occurs when I call different API of client twice after initializing smbclient. I guess, every time client initialization, MKDIR or readir or exits... Need to be re initialized, and then call client api., so I tried to initialize autocloseTimeout when setting - > 0, but there was no result. please help me!!!!

Enumerating shares on a host

Currently, I use the external program to collect the shares.

It would be really great to enumerate all the shares from the host in native javascript.
In order to get this information, Microsoft Remote Administration Protocol is needed to be implemented in addition to the smb2 message structure.

Here might be the starting point.
https://msdn.microsoft.com/en-us/library/cc240321.aspx

Based on the documentation, it looks easier than SMB2 negotiation.

After ten failed connections, a message is displayed indicating that the number of connections reaches the upper limit and smb2 is unavailable

const SMB2 = require('@marsaud/smb2');
for(let i = 0;i<19;i++){
this.shareConfig = {
            share: sharePath,
            domain: 'DOMAIN',
            username: opt.username,
            password: opt.password,
            autoCloseTimeout: opt.autoCloseTimeout,
        };
this.remoter = new SMB2(this.shareConfig);
this.remoter.exists('a.txt',(err,value)=>{})
}

if the sharePath is a exist path ,everything is perfect.
if the sharePath is a error or unexist path ,and we try to connect it many times then throw an error,then the process unable to use the smb create connection

Error: STATUS_REQUEST_NOT_ACCEPTED (0xC00000D0) : No more connections can be made to this remote computer at this time because the computer has already accepted the maximum number of connections.

Readme - Example of createWriteStream is wrong

smb2Client.createWriteStream('path\\to\\the\\file', function(err, readStream) {
    if (err) throw err;
    var readStream = fs.createReadStream('localFile');
    readStream.pipe(writeStream);
});

Should be

smb2Client.createWriteStream('path\\to\\the\\file', function(err, writeStream) {
    if (err) throw err;
    var readStream = fs.createReadStream('localFile');
    readStream.pipe(writeStream);
});

Also, in order to use this library it should say
const SMB2 = require("@marsaud/smb2");
instead of
const SMB2 = require("smb2");

How to check if cifs is connected or not?

// create an SMB2 instance
var smb2Client = new SMB2({
share: '\\10.2.153.109',
domain: 'Domain',
username: 'abcb2',
password: '******!',
});
I am getting error stating
the share is not valid

What is mean by share?
Could you please help me with this?

Hello, how can I adjust the upload speed?

Hello, how can I adjust the upload speed?
When using createWriteStream is very slow, writeFile is very fast. But I am a file upload larger than 2GB, which can use createWriteStream . Hope to help thank you.

ACCESS_DENIED

I can list folder, but can't create file or directory.
Meanwhile, I can do everything in my OSx-client with the same login / pass.

Error: STATUS_ACCESS_DENIED (0xC0000022) : {Access Denied} A process has requested access to an object but has not been granted those access rights.

STATUS_USER_SESSION_DELETED

const smbClient = new smb2({
      client: {
        dialect: '3.1.1'
      },
      share: '\\\\'+ip+'\\'+String(remotepath).substring(0,1)+'$',
      domain: 'workgroup',
      username: username,
      password:password
    });
  
    smbClient.readdir((String(remotepath).substring(3)).replace(/\\/g, '\\\\') + "\\\\", function(err, files) {
     if (err) throw err;
      console.log(files.length);
      return files.length
    });

run my code returning the same error:"STATUS_USER_SESSION_DELETED ",i don't know how to fix it,but it run perfectly well before.Thanks for help

Create multiple level folder

Is it possibile to create a multiple level folder like \folder1\folder2\folder3?
Like for fs-extra there is fs.mkdirs.

isDirectory not working

when we call readdir with options : {stats:true}, calling isDirectory for a file in files array is always returning false.

The problem is in tools/stats.js:
line 17:
return attr === DIRECTORY;
should be :
(attr & DIRECTORY) == DIRECTORY

Update base

Curious if you might consider updating the base requirement to node 8.x?

In this way you can eliminate bluebird and babel from the build and dependency chain... also makes testing against the source easier. I'm willing to put in the effort and submit a PR.

Note: was going to do this anyway, I'm diagnosing an issue I'm seeing regarding permissions error with ensureDir. But would rather submit a PR instead of publishing another name-spaced fork.

ACCESS_DENIED

I tried to list all the files in a Windows Share but couldn't, the SMB2 object has this value:
connected: false

Here is a fiddle of my code:

var SMB2 = require('@marsaud/smb2');
let smb2Client = new SMB2({
  share: '\\\\192.168.17.200\\utilisateurs',
  domain: 'domain',
  username: 'username',
  password: 'password',
  port: 445,
});

smb2Client.readdir('.', (err, files) => {
  if (err) throw err;
  console.log(files);
});

And the error stack

Error: STATUS_ACCESS_DENIED (0xC0000022) : {Access Denied} A process has requested access to an object but has not been granted those ac
cess rights.
    at Object.03000000 (/home/davincilord/test/test-smb/node_modules/@marsaud/smb2/lib/tools/message.js:25:21)
    at Socket.<anonymous> (/home/davincilord/test/test-smb/node_modules/@marsaud/smb2/lib/tools/smb2-forge.js:72:31)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:188:7)
    at readableAddChunk (_stream_readable.js:176:18)
    at Socket.Readable.push (_stream_readable.js:134:10)
    at TCP.onread (net.js:551:20)

Connect to Linux (centos) shared folder fails

Hi,
I'm using v9u-smb2 library in nodejs and trying to access shared folder , my Linux doesn't have a domain
I'm trying to access like that :

share: '\\172.18.196.24\samba3_directory',
domain: 'WORKGROUP',
username: 'pmc',
password: 'password' // the real password

I got this error :
STATUS_LOGON_FAILURE (0xC000006D) : The attempted logon is invalid. This is either due to a bad username or authentication information.
at SMB2Forge.request (/home/pmc/tmp/barak/node-smb/node_modules/v9u-smb2/lib/tools/smb2-forge.js:39:15)
at /home/pmc/tmp/barak/node-smb/node_modules/v9u-smb2/lib/tools/smb2-connection.js:108:11

What can be the problem? this library can work with Linux? Except from samba that I installed on Linux and create shared folder , do I need to configure something else?

from other Linux I can access to this shared folder by write on terminal : smbclient \\172.18.196.24\samba3_directory

Decode datetime values

trying to do same as EndOfFile

           for (var i = 0; i < v.length; i++) {
               val += v[i] * Math.pow(2, i * 8);
           }

got "CreationTime": 132221877448853630
which is not valid timestamp

in which format it is transfered

smb2Client.open('test.txt', 'w' ... is error

---------- demo_samba.js

...

smb2Client.open('test.txt', 'w', function(err, fd) {
if (err) throw err;

  smb2Client.write(
      fd, // file descriptor
      Buffer.from('asdf'), // data to write to the file
      0, // offset in the buffer
      10, // number of bytes to write
      0, // offset in the file
      function(err, bytesWritten, buffer) {
          smb2Client.close(fd, function() {});

          if (err) throw cb(err);
          console.log(bytesWritten);
      }
  );

});


`
PS C:\Users\USERNAME\Desktop\node\test\image-download-main> node demo_samba.js
assert.js:383
throw err;
^

AssertionError [ERR_ASSERTION]: The expression evaluated to a falsy value:

assert(offset > 0)

    at module.exports.write (C:\Users\USERNAME\Desktop\node\test\image-download-main\node_modules\@marsaud\smb2\lib\api\write.js:13:5)
    at module.exports.write (C:\Users\USERNAME\Desktop\node\test\image-download-main\node_modules\@marsaud\smb2\lib\tools\auto-promise.js:30:8)
    at C:\Users\USERNAME\Desktop\node\test\image-download-main\demo_samba.js:177:16
    at C:\Users\USERNAME\Desktop\node\test\image-download-main\node_modules\@marsaud\smb2\lib\tools\smb2-connection.js:153:8
    at Object.04000000 (C:\Users\USERNAME\Desktop\node\test\image-download-main\node_modules\@marsaud\smb2\lib\tools\message.js:15:15)
    at Socket.<anonymous> (C:\Users\USERNAME\Desktop\node\test\image-download-main\node_modules\@marsaud\smb2\lib\tools\smb2-forge.js:71:31)
    at Socket.emit (events.js:315:20)
    at addChunk (internal/streams/readable.js:309:12)
    at readableAddChunk (internal/streams/readable.js:284:9)
    at Socket.Readable.push (internal/streams/readable.js:223:10) {
generatedMessage: true,
code: 'ERR_ASSERTION',
actual: false,
expected: true,
operator: '=='
}

`

how to know that cifs connection is established or not?

var SMB2 = require('@marsaud/smb2');
async function m1() {
  // create an SMB2 instance
  var smb2Client = new SMB2({
    share: '***',
        domain: '***',
        username: '**',
        password: '*****',
        autoCloseTimeout:0
  });
  // console.log(smb2Client)
  let ans = await smb2Client;
  console.log('aa',ans)
 smb2Client.readFile('share-apis.txt', function(err, content) {
  if (err) throw err;
  console.log(content.toString());
});
}
m1()  ;

I am getting smbclient object in which connected property is returning false,However,I am able to use smb2client to read file
Output:
cifscapture

SO,I how can i know that connection is established or not.I just want to test the connection whether it is connected successfully or not.
Thanks
Azam

Streaming Video

Does this library support video streaming with createReadStream?

I have 2 file that I've been testing with read stream. A .txt file that I can get to load and read just fine, and a .mp4 file that when I try to read the stream without the start & end parameters it gives me an "Unsupported Plug-in" on Safari. When I give it the start & end parameters it will act like its loading the video but it will just give a spinning icon and nothing happens. Any ideas on what I'm doing wrong?

STATUS_NOT_SUPPORTED (0xC00000BB) : The request is not supported.

[Got the same issue with the node-smb2 package as well]
Got this message when trying to connect to smb server that I don't have access to
The code so far

   smb2Client = new SMB2Original({
      share: '\\\\00.00.00.00\\abc_export$',
      domain: 'domain',
      username: 'user',
      password: 'pwd',
    });


    smb2Client.readdir('\\', (err, files) => {
      if (err) throw err;
      console.log(files);
    });

Error object:

{
    "errorType": "Error",
    "errorMessage": "STATUS_NOT_SUPPORTED (0xC00000BB) : The request is not supported.",
    "code": "STATUS_NOT_SUPPORTED",
    "stack": [
        "Error: STATUS_NOT_SUPPORTED (0xC00000BB) : The request is not supported.",
        "    at Object.01000000 (/var/task/node_modules/smb2/lib/tools/message.js:25:21)",
        "    at Socket.<anonymous> (/var/task/node_modules/smb2/lib/tools/smb2-forge.js:72:31)",
        "    at Socket.emit (events.js:315:20)",
        "    at addChunk (internal/streams/readable.js:309:12)",
        "    at readableAddChunk (internal/streams/readable.js:284:9)",
        "    at Socket.Readable.push (internal/streams/readable.js:223:10)",
        "    at TCP.onStreamRead (internal/stream_base_commons.js:188:23)"
    ]
}

[Edited: I saw another issue with the same code, but can't find the answer from that issue either. Sorry for sort of spamming ]

Base path option

Would be nice to be able to specify a basepath, that other paths are rooted/relative to.

In this way, when creating the smb connection instance, one can reference "/foo" where the basepath is prefixed automatically.

Related: #30

Bug in readstream size compare?

I'm trying out your fork today because I need to stream a 120-ish MB file from a Windows share to s3 and the readable stream never emits an end event. I added some logging code and it might be miscalculating the file size.

My code is similar to this:

smb2Client.createReadStream(filename, function (err, readStream) {
        if (err) {
            LOG.error(`Error creating ReadStream from windows share`, share, filename, err);
            return callback(err);
        }

        let total = 0;
        readStream.on('readable', () => {
            let chunk;
            while (null !== (chunk = readStream.read())) {
                total += chunk.length;
                LOG.info(`total: ${total} row size ${chunk.length} offset ${readStream.offset.toNumber()} filelength: ${readStream.fileLength}`);
            }
        });
});

When the sizes in the LOG.info stop moving, it ends with reading 3080192 but the total size is 119356491

Using the library you are forking, I get the entire file in memory

smb2Client.readFile(filename, function (err, data) {
        if (err) {
            LOG.error(`Error reading from windows share`, share, filename, err);
            return callback(err);
        }
        LOG.info(data.length);
    });

Outputs 119356491

NTLMv2 authentication not working - login fails

A user of my Homey 'Archive Insights' app is running into this problem:

Since Synology DSM 7.0 Beta, NTLMv1 is disabled, which means that SMB does not work to use in Archive Insights to store the backup to a Synology NAS disk.
Saw this in the log file on my Synology “User [username] from [192.168.1.12] failed to log in via [SMB] due to [NTLMv1 not permitted].” when I tested.
I found this information on Synology’s website “NTLMv1 is disabled since DSM 7.0 Beta for security concerns, and only NTLMv2 is supported by default.”

Is NTLMv2 indeed not supported at the moment? If not, can you please add it @marsaud . If it is supported, any hints how to use that when setting up the client?

STATUS_USER_SESSION_DELETED (0xC0000203)

Hey guys,

i´m trying to call this function " smb2Client.createWriteStream(path, {start});"

but i´m receiving this error: Error: STATUS_USER_SESSION_DELETED (0xC0000203) : The remote user session has been deleted.

my client:
const smb2Client: SMB2 = new SMB2({
domain: process.env.NFS_CIFS_DOMAIN || '',
username: process.env.NFS_CIFS_USER || '',
password: process.env.NFS_CIFS_PASS || '',
share: process.env.NFS_CIFS_SHARE || ',
});

do you guys know what is going on????

Looking for maintainers

Hi,

@marsaud and myself were not the original authors of this lib but we forked it for our own usage and tried to fix bugs when we could.

But we are no longer using it and don't have the time to maintain it for the community.

If you are interested in maintaining it, please let me know 🙂

in NodeJS 18.x on Lambda AWS getting the error:0308010C:digital envelope routines::unsupported

When using the package on AWS to connect to an SMB share, I get the following error:

ERROR Uncaught Exception {
"errorType": "Error",
"errorMessage": "error:0308010C:digital envelope routines::unsupported",
"code": "ERR_OSSL_EVP_UNSUPPORTED",
"library": "digital envelope routines",
"reason": "unsupported",
"stack": [
"Error: error:0308010C:digital envelope routines::unsupported",
" at Cipheriv.createCipherBase (node:internal/crypto/cipher:122:19)",
" at Cipheriv.createCipherWithIV (node:internal/crypto/cipher:141:3)",
" at new Cipheriv (node:internal/crypto/cipher:249:3)",
" at Object.createCipheriv (node:crypto:141:10)",
" at /opt/nodejs/node_modules/ntlm/lib/smbhash.js:46:22",
" at Array.forEach ()",
" at lmhashbuf (/opt/nodejs/node_modules/ntlm/lib/smbhash.js:45:20)",
" at Object.encodeType3 (/opt/nodejs/node_modules/ntlm/lib/ntlm.js:106:3)",
" at Object.generate (/opt/nodejs/node_modules/@marsaud/smb2/lib/messages/session_setup_step2.js:14:22)",
" at SMB2Forge.request (/opt/nodejs/node_modules/@marsaud/smb2/lib/tools/smb2-forge.js:16:24)"
]
}

This seems to be related to NODE_OPTIONS:--openssl-legacy-provider, but even after adding this to the lambda (in v.18.x) the error remains.

Checking files by wildcard

Is it possible to search file by wildcard? eg, ABC*.*_final would match ABC._final, ABC.js_final and ABC2019.js_final.

STATUS_LOGON_FAILURE

I can't even get my code to connect with the share at all. I have the right credentials and permissions because I can do the following with the smbclient cli:

smbclient \\\\freenas.corp.XXXXX.com\\tamres -W corp.XXXXX.com -U “rodney.carvalho%XXXXX" -c "ls"

I'm trying to use the following code and just list the directories, but I get an authentication failure.

var SMB2 = require('@marsaud/smb2');

// create an SMB2 instance
var smb2Client = new SMB2({share:'\\\\freenas\\tamres', port: 445, domain:'corp.XXXXX.com', username:"rodney.carvalho", password:'XXXXX'});

smb2Client.readdir('hello', function(err, files){
    if(err) {
      console.log("GOT ERROR HERE!!!")
      throw err;
    }
    console.log('HELLO!');
    console.log(files);
});

Does anyone see anything I'm doing wrong? Thanks in advance.

Error: STATUS_PENDING

const SMB2 = require('@marsaud/smb2');
const fs =require("fs");

const smb2Client = new SMB2({
    share: `\\\\000.000.000.000\\project`,
    domain: 'DOMAIN',
    username: 'username',
    password: 'password',
});

smb2Client.createWriteStream('personal\\test10k.txt', function(err, writeStream) {
    if (err) throw err;
    const readStream = fs.createReadStream('/home/caocong/test10k.txt');
    readStream.pipe(writeStream);
});
/usr/bin/node /home/caocong/workspace/test/index.js
node:events:342
      throw er; // Unhandled 'error' event
      ^

Error: STATUS_PENDING (0x00000103) : The operation that was requested is pending completion.
    at SMB2Forge.request (/home/caocong/workspace/test/node_modules/@marsaud/smb2/lib/tools/smb2-forge.js:22:15)
    at Writable.stream._destroy (/home/caocong/workspace/test/node_modules/@marsaud/smb2/lib/api/createWriteStream.js:55:9)
    at _destroy (node:internal/streams/destroy:72:23)
    at Writable.destroy (node:internal/streams/destroy:64:5)
    at Writable.destroy (node:internal/streams/writable:861:11)
    at errorOrDestroy (node:internal/streams/destroy:242:12)
    at onwriteError (node:internal/streams/writable:422:3)
    at onwrite (node:internal/streams/writable:457:7)
    at /home/caocong/workspace/test/node_modules/@marsaud/smb2/lib/api/createWriteStream.js:40:20
    at Object.<anonymous> (/home/caocong/workspace/test/node_modules/@marsaud/smb2/lib/tools/message.js:19:15)
Emitted 'error' event on Writable instance at:
    at Writable.onerror (node:internal/streams/readable:770:14)
    at Writable.emit (node:events:365:28)
    at emitErrorNT (node:internal/streams/destroy:193:8)
    at emitErrorCloseNT (node:internal/streams/destroy:158:3)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  messageName: 'close',
  params: {
    StructureSize: Buffer(2) [Uint8Array] [ 89, 0 ],
    OplockLevel: Buffer(1) [Uint8Array] [ 0 ],
    Flags: Buffer(1) [Uint8Array] [ 0 ],
    CreateAction: Buffer(4) [Uint8Array] [ 2, 0, 0, 0 ],
    CreationTime: Buffer(8) [Uint8Array] [
      24, 65, 188, 85,
      11, 86, 215,  1
    ],
    LastAccessTime: Buffer(8) [Uint8Array] [
      24, 65, 188, 85,
      11, 86, 215,  1
    ],
    LastWriteTime: Buffer(8) [Uint8Array] [
      24, 65, 188, 85,
      11, 86, 215,  1
    ],
    ChangeTime: Buffer(8) [Uint8Array] [
      24, 65, 188, 85,
      11, 86, 215,  1
    ],
    AllocationSize: Buffer(8) [Uint8Array] [
      0, 0, 0, 0,
      0, 0, 0, 0
    ],
    EndofFile: Buffer(8) [Uint8Array] [
      0, 0, 0, 0,
      0, 0, 0, 0
    ],
    FileAttributes: Buffer(4) [Uint8Array] [ 32, 0, 0, 0 ],
    Reserved2: Buffer(4) [Uint8Array] [ 0, 0, 0, 0 ],
    FileId: Buffer(16) [Uint8Array] [
      199, 131, 249, 165,   0,  0,
        0,   0, 117,  59, 179, 28,
        0,   0,   0,   0
    ],
    CreateContextsOffset: Buffer(4) [Uint8Array] [ 0, 0, 0, 0 ],
    CreateContextsLength: Buffer(4) [Uint8Array] [ 0, 0, 0, 0 ],
    Buffer: Buffer(0) [Uint8Array] []
  },
  code: 'STATUS_PENDING'
}

I found out the reason is async request. But I don't know how to do.

Domain name for local network samba?

I'm sorry if this is not really an issue, more like a normal question due to my inexperience.

But what to fill in domain in the constructor, if your target share is from a local network?
How do you get the domain of a local (LAN) shared?

My PC (client) is a Windows 10, trying to connect to samba from linux through local network.

import samba from '@marsaud/smb2'

let client = new samba({
    share: '\\\\192.168.100.3\\book1',
    domain: 'Domain', // <----- ??
    username: 'dnm13',
    password: 'thisisapassword',
});

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.