hierynomus / smbj

Server Message Block (SMB2, SMB3) implementation in Java
Other
713 stars 180 forks source link

DiskShare.openFile(...) seems to delete the files contents by default?! #786

Closed DanskerDave closed 1 year ago

DanskerDave commented 1 year ago

When opening a file, the default SMB2CreateDisposition seems to be to delete its contents. Thats scary! As far as I can see, the default is SMB2CreateDisposition.FILE_SUPERSEDE.

A couple of Issues.:

My code follows below...

All the best, Dave

package smbj.read;

import java.io.IOException;
import java.util.EnumSet;

import com.hierynomus.msdtyp.AccessMask;
import com.hierynomus.msfscc.FileAttributes;
import com.hierynomus.mssmb2.SMB2CreateDisposition;
import com.hierynomus.mssmb2.SMB2CreateOptions;
import com.hierynomus.mssmb2.SMB2ShareAccess;
import com.hierynomus.smbj.SMBClient;
import com.hierynomus.smbj.auth.AuthenticationContext;
import com.hierynomus.smbj.share.DiskShare;

public class SmbReadFileAnon {

    public static void main(final String[] args) throws IOException {

        try(final     var client  = new SMBClient();
            final     var conn    = client.connect("hostname"))
        {
            final     var context = new AuthenticationContext("userid", "password".toCharArray(), null);

            try(final var session = conn.authenticate(context);
                final var share   = (DiskShare) session.connectShare("shareName"))
            {
                final var accessMaskRead       =                      EnumSet.of(AccessMask           .GENERIC_READ);
                final var fileAttrNotDirectory = EnumSet.complementOf(EnumSet.of(FileAttributes       .FILE_ATTRIBUTE_DIRECTORY));
                final var shareAccessRead      =                      EnumSet.of(SMB2ShareAccess      .FILE_SHARE_READ);
                final var optionSequential     =                      EnumSet.of(SMB2CreateOptions    .FILE_SEQUENTIAL_ONLY);
                final var dispositionOpen      =                                 SMB2CreateDisposition.FILE_OPEN;

                final var smbjFile = share.openFile("/path/readMe.txt", accessMaskRead, fileAttrNotDirectory, shareAccessRead, null, optionSequential);
                final var bytes    = smbjFile.getInputStream().readAllBytes();

                System.out.println("Contents.: " + new String(bytes));
            }
        }
    }
}
LeafyLappa commented 1 year ago

Thumbs up as this made me spend a lot of time until I came across this issue: https://github.com/hierynomus/smbj/issues/166

DanskerDave commented 1 year ago

Thumbs up as this made me spend a lot of time until I came across this issue: #166

Its certainly quite unique in my 45 years or so in this business: first time I've ever experienced a file opened with read intent being overwritten!

hierynomus commented 1 year ago

I've merged a fix to the master branch.